diff --git a/demonstrations_v2/tutorial_quantum_circuit_cutting/demo.py b/demonstrations_v2/tutorial_quantum_circuit_cutting/demo.py index bdcfb59cb2..e5118e08c9 100644 --- a/demonstrations_v2/tutorial_quantum_circuit_cutting/demo.py +++ b/demonstrations_v2/tutorial_quantum_circuit_cutting/demo.py @@ -116,41 +116,41 @@ PennyLane implementation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -PennyLane's built-in circuit cutting algorithm, ``qml.cut_circuit``, +PennyLane's built-in circuit cutting algorithm, ``qp.cut_circuit``, takes a large quantum circuit and decomposes it into smaller subcircuits that are executed on a small quantum device. The results from executing the smaller subcircuits are then recombined through some classical post-processing to obtain the original result of the large quantum circuit. -Let’s simulate a "real-world" scenario with ``qml.cut_circuit`` using the +Let’s simulate a "real-world" scenario with ``qp.cut_circuit`` using the circuit below. """ # Import the relevant libraries from functools import partial -import pennylane as qml +import pennylane as qp from pennylane import numpy as np -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(x): - qml.RX(x, wires=0) - qml.RY(0.9, wires=1) - qml.RX(0.3, wires=2) + qp.RX(x, wires=0) + qp.RY(0.9, wires=1) + qp.RX(0.3, wires=2) - qml.CZ(wires=[0, 1]) - qml.RY(-0.4, wires=0) + qp.CZ(wires=[0, 1]) + qp.RY(-0.4, wires=0) - qml.CZ(wires=[1, 2]) + qp.CZ(wires=[1, 2]) - return qml.expval(qml.pauli.string_to_pauli_word("ZZZ")) + return qp.expval(qp.pauli.string_to_pauli_word("ZZZ")) x = np.array(0.531, requires_grad=True) -fig, ax = qml.draw_mpl(circuit)(x) +fig, ax = qp.draw_mpl(circuit)(x) ###################################################################### @@ -167,29 +167,29 @@ def circuit(x): # ``WireCut`` operation at that location as shown below: # -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) # Quantum Circuit with QNode -@qml.qnode(dev) +@qp.qnode(dev) def circuit(x): - qml.RX(x, wires=0) - qml.RY(0.9, wires=1) - qml.RX(0.3, wires=2) + qp.RX(x, wires=0) + qp.RY(0.9, wires=1) + qp.RX(0.3, wires=2) - qml.CZ(wires=[0, 1]) - qml.RY(-0.4, wires=0) + qp.CZ(wires=[0, 1]) + qp.RY(-0.4, wires=0) - qml.WireCut(wires=1) # Cut location + qp.WireCut(wires=1) # Cut location - qml.CZ(wires=[1, 2]) + qp.CZ(wires=[1, 2]) - return qml.expval(qml.pauli.string_to_pauli_word("ZZZ")) + return qp.expval(qp.pauli.string_to_pauli_word("ZZZ")) x = np.array(0.531, requires_grad=True) # Defining the parameter x -fig, ax = qml.draw_mpl(circuit)(x) # Drawing circuit +fig, ax = qp.draw_mpl(circuit)(x) # Drawing circuit ###################################################################### @@ -198,29 +198,29 @@ def circuit(x): # operation is inserted. ``WireCut`` is used to manually mark locations for # wire cuts. # -# Next, we apply ``qml.cut_circuit`` operation as a decorator to the +# Next, we apply ``qp.cut_circuit`` operation as a decorator to the # ``circuit`` function to perform circuit cutting on the quantum circuit. -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) # Quantum Circuit with QNode -@qml.cut_circuit # Applying qml.cut_circuit for circuit cut operation -@qml.qnode(dev) +@qp.cut_circuit # Applying qp.cut_circuit for circuit cut operation +@qp.qnode(dev) def circuit(x): - qml.RX(x, wires=0) - qml.RY(0.9, wires=1) - qml.RX(0.3, wires=2) + qp.RX(x, wires=0) + qp.RY(0.9, wires=1) + qp.RX(0.3, wires=2) - qml.CZ(wires=[0, 1]) - qml.RY(-0.4, wires=0) + qp.CZ(wires=[0, 1]) + qp.RY(-0.4, wires=0) - qml.WireCut(wires=1) # Cut location + qp.WireCut(wires=1) # Cut location - qml.CZ(wires=[1, 2]) + qp.CZ(wires=[1, 2]) - return qml.expval(qml.pauli.string_to_pauli_word("ZZZ")) + return qp.expval(qp.pauli.string_to_pauli_word("ZZZ")) x = np.array(0.531, requires_grad=True) @@ -228,7 +228,7 @@ def circuit(x): ###################################################################### -# Let's explore what happens behind the scenes in ``qml.cut_circuit``. When the +# Let's explore what happens behind the scenes in ``qp.cut_circuit``. When the # ``circuit`` qnode function is executed, the quantum circuit is converted to # a `quantum tape `__ # and then to a graph. Any ``WireCut`` in the quantum @@ -253,7 +253,7 @@ def circuit(x): # separate these fragments into different subcircuit graphs, the # ``fragment_graph()`` function is called to pull apart the quantum circuit # graph as shown in figure 3. The subcircuit graphs are reconverted back to -# quantum tapes and ``qml.cut_circuit`` runs multiple configurations of the +# quantum tapes and ``qp.cut_circuit`` runs multiple configurations of the # 2-qubit subcircuit tapes which are then post-processed to replicate the result # of the uncut circuit. # @@ -286,29 +286,29 @@ def circuit(x): # the classical post-processing overhead is minimized. The main algorithm # behind automatic cut placement is `graph partitioning `__ # -# If ``auto_cutter`` is enabled in ``qml.cut_circuit``, PennyLane makes attempts +# If ``auto_cutter`` is enabled in ``qp.cut_circuit``, PennyLane makes attempts # to find an optimal cut using graph partitioning. Whenever it is difficult to # manually determine the optimal cut location, this is the recommended # approach to circuit cutting. The following example shows this capability # on the same circuit as above but with the ``WireCut`` removed. # -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) -@partial(qml.cut_circuit, auto_cutter=True) # auto_cutter enabled -@qml.qnode(dev) +@partial(qp.cut_circuit, auto_cutter=True) # auto_cutter enabled +@qp.qnode(dev) def circuit(x): - qml.RX(x, wires=0) - qml.RY(0.9, wires=1) - qml.RX(0.3, wires=2) + qp.RX(x, wires=0) + qp.RY(0.9, wires=1) + qp.RX(0.3, wires=2) - qml.CZ(wires=[0, 1]) - qml.RY(-0.4, wires=0) + qp.CZ(wires=[0, 1]) + qp.RY(-0.4, wires=0) - qml.CZ(wires=[1, 2]) + qp.CZ(wires=[1, 2]) - return qml.expval(qml.pauli.string_to_pauli_word("ZZZ")) + return qp.expval(qp.pauli.string_to_pauli_word("ZZZ")) x = np.array(0.531, requires_grad=True) @@ -499,7 +499,7 @@ def qaoa_template(params): gamma, beta = params for i in range(len(graph)): # Apply the Hadamard gates - qml.Hadamard(wires=i) + qp.Hadamard(wires=i) for i, j in top_edges: @@ -507,9 +507,9 @@ def qaoa_template(params): # corresponding to the # green edges in the figure - qml.MultiRZ(2 * gamma, wires=[i, j]) + qp.MultiRZ(2 * gamma, wires=[i, j]) - qml.WireCut(wires=middle_nodes) # Place the wire cut + qp.WireCut(wires=middle_nodes) # Place the wire cut for i, j in bottom_edges: @@ -517,10 +517,10 @@ def qaoa_template(params): # corresponding to the # purple edges in the figure - qml.MultiRZ(2 * gamma, wires=[i, j]) + qp.MultiRZ(2 * gamma, wires=[i, j]) for i in graph.nodes(): # Finally, apply the RX gates - qml.RX(2 * beta, wires=i) + qp.RX(2 * beta, wires=i) ###################################################################### @@ -532,13 +532,13 @@ def qaoa_template(params): all_wires = list(range(len(graph))) -with qml.queuing.AnnotatedQueue() as q: +with qp.queuing.AnnotatedQueue() as q: qaoa_template(optimal_params) - qml.sample(wires=all_wires) + qp.sample(wires=all_wires) tape = QuantumTape.from_queue(q) -fig, _ = qml.drawer.tape_mpl(tape) +fig, _ = qp.drawer.tape_mpl(tape) fig.set_size_inches(12, 6) @@ -548,24 +548,24 @@ def qaoa_template(params): # # To run fragment subcircuits and combine them into a finite-shot estimate # of the optimal cost function using the Pauli cut method, we can use -# built-in PennyLane functions. We simply use the ``qml.cut_circuit_mc`` +# built-in PennyLane functions. We simply use the ``qp.cut_circuit_mc`` # transform and everything is taken care of for us. # -# Note that we have already introduced the ``qml.cut_circuit`` transform +# Note that we have already introduced the ``qp.cut_circuit`` transform # in the previous section. The ``_mc`` appendix stands for Monte Carlo and # is used to calculate finite-shot estimates of observables. The -# observable itself is passed to the ``qml.cut_circuit_mc`` transform as a +# observable itself is passed to the ``qp.cut_circuit_mc`` transform as a # function mapping a bitstring (circuit sample) to a single number. # -dev = qml.device("default.qubit", wires=all_wires) +dev = qp.device("default.qubit", wires=all_wires) -@partial(qml.cut_circuit_mc, classical_processing_fn=qaoa_cost) -@qml.qnode(dev) +@partial(qp.cut_circuit_mc, classical_processing_fn=qaoa_cost) +@qp.qnode(dev) def qaoa(params): qaoa_template(params) - return qml.sample(wires=all_wires) + return qp.sample(wires=all_wires) ###################################################################### @@ -580,7 +580,7 @@ def qaoa(params): pauli_cost_values = np.zeros_like(shot_counts, dtype=float) for i, shots in enumerate(shot_counts): - pauli_cost_values[i] = qml.set_shots(qaoa, int(shots))(optimal_params) + pauli_cost_values[i] = qp.set_shots(qaoa, int(shots))(optimal_params) ###################################################################### @@ -593,7 +593,7 @@ def qaoa(params): # As noted earlier, the easiest way to mathematically represent the # randomized channel-based method is to write down Kraus operators for the # relevant channels, :math:`\Psi _0` and :math:`\Psi _1.` Once we have -# represented them in explicit matrix form, we can simply use ``qml.QubitChannel``. +# represented them in explicit matrix form, we can simply use ``qp.QubitChannel``. # # # To get our matrices, we represent the computational basis set along the @@ -640,17 +640,17 @@ def make_kraus_ops(num_wires: int): kraus1 = np.identity(d**2).reshape(d**2, d, d) kraus1 /= np.sqrt(d) - # Finally, return a list of NumPy arrays, as per `qml.QubitChannel` docs. + # Finally, return a list of NumPy arrays, as per `qp.QubitChannel` docs. return list(kraus0.astype(complex)), list(kraus1.astype(complex)) ###################################################################### # Our next task is to generate two new ``QuantumTape`` objects from our # existing ``tape``, one for :math:`\Psi _0` and one for :math:`\Psi _1.` -# Currently, a ``qml.WireCut`` dummy gate is used to represent the cut +# Currently, a ``qp.WireCut`` dummy gate is used to represent the cut # position and size. So, iterating through gates in ``tape``: # -# - If the gate is a ``qml.WireCut``, we apply the ``qml.QubitChannel`` +# - If the gate is a ``qp.WireCut``, we apply the ``qp.QubitChannel`` # corresponding to :math:`\Psi _0` or :math:`\Psi _1` to different new # tapes. # - Otherwise, just apply the same existing gate to both new tapes. @@ -662,7 +662,7 @@ def make_kraus_ops(num_wires: int): wire_cut = None for i, op in enumerate(tape.operations): - if isinstance(op, qml.WireCut): + if isinstance(op, qp.WireCut): cut_index = i wire_cut = op break @@ -673,8 +673,8 @@ def make_kraus_ops(num_wires: int): K0, K1 = make_kraus_ops(k) # Generate Kraus operators on the fly probs = (d + 1) / (2 * d + 1), d / (2 * d + 1) # Probabilities of the two channels -psi_0 = qml.QubitChannel(K0, wires=wire_cut.wires) -psi_1 = qml.QubitChannel(K1, wires=wire_cut.wires) +psi_0 = qp.QubitChannel(K0, wires=wire_cut.wires) +psi_1 = qp.QubitChannel(K1, wires=wire_cut.wires) ops_0 = tape.operations ops_0[cut_index] = psi_0 @@ -692,7 +692,7 @@ def make_kraus_ops(num_wires: int): print(f"Cut size: k={k}") print(f"Channel probabilities: p0={probs[0]:.2f}; p1={probs[1]:.2f}", "\n") -fig, _ = qml.drawer.tape_mpl(tape0) +fig, _ = qp.drawer.tape_mpl(tape0) fig.set_size_inches(12, 6) ###################################################################### @@ -709,7 +709,7 @@ def make_kraus_ops(num_wires: int): # simulator. Luckily, PennyLane has just what we need: # -device = qml.device("default.mixed", wires=tape.wires) +device = qp.device("default.mixed", wires=tape.wires) ###################################################################### # We only need a single run for each of the two generated tapes, ``tape0`` and @@ -737,10 +737,10 @@ def make_kraus_ops(num_wires: int): tape0 = QuantumTape(ops=ops_0, measurements=tape.measurements, shots=channel_shots[0].item()) tape1 = QuantumTape(ops=ops_1, measurements=tape.measurements, shots=channel_shots[1].item()) -(shots0,) = qml.execute([tape0], device=device, cache=False, diff_method=None) +(shots0,) = qp.execute([tape0], device=device, cache=False, diff_method=None) samples[choices == 0] = shots0 -(shots1,) = qml.execute([tape1], device=device, cache=False, diff_method=None) +(shots1,) = qp.execute([tape1], device=device, cache=False, diff_method=None) samples[choices == 1] = shots1 ###################################################################### diff --git a/demonstrations_v2/tutorial_quantum_circuit_cutting/metadata.json b/demonstrations_v2/tutorial_quantum_circuit_cutting/metadata.json index 5c07f1258f..7dea29fec9 100644 --- a/demonstrations_v2/tutorial_quantum_circuit_cutting/metadata.json +++ b/demonstrations_v2/tutorial_quantum_circuit_cutting/metadata.json @@ -14,7 +14,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-09-02T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_quantum_dropout/demo.py b/demonstrations_v2/tutorial_quantum_dropout/demo.py index 4469c56943..bef5b9b756 100644 --- a/demonstrations_v2/tutorial_quantum_dropout/demo.py +++ b/demonstrations_v2/tutorial_quantum_dropout/demo.py @@ -55,7 +55,7 @@ # import numpy as np -import pennylane as qml +import pennylane as qp seed = 12345 np.random.seed(seed=seed) @@ -91,9 +91,9 @@ def embedding(x, wires): # employing also nonlinear functions assert len(x) == 1 # check feature is 1-D for i in wires: - qml.RY(jnp.arcsin(x), wires=i) + qp.RY(jnp.arcsin(x), wires=i) for i in wires: - qml.RZ(jnp.arccos(x ** 2), wires=i) + qp.RZ(jnp.arccos(x ** 2), wires=i) def true_cond(angle): @@ -111,7 +111,7 @@ def false_cond(angle): def var_ansatz( - theta, wires, rotations=[qml.RX, qml.RZ, qml.RX], entangler=qml.CNOT, keep_rotation=None + theta, wires, rotations=[qp.RX, qp.RZ, qp.RX], entangler=qp.CNOT, keep_rotation=None ): """Single layer of the variational ansatz for our QNN. @@ -170,9 +170,9 @@ def var_ansatz( def create_circuit(n_qubits, layers): - device = qml.device("default.qubit", wires=n_qubits) + device = qp.device("default.qubit", wires=n_qubits) - @qml.qnode(device) + @qp.qnode(device) def circuit(x, theta, keep_rot): # print(x) # print(theta) @@ -185,11 +185,11 @@ def circuit(x, theta, keep_rot): var_ansatz( theta[i * params_per_layer : (i + 1) * params_per_layer], wires=range(n_qubits), - entangler=qml.CNOT, + entangler=qp.CNOT, keep_rotation=keep_rotation, ) - return qml.expval(qml.PauliZ(wires=0)) # we measure only the first qubit + return qp.expval(qp.PauliZ(wires=0)) # we measure only the first qubit return circuit @@ -215,7 +215,7 @@ def circuit(x, theta, keep_rot): # we encode a single coordinate single_sample = np.array([0]) -qml.draw_mpl(circ, decimals=2,)(single_sample, numbered_params, keep_all_rot) +qp.draw_mpl(circ, decimals=2,)(single_sample, numbered_params, keep_all_rot) plt.show() diff --git a/demonstrations_v2/tutorial_quantum_dropout/metadata.json b/demonstrations_v2/tutorial_quantum_dropout/metadata.json index 3620227380..411c815c9b 100644 --- a/demonstrations_v2/tutorial_quantum_dropout/metadata.json +++ b/demonstrations_v2/tutorial_quantum_dropout/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-03-12T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_quantum_gans/demo.py b/demonstrations_v2/tutorial_quantum_gans/demo.py index 9883817a9c..a642a48cc4 100644 --- a/demonstrations_v2/tutorial_quantum_gans/demo.py +++ b/demonstrations_v2/tutorial_quantum_gans/demo.py @@ -132,7 +132,7 @@ import pandas as pd import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec -import pennylane as qml +import pennylane as qp # Pytorch imports import torch @@ -366,32 +366,32 @@ def forward(self, x): # # Quantum simulator -dev = qml.device("lightning.qubit", wires=n_qubits) +dev = qp.device("lightning.qubit", wires=n_qubits) # Enable CUDA device if available device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") ###################################################################### # Next, we define the quantum circuit and measurement process described above. -@qml.qnode(dev, diff_method="parameter-shift") +@qp.qnode(dev, diff_method="parameter-shift") def quantum_circuit(noise, weights): weights = weights.reshape(q_depth, n_qubits) # Initialise latent vectors for i in range(n_qubits): - qml.RY(noise[i], wires=i) + qp.RY(noise[i], wires=i) # Repeated layer for i in range(q_depth): # Parameterised layer for y in range(n_qubits): - qml.RY(weights[i][y], wires=y) + qp.RY(weights[i][y], wires=y) # Control Z gates for y in range(n_qubits - 1): - qml.CZ(wires=[y, y + 1]) + qp.CZ(wires=[y, y + 1]) - return qml.probs(wires=list(range(n_qubits))) + return qp.probs(wires=list(range(n_qubits))) # For further info on how the non-linear transform is implemented in Pennylane diff --git a/demonstrations_v2/tutorial_quantum_gans/metadata.json b/demonstrations_v2/tutorial_quantum_gans/metadata.json index c07e0c8b38..47a5365623 100644 --- a/demonstrations_v2/tutorial_quantum_gans/metadata.json +++ b/demonstrations_v2/tutorial_quantum_gans/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-02-01T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_quantum_metrology/demo.py b/demonstrations_v2/tutorial_quantum_metrology/demo.py index 6340f0c1b3..40d357da59 100644 --- a/demonstrations_v2/tutorial_quantum_metrology/demo.py +++ b/demonstrations_v2/tutorial_quantum_metrology/demo.py @@ -119,7 +119,7 @@ We now turn to the actual implementation of the scheme. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np @@ -132,7 +132,7 @@ # We will choose the ``cirq.mixedsimulator`` device from the # `Pennylane-Cirq `_ # plugin for this tutorial. -dev = qml.device("cirq.mixedsimulator", wires=3) +dev = qp.device("cirq.mixedsimulator", wires=3) ############################################################################## # Next, we model the parameter encoding. The phase shifts are recreated using @@ -143,7 +143,7 @@ def encoding(phi, gamma): for i in range(3): - qml.RZ(phi[i], wires=[i]) + qp.RZ(phi[i], wires=[i]) cirq_ops.PhaseDamp(gamma, wires=[i]) @@ -156,7 +156,7 @@ def encoding(phi, gamma): def ansatz(weights): - qml.ArbitraryStatePreparation(weights, wires=[0, 1, 2]) + qp.ArbitraryStatePreparation(weights, wires=[0, 1, 2]) NUM_ANSATZ_PARAMETERS = 14 @@ -164,7 +164,7 @@ def ansatz(weights): def measurement(weights): for i in range(3): - qml.ArbitraryStatePreparation(weights[2 * i : 2 * (i + 1)], wires=[i]) + qp.ArbitraryStatePreparation(weights[2 * i : 2 * (i + 1)], wires=[i]) NUM_MEASUREMENT_PARAMETERS = 6 @@ -174,19 +174,19 @@ def measurement(weights): # We now have everything at hand to model the quantum part of our experiment # as a QNode. We will return the output probabilities necessary to compute the # Classical Fisher Information Matrix. -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def experiment(weights, phi, gamma=0.0): ansatz(weights[:NUM_ANSATZ_PARAMETERS]) encoding(phi, gamma) measurement(weights[NUM_ANSATZ_PARAMETERS:]) - return qml.probs(wires=[0, 1, 2]) + return qp.probs(wires=[0, 1, 2]) # Draw the circuit at the given parameter values print( - qml.draw(experiment, level="device", max_length=80)( + qp.draw(experiment, level="device", max_length=80)( np.arange(NUM_ANSATZ_PARAMETERS + NUM_MEASUREMENT_PARAMETERS), np.zeros(3), gamma=0.2, @@ -285,7 +285,7 @@ def opt_cost(weights, phi=phi, gamma=gamma, J=J, W=W): requires_grad=True, ) -opt = qml.AdagradOptimizer(stepsize=0.1) +opt = qp.AdagradOptimizer(stepsize=0.1) print("Initialization: Cost = {:6.4f}".format(opt_cost(weights))) for i in range(20): diff --git a/demonstrations_v2/tutorial_quantum_metrology/metadata.json b/demonstrations_v2/tutorial_quantum_metrology/metadata.json index f6e3173885..242aee7d9a 100644 --- a/demonstrations_v2/tutorial_quantum_metrology/metadata.json +++ b/demonstrations_v2/tutorial_quantum_metrology/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-06-18T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_quantum_natural_gradient/demo.py b/demonstrations_v2/tutorial_quantum_natural_gradient/demo.py index 44f59b57e6..405f77819b 100644 --- a/demonstrations_v2/tutorial_quantum_natural_gradient/demo.py +++ b/demonstrations_v2/tutorial_quantum_natural_gradient/demo.py @@ -185,36 +185,36 @@ # Let's consider a small variational quantum circuit example coded in PennyLane: import numpy as np -import pennylane as qml +import pennylane as qp from pennylane import numpy as pnp -dev = qml.device("lightning.qubit", wires=3) +dev = qp.device("lightning.qubit", wires=3) -@qml.qnode(dev, interface="autograd", diff_method="parameter-shift") +@qp.qnode(dev, interface="autograd", diff_method="parameter-shift") def circuit(params): # |psi_0>: state preparation - qml.RY(np.pi / 4, wires=0) - qml.RY(np.pi / 3, wires=1) - qml.RY(np.pi / 7, wires=2) + qp.RY(np.pi / 4, wires=0) + qp.RY(np.pi / 3, wires=1) + qp.RY(np.pi / 7, wires=2) # V0(theta0, theta1): Parametrized layer 0 - qml.RZ(params[0], wires=0) - qml.RZ(params[1], wires=1) + qp.RZ(params[0], wires=0) + qp.RZ(params[1], wires=1) # W1: non-parametrized gates - qml.CNOT(wires=[0, 1]) - qml.CNOT(wires=[1, 2]) + qp.CNOT(wires=[0, 1]) + qp.CNOT(wires=[1, 2]) # V_1(theta2, theta3): Parametrized layer 1 - qml.RY(params[2], wires=1) - qml.RX(params[3], wires=2) + qp.RY(params[2], wires=1) + qp.RX(params[3], wires=2) # W2: non-parametrized gates - qml.CNOT(wires=[0, 1]) - qml.CNOT(wires=[1, 2]) + qp.CNOT(wires=[0, 1]) + qp.CNOT(wires=[1, 2]) - return qml.expval(qml.PauliY(0)) + return qp.expval(qp.PauliY(0)) # Use pennylane.numpy for trainable parameters params = pnp.array([0.432, -0.123, 0.543, 0.233]) @@ -255,9 +255,9 @@ def circuit(params): def layer0_subcircuit(params): """This function contains all gates that precede parametrized layer 0""" - qml.RY(np.pi / 4, wires=0) - qml.RY(np.pi / 3, wires=1) - qml.RY(np.pi / 7, wires=2) + qp.RY(np.pi / 4, wires=0) + qp.RY(np.pi / 3, wires=1) + qp.RY(np.pi / 7, wires=2) ############################################################################## @@ -272,10 +272,10 @@ def layer0_subcircuit(params): # We can see that the diagonal terms are simply given by the variance: -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def layer0_diag(params): layer0_subcircuit(params) - return qml.var(qml.PauliZ(0)), qml.var(qml.PauliZ(1)) + return qp.var(qp.PauliZ(0)), qp.var(qp.PauliZ(1)) # calculate the diagonal terms @@ -288,17 +288,17 @@ def layer0_diag(params): # off-diagonal covariance terms of :math:`g^{(0)}:` -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def layer0_off_diag_single(params): layer0_subcircuit(params) - return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)) + return qp.expval(qp.PauliZ(0)), qp.expval(qp.PauliZ(1)) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def layer0_off_diag_double(params): layer0_subcircuit(params) ZZ = np.kron(np.diag([1, -1]), np.diag([1, -1])) - return qml.expval(qml.Hermitian(ZZ, wires=[0, 1])) + return qp.expval(qp.Hermitian(ZZ, wires=[0, 1])) # calculate the off-diagonal terms @@ -327,17 +327,17 @@ def layer1_subcircuit(params): """This function contains all gates that precede parametrized layer 1""" # |psi_0>: state preparation - qml.RY(np.pi / 4, wires=0) - qml.RY(np.pi / 3, wires=1) - qml.RY(np.pi / 7, wires=2) + qp.RY(np.pi / 4, wires=0) + qp.RY(np.pi / 3, wires=1) + qp.RY(np.pi / 7, wires=2) # V0(theta0, theta1): Parametrized layer 0 - qml.RZ(params[0], wires=0) - qml.RZ(params[1], wires=1) + qp.RZ(params[0], wires=0) + qp.RZ(params[1], wires=1) # W1: non-parametrized gates - qml.CNOT(wires=[0, 1]) - qml.CNOT(wires=[1, 2]) + qp.CNOT(wires=[0, 1]) + qp.CNOT(wires=[1, 2]) ############################################################################## @@ -349,10 +349,10 @@ def layer1_subcircuit(params): # :target: javascript:void(0) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def layer1_diag(params): layer1_subcircuit(params) - return qml.var(qml.PauliY(1)), qml.var(qml.PauliX(2)) + return qp.var(qp.PauliY(1)), qp.var(qp.PauliX(2)) ############################################################################## @@ -368,19 +368,19 @@ def layer1_diag(params): # observables to be computed. -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def layer1_off_diag_single(params): layer1_subcircuit(params) - return qml.expval(qml.PauliY(1)), qml.expval(qml.PauliX(2)) + return qp.expval(qp.PauliY(1)), qp.expval(qp.PauliX(2)) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def layer1_off_diag_double(params): layer1_subcircuit(params) X = np.array([[0, 1], [1, 0]]) Y = np.array([[0, -1j], [1j, 0]]) YX = np.kron(Y, X) - return qml.expval(qml.Hermitian(YX, wires=[1, 2])) + return qp.expval(qp.Hermitian(YX, wires=[1, 2])) # calculate the off-diagonal terms @@ -404,7 +404,7 @@ def layer1_off_diag_double(params): # PennyLane contains a built-in function for computing the Fubini-Study metric # tensor, :func:`~.pennylane.metric_tensor`, which # we can use to verify this result: -print(np.round(qml.metric_tensor(circuit, approx="block-diag")(params), 8)) +print(np.round(qp.metric_tensor(circuit, approx="block-diag")(params), 8)) ############################################################################## # As opposed to our manual computation, which required 6 different quantum @@ -420,7 +420,7 @@ def layer1_off_diag_double(params): # # Note that the :func:`~.pennylane.metric_tensor` function also supports computing the diagonal # approximation to the metric tensor: -print(qml.metric_tensor(circuit, approx='diag')(params)) +print(qp.metric_tensor(circuit, approx='diag')(params)) ############################################################################## # Furthermore, the returned metric tensor is **full differentiable**; include it @@ -442,7 +442,7 @@ def layer1_off_diag_double(params): # Performing vanilla gradient descent: gd_cost = [] -opt = qml.GradientDescentOptimizer(0.01) +opt = qp.GradientDescentOptimizer(0.01) theta = init_params for _ in range(steps): @@ -453,7 +453,7 @@ def layer1_off_diag_double(params): # Performing quantum natural gradient descent: qng_cost = [] -opt = qml.QNGOptimizer(0.01) +opt = qp.QNGOptimizer(0.01) theta = init_params for _ in range(steps): diff --git a/demonstrations_v2/tutorial_quantum_natural_gradient/metadata.json b/demonstrations_v2/tutorial_quantum_natural_gradient/metadata.json index 3c62496128..62d7441fbb 100644 --- a/demonstrations_v2/tutorial_quantum_natural_gradient/metadata.json +++ b/demonstrations_v2/tutorial_quantum_natural_gradient/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-11T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_quantum_phase_transitions/demo.py b/demonstrations_v2/tutorial_quantum_phase_transitions/demo.py index 6510ef32ce..4ba0e5548d 100644 --- a/demonstrations_v2/tutorial_quantum_phase_transitions/demo.py +++ b/demonstrations_v2/tutorial_quantum_phase_transitions/demo.py @@ -78,7 +78,7 @@ # # The code below creates this Hamiltonian for three qubits: # -import pennylane as qml +import pennylane as qp from pennylane import numpy as np @@ -86,14 +86,14 @@ J = 2 wires = range(N) -dev = qml.device("lightning.qubit", wires=N) +dev = qp.device("lightning.qubit", wires=N) coeffs = [-J] * (N - 1) obs = [] for i in range(N - 1): - obs.append(qml.Z(i) @ qml.Z(i + 1)) -H = qml.Hamiltonian(coeffs, obs) + obs.append(qp.Z(i) @ qp.Z(i + 1)) +H = qp.Hamiltonian(coeffs, obs) print(f"H={H}") @@ -141,31 +141,31 @@ def create_ansatz(params, N): # STEP 1: perform single-qubit rotations on all the qubits for i in range(N): - qml.RZ(phi=params[i], wires=i) - qml.RX(phi=params[N + i], wires=i) - qml.RZ(phi=params[2 * N + i], wires=i) + qp.RZ(phi=params[i], wires=i) + qp.RX(phi=params[N + i], wires=i) + qp.RZ(phi=params[2 * N + i], wires=i) # STEP 2: perform a CNOT gate on each pair of neighbouring qubits for i in range(N - 1): - qml.CNOT(wires=[i, i + 1]) + qp.CNOT(wires=[i, i + 1]) # STEP 3: perform single-qubit rotations on all the qubits for i in range(N): - qml.RZ(phi=params[3 * N + i], wires=i) - qml.RX(phi=params[4 * N + i], wires=i) - qml.RZ(phi=params[5 * N + i], wires=i) + qp.RZ(phi=params[3 * N + i], wires=i) + qp.RX(phi=params[4 * N + i], wires=i) + qp.RZ(phi=params[5 * N + i], wires=i) -@qml.qnode(dev) +@qp.qnode(dev) def quantum_circuit(params): # Create a quantum state using params create_ansatz(params, N) - return qml.expval(H) + return qp.expval(H) max_iters = 200 tolerance = 1e-04 # create an optimizer -opt = qml.GradientDescentOptimizer(stepsize=0.1) +opt = qp.GradientDescentOptimizer(stepsize=0.1) # energy is a list that stores all the estimates for the ground-state energy energy = [] @@ -279,30 +279,30 @@ def quantum_circuit(params): # Store the expectation values of the magnetization operator M for different values of J/h_x magnetization_list = [] -dev_2 = qml.device("lightning.qubit", wires=N) +dev_2 = qp.device("lightning.qubit", wires=N) # This function prepares an estimate of the ground state & calculates its energy. -@qml.qnode(dev_2) +@qp.qnode(dev_2) def quantum_circuit_2(params): # Generate an estimate of the ground state create_ansatz(params, N) - return qml.expval(H) + return qp.expval(H) # A function that returns the magnetization operator of N qubits. def magnetization_op(N): - total_op = qml.PauliZ(0) + total_op = qp.PauliZ(0) if N > 1: for i in range(1, N): - total_op = total_op + qml.PauliZ(i) + total_op = total_op + qp.PauliZ(i) return total_op / N #Prepare a parameterized state & return the value of the magnetization operator. -@qml.qnode(dev_2) +@qp.qnode(dev_2) def calculate_magnetization(params): create_ansatz(params, N) - return qml.expval(magnetization_op(N)) + return qp.expval(magnetization_op(N)) # Loop through all the different values of J for i in range(len(J_list)): @@ -314,14 +314,14 @@ def calculate_magnetization(params): obs = [] for j in range(N - 1): - obs.append(qml.Z(j) @ qml.Z(j + 1)) + obs.append(qp.Z(j) @ qp.Z(j + 1)) # Add Pauli X terms to the Hamiltonian for j in range(N): - obs.append(qml.X(j)) + obs.append(qp.X(j)) coeffs.append(-h_x) - H = qml.Hamiltonian(coeffs, obs) + H = qp.Hamiltonian(coeffs, obs) params = np.array([2 * np.pi * random.uniform(0, 1)] * (6 * N), requires_grad=True) @@ -329,7 +329,7 @@ def calculate_magnetization(params): tolerance = 1e-04 # create an optimizer - opt = qml.MomentumOptimizer(stepsize=0.02, momentum=0.9) + opt = qp.MomentumOptimizer(stepsize=0.02, momentum=0.9) energy = [] @@ -432,7 +432,7 @@ def calculate_magnetization(params): N = 2 -H = qml.spin.transverse_ising(lattice="square", n_cells=[N, N], h=1.0, boundary_condition=True) +H = qp.spin.transverse_ising(lattice="square", n_cells=[N, N], h=1.0, boundary_condition=True) print(f"H={H}") @@ -441,23 +441,23 @@ def calculate_magnetization(params): # wires_2D = range(N**2) -dev_2D = qml.device("lightning.qubit", wires=wires_2D) +dev_2D = qp.device("lightning.qubit", wires=wires_2D) random.seed(a=10) # generate random parameter values for the initial statevector params = np.array([2 * np.pi * random.uniform(0, 1)] * (6 * N), requires_grad=True) -@qml.qnode(dev_2D) +@qp.qnode(dev_2D) def quantum_circuit_2D(params): create_ansatz(params, N) - return qml.expval(H) + return qp.expval(H) max_iters = 500 tolerance = 3e-04 # create an optimizer -opt = qml.GradientDescentOptimizer(stepsize=0.015) +opt = qp.GradientDescentOptimizer(stepsize=0.015) energy = [] @@ -484,7 +484,7 @@ def quantum_circuit_2D(params): # N = 3 -dev_2D_varying_J = qml.device("lightning.qubit", wires=N**2) +dev_2D_varying_J = qp.device("lightning.qubit", wires=N**2) # strength of transverse magnetic field h_x = 1 @@ -495,19 +495,19 @@ def quantum_circuit_2D(params): magnetization_list = [] # Prepare a parameterized state & calculate the value of the magnetization operator. -@qml.qnode(dev_2D_varying_J) +@qp.qnode(dev_2D_varying_J) def calculate_magnetization_2D(params): create_ansatz(params, N) - return qml.expval(magnetization_op(N)) + return qp.expval(magnetization_op(N)) -@qml.qnode(dev_2D_varying_J) +@qp.qnode(dev_2D_varying_J) def quantum_circuit_2D_varying_J(params): create_ansatz(params, N) - return qml.expval(H) + return qp.expval(H) # Loop through all values of J for i in range(len(J_list)): - H = qml.spin.transverse_ising( + H = qp.spin.transverse_ising( lattice="square", coupling=J_list[i], n_cells=[N, N], boundary_condition=True ) #Set the initial values of the rotation angle parameters. @@ -521,7 +521,7 @@ def quantum_circuit_2D_varying_J(params): max_iters = 500 # create an optimizer - opt = qml.MomentumOptimizer(stepsize=0.03, momentum=0.9) + opt = qp.MomentumOptimizer(stepsize=0.03, momentum=0.9) energy = [] @@ -584,18 +584,18 @@ def quantum_circuit_2D_varying_J(params): # We do this to copy what was done in Reference 13: https://arxiv.org/abs/2008.04894 obs = [] for j in range(N - 1): - obs.append(qml.Z(j) @ qml.Z(j + 1)) -obs.append(qml.Z(N-1) @ qml.Z(0)) + obs.append(qp.Z(j) @ qp.Z(j + 1)) +obs.append(qp.Z(N-1) @ qp.Z(0)) # add Pauli X terms to Hamiltonian (transverse field) for j in range(N): - obs.append(qml.X(j)) + obs.append(qp.X(j)) # add Pauli Z terms to Hamiltonian (longitudinal field) for j in range(N): - obs.append(qml.Z(j)) + obs.append(qp.Z(j)) -dev = qml.device("lightning.qubit", wires=N) +dev = qp.device("lightning.qubit", wires=N) J = -0.1 @@ -613,17 +613,17 @@ def quantum_circuit_2D_varying_J(params): coeffs = J_coeffs + X_coeffs + Z_coeffs -H = qml.Hamiltonian(coeffs, obs) +H = qp.Hamiltonian(coeffs, obs) # create the circuit that evolves the system in time -@qml.qnode(dev) +@qp.qnode(dev) def time_evolution_circuit(H, T): #Evolve the system via a sequence of short approximate Trotter time steps #https://docs.pennylane.ai/en/stable/code/api/pennylane.TrotterProduct.html - qml.TrotterProduct(H, time=T, n=math.ceil(T / 0.1)+1, order=2) + qp.TrotterProduct(H, time=T, n=math.ceil(T / 0.1)+1, order=2) # return the final probabilities - return qml.probs(wires=range(N)) + return qp.probs(wires=range(N)) ############################################################################## diff --git a/demonstrations_v2/tutorial_quantum_phase_transitions/metadata.json b/demonstrations_v2/tutorial_quantum_phase_transitions/metadata.json index ffeea8659c..75397ca2a8 100644 --- a/demonstrations_v2/tutorial_quantum_phase_transitions/metadata.json +++ b/demonstrations_v2/tutorial_quantum_phase_transitions/metadata.json @@ -9,7 +9,7 @@ } ], "dateOfPublication": "2025-10-28T00:00:00+00:00", - "dateOfLastModification": "2025-10-30T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": ["Optimization","Quantum Machine Learning"], "tags": ["quantum phase transition", "Ising model"], "previewImages": [ diff --git a/demonstrations_v2/tutorial_quantum_transfer_learning/demo.py b/demonstrations_v2/tutorial_quantum_transfer_learning/demo.py index 1cf90b6c24..3c5e316062 100644 --- a/demonstrations_v2/tutorial_quantum_transfer_learning/demo.py +++ b/demonstrations_v2/tutorial_quantum_transfer_learning/demo.py @@ -133,7 +133,7 @@ from torchvision import datasets, transforms # Pennylane -import pennylane as qml +import pennylane as qp from pennylane import numpy as np torch.manual_seed(42) @@ -167,7 +167,7 @@ ############################################################################## # We initialize a PennyLane device with a ``default.qubit`` backend. -dev = qml.device("default.qubit", wires=n_qubits) +dev = qp.device("default.qubit", wires=n_qubits) ############################################################################## # We configure PyTorch to use CUDA only if available. Otherwise the CPU is used. @@ -274,14 +274,14 @@ def H_layer(nqubits): """Layer of single-qubit Hadamard gates. """ for idx in range(nqubits): - qml.Hadamard(wires=idx) + qp.Hadamard(wires=idx) def RY_layer(w): """Layer of parametrized qubit rotations around the y axis. """ for idx, element in enumerate(w): - qml.RY(element, wires=idx) + qp.RY(element, wires=idx) def entangling_layer(nqubits): @@ -291,9 +291,9 @@ def entangling_layer(nqubits): # CNOT CNOT CNOT CNOT... CNOT # CNOT CNOT CNOT... CNOT for i in range(0, nqubits - 1, 2): # Loop over even indices: i=0,2,...N-2 - qml.CNOT(wires=[i, i + 1]) + qp.CNOT(wires=[i, i + 1]) for i in range(1, nqubits - 1, 2): # Loop over odd indices: i=1,3,...N-3 - qml.CNOT(wires=[i, i + 1]) + qp.CNOT(wires=[i, i + 1]) ############################################################################## @@ -313,7 +313,7 @@ def entangling_layer(nqubits): # additional post-processing. -@qml.qnode(dev) +@qp.qnode(dev) def quantum_net(q_input_features, q_weights_flat): """ The variational quantum circuit. @@ -334,7 +334,7 @@ def quantum_net(q_input_features, q_weights_flat): RY_layer(q_weights[k]) # Expectation values in the Z basis - exp_vals = [qml.expval(qml.PauliZ(position)) for position in range(n_qubits)] + exp_vals = [qp.expval(qp.PauliZ(position)) for position in range(n_qubits)] return tuple(exp_vals) diff --git a/demonstrations_v2/tutorial_quantum_transfer_learning/metadata.json b/demonstrations_v2/tutorial_quantum_transfer_learning/metadata.json index f586354c9a..f67e0590b4 100644 --- a/demonstrations_v2/tutorial_quantum_transfer_learning/metadata.json +++ b/demonstrations_v2/tutorial_quantum_transfer_learning/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-12-19T00:00:00+00:00", - "dateOfLastModification": "2025-11-10T11:00:00+00:00", + "dateOfLastModification": "2026-04-17T11:00:00+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_quanvolution/demo.py b/demonstrations_v2/tutorial_quanvolution/demo.py index 7ada3a800c..c7525d9a8d 100644 --- a/demonstrations_v2/tutorial_quanvolution/demo.py +++ b/demonstrations_v2/tutorial_quanvolution/demo.py @@ -83,7 +83,7 @@ This Python code requires *PennyLane* with the *TensorFlow* interface and the plotting library *matplotlib*. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np from pennylane.templates import RandomLayers import tensorflow as tf @@ -146,21 +146,21 @@ # 3. a final measurement in the computational basis, estimating :math:`4` expectation values. -dev = qml.device("default.qubit", wires=4) +dev = qp.device("default.qubit", wires=4) # Random circuit parameters rand_params = np.random.uniform(high=2 * np.pi, size=(n_layers, 4)) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(phi): # Encoding of 4 classical input values for j in range(4): - qml.RY(np.pi * phi[j], wires=j) + qp.RY(np.pi * phi[j], wires=j) # Random quantum circuit RandomLayers(rand_params, wires=list(range(4))) # Measurement producing 4 classical output values - return [qml.expval(qml.PauliZ(j)) for j in range(4)] + return [qp.expval(qp.PauliZ(j)) for j in range(4)] ############################################################################## diff --git a/demonstrations_v2/tutorial_quanvolution/metadata.json b/demonstrations_v2/tutorial_quanvolution/metadata.json index d44930f757..ecb21ac8da 100644 --- a/demonstrations_v2/tutorial_quanvolution/metadata.json +++ b/demonstrations_v2/tutorial_quanvolution/metadata.json @@ -8,7 +8,7 @@ "executable_stable": false, "executable_latest": false, "dateOfPublication": "2020-03-24T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_qubit_rotation/demo.py b/demonstrations_v2/tutorial_qubit_rotation/demo.py index cf68662eaf..16163f009f 100644 --- a/demonstrations_v2/tutorial_qubit_rotation/demo.py +++ b/demonstrations_v2/tutorial_qubit_rotation/demo.py @@ -86,7 +86,7 @@ # The first thing we need to do is import PennyLane, as well as the wrapped version # of NumPy provided by Jax. -import pennylane as qml +import pennylane as qp from jax import numpy as np import jax @@ -118,7 +118,7 @@ # For this tutorial, we are using the qubit model, so let's initialize the ``'lightning.qubit'`` device # provided by PennyLane. -dev1 = qml.device("lightning.qubit", wires=1) +dev1 = qp.device("lightning.qubit", wires=1) ############################################################################## # For all devices, :func:`~.pennylane.device` accepts the following arguments: @@ -152,9 +152,9 @@ def circuit(params): - qml.RX(params[0], wires=0) - qml.RY(params[1], wires=0) - return qml.expval(qml.PauliZ(0)) + qp.RX(params[0], wires=0) + qp.RY(params[1], wires=0) + return qp.expval(qp.PauliZ(0)) ############################################################################## @@ -195,11 +195,11 @@ def circuit(params): # **directly above** the function definition: -@qml.qnode(dev1) +@qp.qnode(dev1) def circuit(params): - qml.RX(params[0], wires=0) - qml.RY(params[1], wires=0) - return qml.expval(qml.PauliZ(0)) + qp.RX(params[0], wires=0) + qp.RY(params[1], wires=0) + return qp.expval(qp.PauliZ(0)) ############################################################################## @@ -248,11 +248,11 @@ def circuit(params): # two positional arguments, instead of one array argument: -@qml.qnode(dev1) +@qp.qnode(dev1) def circuit2(phi1, phi2): - qml.RX(phi1, wires=0) - qml.RY(phi2, wires=0) - return qml.expval(qml.PauliZ(0)) + qp.RX(phi1, wires=0) + qp.RY(phi2, wires=0) + return qp.expval(qp.PauliZ(0)) ################################################################################ diff --git a/demonstrations_v2/tutorial_qubit_rotation/metadata.json b/demonstrations_v2/tutorial_qubit_rotation/metadata.json index 0d9725d3e2..f8e7e1b502 100644 --- a/demonstrations_v2/tutorial_qubit_rotation/metadata.json +++ b/demonstrations_v2/tutorial_qubit_rotation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-11T00:00:00+00:00", - "dateOfLastModification": "2026-02-15T14:40:02+02:00", + "dateOfLastModification": "2026-04-17T14:40:02+02:00", "categories": [ "Getting Started" ], diff --git a/demonstrations_v2/tutorial_qubit_tapering/demo.py b/demonstrations_v2/tutorial_qubit_tapering/demo.py index 5f338e68f3..d7b4235b36 100644 --- a/demonstrations_v2/tutorial_qubit_tapering/demo.py +++ b/demonstrations_v2/tutorial_qubit_tapering/demo.py @@ -119,7 +119,7 @@ In PennyLane, a :doc:`molecular Hamiltonian ` can be created by specifying the atomic symbols and coordinates. """ -import pennylane as qml +import pennylane as qp from jax import numpy as jnp import jax @@ -128,8 +128,8 @@ geometry = jnp.array([[0.00000000, 0.00000000, -0.87818361], [0.00000000, 0.00000000, 0.87818362]]) -molecule = qml.qchem.Molecule(symbols, geometry, charge=1) -H, qubits = qml.qchem.molecular_hamiltonian(molecule) +molecule = qp.qchem.Molecule(symbols, geometry, charge=1) +H, qubits = qp.qchem.molecular_hamiltonian(molecule) H ############################################################################## @@ -140,8 +140,8 @@ # Hamiltonian. In PennyLane, these are constructed by using the # :func:`~.pennylane.symmetry_generators` and :func:`~.pennylane.paulix_ops` functions. -generators = qml.symmetry_generators(H) -paulixops = qml.paulix_ops(generators, qubits) +generators = qp.symmetry_generators(H) +paulixops = qp.paulix_ops(generators, qubits) for idx, generator in enumerate(generators): print(f"generator {idx+1}: {generator}, paulix_op: {paulixops[idx]}") @@ -157,7 +157,7 @@ n_electrons = 2 -paulix_sector = qml.qchem.optimal_sector(H, generators, n_electrons) +paulix_sector = qp.qchem.optimal_sector(H, generators, n_electrons) print(paulix_sector) ############################################################################## @@ -167,9 +167,9 @@ # qubits :math:`q_2, q_3` by replacing the Pauli-X operators acting on those qubits with the optimal # eigenvalues. -H_tapered = qml.taper(H, generators, paulixops, paulix_sector) +H_tapered = qp.taper(H, generators, paulixops, paulix_sector) H_tapered_coeffs, H_tapered_ops = H_tapered.terms() -H_tapered = qml.Hamiltonian(jnp.real(jnp.array(H_tapered_coeffs)), H_tapered_ops) +H_tapered = qp.Hamiltonian(jnp.real(jnp.array(H_tapered_coeffs)), H_tapered_ops) print(H_tapered) ############################################################################## @@ -180,11 +180,11 @@ # representation of Hamiltonians. This allows us to directly diagonalize them to obtain exact values # of the ground-state energies. -H_sparse = qml.SparseHamiltonian(H.sparse_matrix(), wires=H.wires) -H_tapered_sparse = qml.SparseHamiltonian(H_tapered.sparse_matrix(), wires=H_tapered.wires) +H_sparse = qp.SparseHamiltonian(H.sparse_matrix(), wires=H.wires) +H_tapered_sparse = qp.SparseHamiltonian(H_tapered.sparse_matrix(), wires=H_tapered.wires) -print("Eigenvalues of H:\n", qml.eigvals(H_sparse, k=16)) -print("\nEigenvalues of H_tapered:\n", qml.eigvals(H_tapered_sparse, k=4)) +print("Eigenvalues of H:\n", qp.eigvals(H_sparse, k=16)) +print("\nEigenvalues of H_tapered:\n", qp.eigvals(H_tapered_sparse, k=4)) ############################################################################## # Note that a second-quantized Hamiltonian is independent of the number of electrons and its @@ -205,7 +205,7 @@ # Hamiltonian. This reduces the number of qubits in the Hartree-Fock state to match that of the # tapered Hamiltonian. It can be done with the :func:`~.pennylane.qchem.taper_hf` function. -state_tapered = qml.qchem.taper_hf(generators, paulixops, paulix_sector, +state_tapered = qp.qchem.taper_hf(generators, paulixops, paulix_sector, num_electrons=n_electrons, num_wires=len(H.wires)) print(state_tapered) @@ -214,21 +214,21 @@ # :math:`[1 1 0 0].` We can now generate the qubit representation of these states and compute the # Hartree-Fock energies for each Hamiltonian. -dev = qml.device("default.qubit", wires=H.wires) -@qml.qnode(dev, interface="jax") +dev = qp.device("default.qubit", wires=H.wires) +@qp.qnode(dev, interface="jax") def circuit(): - qml.BasisState(jnp.array([1, 1, 0, 0]), wires=H.wires) - return qml.state() + qp.BasisState(jnp.array([1, 1, 0, 0]), wires=H.wires) + return qp.state() qubit_state = circuit() HF_energy = qubit_state.T @ H.sparse_matrix().toarray() @ qubit_state print(f"HF energy: {jnp.real(HF_energy):.8f} Ha") -dev = qml.device("lightning.qubit", wires=H_tapered.wires) -@qml.qnode(dev, interface="jax") +dev = qp.device("lightning.qubit", wires=H_tapered.wires) +@qp.qnode(dev, interface="jax") def circuit(): - qml.BasisState(jnp.array([1, 1]), wires=H_tapered.wires) - return qml.state() + qp.BasisState(jnp.array([1, 1]), wires=H_tapered.wires) + return qp.state() qubit_state = circuit() HF_energy = qubit_state.T @ H_tapered.sparse_matrix().toarray() @ qubit_state @@ -247,24 +247,24 @@ def circuit(): # :func:`~.pennylane.DoubleExcitation` operations tapered using # :func:`~.pennylane.qchem.taper_operation`. -singles, doubles = qml.qchem.excitations(n_electrons, len(H.wires)) +singles, doubles = qp.qchem.excitations(n_electrons, len(H.wires)) tapered_doubles = [ - qml.taper_operation(qml.DoubleExcitation, generators, paulixops, paulix_sector, + qp.taper_operation(qp.DoubleExcitation, generators, paulixops, paulix_sector, wire_order=H.wires, op_wires=double) for double in doubles ] tapered_singles = [ - qml.taper_operation(qml.SingleExcitation, generators, paulixops, paulix_sector, + qp.taper_operation(qp.SingleExcitation, generators, paulixops, paulix_sector, wire_order=H.wires, op_wires=single) for single in singles ] -dev = qml.device("lightning.qubit", wires=H_tapered.wires) +dev = qp.device("lightning.qubit", wires=H_tapered.wires) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def tapered_circuit(params): - qml.BasisState(state_tapered, wires=H_tapered.wires) + qp.BasisState(state_tapered, wires=H_tapered.wires) for idx, tapered_op in enumerate(tapered_doubles + tapered_singles): tapered_op(params[idx]) - return qml.expval(H_tapered) + return qp.expval(H_tapered) ############################################################################## # We define an optimizer and the initial values of the circuit parameters and optimize the circuit diff --git a/demonstrations_v2/tutorial_qubit_tapering/metadata.json b/demonstrations_v2/tutorial_qubit_tapering/metadata.json index 42212516f7..da68134fe7 100644 --- a/demonstrations_v2/tutorial_qubit_tapering/metadata.json +++ b/demonstrations_v2/tutorial_qubit_tapering/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-05-16T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry" ], diff --git a/demonstrations_v2/tutorial_qubitization/demo.py b/demonstrations_v2/tutorial_qubitization/demo.py index f4382e3460..40e83f5f41 100644 --- a/demonstrations_v2/tutorial_qubitization/demo.py +++ b/demonstrations_v2/tutorial_qubitization/demo.py @@ -92,11 +92,11 @@ First, let's define a simple Hamiltonian to use as an example: """ -import pennylane as qml +import pennylane as qp -H = -0.4 * qml.Z(0) + 0.3 * qml.Z(1) + 0.4 * qml.Z(0) @ qml.Z(1) +H = -0.4 * qp.Z(0) + 0.3 * qp.Z(1) + 0.4 * qp.Z(0) @ qp.Z(1) -print(qml.matrix(H).real) +print(qp.matrix(H).real) ############################################################################## # We have chosen an operator that is diagonal in the computational basis because it is easy to identify @@ -110,21 +110,21 @@ control_wires = [2, 3] estimation_wires = [4, 5, 6, 7, 8, 9] -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): # Initialize the eigenstate |11⟩ for wire in [0, 1]: - qml.X(wire) + qp.X(wire) # Apply QPE with the qubitization operator - qml.QuantumPhaseEstimation( - qml.Qubitization(H, control_wires), estimation_wires=estimation_wires + qp.QuantumPhaseEstimation( + qp.Qubitization(H, control_wires), estimation_wires=estimation_wires ) - return qml.probs(wires=estimation_wires) + return qp.probs(wires=estimation_wires) ############################################################################## diff --git a/demonstrations_v2/tutorial_qubitization/metadata.json b/demonstrations_v2/tutorial_qubitization/metadata.json index 7df408a5e5..ceb21c75d0 100644 --- a/demonstrations_v2/tutorial_qubitization/metadata.json +++ b/demonstrations_v2/tutorial_qubitization/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-09-09T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Algorithms" diff --git a/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/demo.py b/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/demo.py index be3dfde8c2..88e43ee5d2 100644 --- a/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/demo.py +++ b/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/demo.py @@ -126,58 +126,58 @@ """ -import pennylane as qml +import pennylane as qp -dev = qml.device("default.qubit", wires = 4) +dev = qp.device("default.qubit", wires = 4) def Uf(): # The oracle in charge of encoding a hidden "a" value. - qml.CNOT(wires=[1, 3]) - qml.CNOT(wires=[2 ,3]) + qp.CNOT(wires=[1, 3]) + qp.CNOT(wires=[2 ,3]) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit0(): """Circuit used to derive a0""" # Initialize x = [1,0,0] - qml.PauliX(wires = 0) + qp.PauliX(wires = 0) # Apply our oracle Uf() # We measure the last qubit - return qml.sample(wires = 3) + return qp.sample(wires = 3) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit1(): # Circuit used to derive a1 # Initialize x = [0,1,0] - qml.PauliX(wires = 1) + qp.PauliX(wires = 1) # We apply our oracle Uf() # We measure the last qubit - return qml.sample(wires = 3) + return qp.sample(wires = 3) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit2(): # Circuit used to derive a2 # Initialize x = [0,0,1] - qml.PauliX(wires = 2) + qp.PauliX(wires = 2) # We apply our oracle Uf() # We measure the last qubit - return qml.sample(wires = 3) + return qp.sample(wires = 3) # We run for x = [1,0,0] a0 = circuit0() @@ -195,26 +195,26 @@ def circuit2(): # In this case, with 3 queries (:math:`n=3`), we have discovered the value of :math:`\vec{a}.` Let's run the Bernstein–Vazirani subroutine (using qubits as qubits this time) to check that one call is enough: -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit(): # We initialize to |0001> - qml.PauliX(wires = 3) + qp.PauliX(wires = 3) # We run the Hadamards for i in range(4): - qml.Hadamard(wires = i) + qp.Hadamard(wires = i) # We apply our function Uf() # We run the Hadamards for i in range(3): - qml.Hadamard(wires = i) + qp.Hadamard(wires = i) # We measure the first 3 qubits - return qml.sample(wires = range(3)) + return qp.sample(wires = range(3)) a = circuit() @@ -248,52 +248,52 @@ def circuit(): # These generalizations simply adjust the addition operation to be performed in modulo 3 instead of modulo 2. # So, with these ingredients, we are ready to go to the code. -dev = qml.device("default.qutrit", wires=4) +dev = qp.device("default.qutrit", wires=4) def Uf(): # The oracle in charge of encoding a hidden "a" value. - qml.TAdd(wires = [1,3]) - qml.TAdd(wires = [1,3]) - qml.TAdd(wires = [2,3]) + qp.TAdd(wires = [1,3]) + qp.TAdd(wires = [1,3]) + qp.TAdd(wires = [2,3]) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit0(): # Initialize x = [1,0,0] - qml.TShift(wires = 0) + qp.TShift(wires = 0) # We apply our oracle Uf() # We measure the last qutrit - return qml.sample(wires = 3) + return qp.sample(wires = 3) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit1(): # Initialize x = [0,1,0] - qml.TShift(wires = 1) + qp.TShift(wires = 1) # We apply our oracle Uf() # We measure the last qutrit - return qml.sample(wires = 3) + return qp.sample(wires = 3) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit2(): # Initialize x = [0,0,1] - qml.TShift(wires = 2) + qp.TShift(wires = 2) # We apply our oracle Uf() # We measure the last qutrit - return qml.sample(wires = 3) + return qp.sample(wires = 3) # Run to obtain the three trits of a a0 = circuit0() @@ -321,26 +321,26 @@ def circuit2(): # Let's go to the code and see how to run this in PennyLane. -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def circuit(): # We initialize to |0001> - qml.TShift(wires = 3) + qp.TShift(wires = 3) # We run the THadamard for i in range(4): - qml.THadamard(wires = i) + qp.THadamard(wires = i) # We run the oracle Uf() # We run the THadamard again for i in range(3): - qml.THadamard(wires = i) + qp.THadamard(wires = i) # We measure the first 3 qutrits - return qml.sample(wires = range(3)) + return qp.sample(wires = range(3)) a = circuit() diff --git a/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/metadata.json b/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/metadata.json index 6e7db66160..39a19c531d 100644 --- a/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/metadata.json +++ b/demonstrations_v2/tutorial_qutrits_bernstein_vazirani/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-05-09T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_resource_estimation/demo.py b/demonstrations_v2/tutorial_resource_estimation/demo.py index 81648ed18a..3bf3dc69e2 100644 --- a/demonstrations_v2/tutorial_resource_estimation/demo.py +++ b/demonstrations_v2/tutorial_resource_estimation/demo.py @@ -46,7 +46,7 @@ For most cases of interest, this algorithm requires more qubits and longer circuit depths than what can be implemented on existing hardware. The PennyLane functionality in the -:mod:`qml.estimator ` module allows us to estimate the number of logical qubits +:mod:`qp.estimator ` module allows us to estimate the number of logical qubits and the number of non-Clifford gates that are needed to implement the algorithm. We can estimate these resources by simply defining system specifications and a target error for estimation. Let's see how! @@ -62,7 +62,7 @@ the water molecule at its equilibrium geometry with the `6-31g basis set `_ as an example. """ -import pennylane as qml +import pennylane as qp import numpy as np import jax @@ -77,13 +77,13 @@ # Then we construct a molecule object and compute the one- and two-electron # integrals in the molecular orbital basis. -mol = qml.qchem.Molecule(symbols, geometry, basis_name='6-31g') -core, one, two = qml.qchem.electron_integrals(mol)() +mol = qp.qchem.Molecule(symbols, geometry, basis_name='6-31g') +core, one, two = qp.qchem.electron_integrals(mol)() ############################################################################## # We now create an instance of the :class:`~.pennylane.estimator.qpe_resources.DoubleFactorization` class -algo = qml.estimator.DoubleFactorization(one, two) +algo = qp.estimator.DoubleFactorization(one, two) ############################################################################## # and obtain the estimated number of non-Clifford gates and logical qubits. @@ -97,7 +97,7 @@ chemical_accuracy = 0.0016 error = chemical_accuracy * 10 -algo = qml.estimator.DoubleFactorization(one, two, error=error) +algo = qp.estimator.DoubleFactorization(one, two, error=error) print(f'Estimated gates : {algo.gates:.2e} \nEstimated qubits: {algo.qubits}') ############################################################################## @@ -110,7 +110,7 @@ n_qubits = [] for tol in threshold: - algo_ = qml.estimator.DoubleFactorization(one, two, tol_factor=tol, tol_eigval=tol) + algo_ = qp.estimator.DoubleFactorization(one, two, tol_factor=tol, tol_eigval=tol) n_gates.append(algo_.gates) n_qubits.append(algo_.qubits) @@ -143,7 +143,7 @@ ############################################################################## # We now create an instance of the :class:`~.pennylane.estimator.qpe_resources.FirstQuantization` class -algo = qml.estimator.FirstQuantization(planewaves, electrons, vectors=vectors) +algo = qp.estimator.FirstQuantization(planewaves, electrons, vectors=vectors) ############################################################################## # and obtain the estimated number of non-Clifford gates and logical qubits. @@ -163,7 +163,7 @@ n_qubits_ = [] for pw in planewaves: - algo_ = qml.estimator.FirstQuantization(pw, electrons, vectors=vectors, error=er) + algo_ = qp.estimator.FirstQuantization(pw, electrons, vectors=vectors, error=er) n_gates_.append(algo_.gates) n_qubits_.append(algo_.qubits) n_gates.append(n_gates_) @@ -219,8 +219,8 @@ # # First, we construct the molecular Hamiltonian. -molecule = qml.qchem.Molecule(symbols, geometry) -H = qml.qchem.molecular_hamiltonian(molecule)[0] +molecule = qp.qchem.Molecule(symbols, geometry) +H = qp.qchem.molecular_hamiltonian(molecule)[0] H_coeffs, H_ops = H.terms() ############################################################################## @@ -230,7 +230,7 @@ # :math:`\left \langle H \right \rangle` with a target error set to the chemical accuracy, 0.0016 # :math:`\text{Ha},` is obtained as follows. -m = qml.estimator.estimate_shots(H_coeffs) +m = qp.estimator.estimate_shots(H_coeffs) print(f'Shots : {m:.2e}') ############################################################################## @@ -239,17 +239,17 @@ # :func:`~.pennylane.pauli.group_observables()`, which partitions the Pauli words into # groups of commuting terms that can be measured simultaneously. -ops, coeffs = qml.pauli.group_observables(H_ops, H_coeffs) +ops, coeffs = qp.pauli.group_observables(H_ops, H_coeffs) coeffs = [np.array(c) for c in coeffs] # cast as numpy array -m = qml.estimator.estimate_shots(coeffs) +m = qp.estimator.estimate_shots(coeffs) print(f'Shots : {m:.2e}') ############################################################################## # It is also interesting to illustrate how the number of shots depends on the target error. error = np.array([0.02, 0.015, 0.01, 0.005, 0.001]) -m = [qml.estimator.estimate_shots(H_coeffs, error=er) for er in error] +m = [qp.estimator.estimate_shots(H_coeffs, error=er) for er in error] e_ = np.linspace(error[0], error[-1], num=50) m_ = 1.4e4 / np.linspace(error[0], error[-1], num=50)**2 diff --git a/demonstrations_v2/tutorial_resource_estimation/metadata.json b/demonstrations_v2/tutorial_resource_estimation/metadata.json index 988ff6fe92..ce8aa233a5 100644 --- a/demonstrations_v2/tutorial_resource_estimation/metadata.json +++ b/demonstrations_v2/tutorial_resource_estimation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-11-21T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry" ], diff --git a/demonstrations_v2/tutorial_resource_estimation_QSVT/demo.py b/demonstrations_v2/tutorial_resource_estimation_QSVT/demo.py index 6dd043b96a..0200e26706 100644 --- a/demonstrations_v2/tutorial_resource_estimation_QSVT/demo.py +++ b/demonstrations_v2/tutorial_resource_estimation_QSVT/demo.py @@ -48,11 +48,11 @@ For a recap on this technique, see our demo on `linear combination of unitaries and block encodings `_. """ -import pennylane as qml +import pennylane as qp -A = 0.1 * (qml.Z(0) @ qml.Z(1)) + 0.2 * (qml.X(0) @ qml.X(1)) + 0.3 * (qml.X(0) @ qml.Z(1)) +A = 0.1 * (qp.Z(0) @ qp.Z(1)) + 0.2 * (qp.X(0) @ qp.X(1)) + 0.3 * (qp.X(0) @ qp.Z(1)) -print(qml.matrix(A, wire_order=[0, 1])) +print(qp.matrix(A, wire_order=[0, 1])) ############################################################################## # Resources from an Executable Workflow @@ -73,7 +73,7 @@ poly = (0, 0, 0, 0, 0, 1) # f(x) = x^5 def circ(): - qml.qsvt(A, poly, encoding_wires=encoding_wires) + qp.qsvt(A, poly, encoding_wires=encoding_wires) return ## --- Resource Estimation: --- diff --git a/demonstrations_v2/tutorial_resource_estimation_QSVT/metadata.json b/demonstrations_v2/tutorial_resource_estimation_QSVT/metadata.json index fee8744bdc..f03fe5a910 100644 --- a/demonstrations_v2/tutorial_resource_estimation_QSVT/metadata.json +++ b/demonstrations_v2/tutorial_resource_estimation_QSVT/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2026-02-27T10:00:00+00:00", - "dateOfLastModification": "2026-02-27T10:00:00+00:00", + "dateOfLastModification": "2026-04-17T10:00:00+00:00", "categories": [ "Algorithms" ], diff --git a/demonstrations_v2/tutorial_resourcefulness/demo.py b/demonstrations_v2/tutorial_resourcefulness/demo.py index 4ed0121eb1..85cf63c7ab 100644 --- a/demonstrations_v2/tutorial_resourcefulness/demo.py +++ b/demonstrations_v2/tutorial_resourcefulness/demo.py @@ -359,31 +359,31 @@ def g(x): # -import pennylane as qml +import pennylane as qp from scipy.stats import unitary_group -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def product_state(n_qubits): for i in range(n_qubits): U_haar = unitary_group.rvs(2) - qml.QubitUnitary(U_haar, wires=i) - return qml.state() + qp.QubitUnitary(U_haar, wires=i) + return qp.state() -@qml.qnode(dev) +@qp.qnode(dev) def haar_state(n_qubits): U_haar = unitary_group.rvs(2**n_qubits) - qml.QubitUnitary(U_haar, wires=range(n_qubits)) - return qml.state() + qp.QubitUnitary(U_haar, wires=range(n_qubits)) + return qp.state() -@qml.qnode(dev) +@qp.qnode(dev) def ghz_state(n_qubits): - qml.Hadamard(wires=0) + qp.Hadamard(wires=0) for i in range(1, n_qubits): - qml.CNOT(wires=[0, i]) - return qml.state() + qp.CNOT(wires=[0, i]) + return qp.state() n = 2 states = [product_state(n), haar_state(n), ghz_state(n)] diff --git a/demonstrations_v2/tutorial_resourcefulness/metadata.json b/demonstrations_v2/tutorial_resourcefulness/metadata.json index 2b2a6a0de0..7a1c57243b 100644 --- a/demonstrations_v2/tutorial_resourcefulness/metadata.json +++ b/demonstrations_v2/tutorial_resourcefulness/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-10-30T09:00:00+00:00", - "dateOfLastModification": "2026-02-19T09:00:00+00:00", + "dateOfLastModification": "2026-04-17T09:00:00+00:00", "categories": [ "Quantum Computing" ], diff --git a/demonstrations_v2/tutorial_rl_pulse/demo.py b/demonstrations_v2/tutorial_rl_pulse/demo.py index 0b40f614e2..574a45023e 100644 --- a/demonstrations_v2/tutorial_rl_pulse/demo.py +++ b/demonstrations_v2/tutorial_rl_pulse/demo.py @@ -177,7 +177,7 @@ multi-qubit devices and gates. """ -import pennylane as qml +import pennylane as qp # Quantum computer qubit_freqs = [4.81] # GHz @@ -185,7 +185,7 @@ couplings = [] # No couplings wires = [0] -H_int = qml.pulse.transmon_interaction(qubit_freqs, connections, couplings, wires) +H_int = qp.pulse.transmon_interaction(qubit_freqs, connections, couplings, wires) # Microwave pulse pulse_duration = 22.4 # ns @@ -193,10 +193,10 @@ segment_duration = pulse_duration / n_segments freq = qubit_freqs[0] # Resonant with the qubit -amplitude = qml.pulse.pwc(pulse_duration) -phase = qml.pulse.pwc(pulse_duration) +amplitude = qp.pulse.pwc(pulse_duration) +phase = qp.pulse.pwc(pulse_duration) -H_drive = qml.pulse.transmon_drive(amplitude, phase, freq, wires) +H_drive = qp.pulse.transmon_drive(amplitude, phase, freq, wires) # Full time-dependent parametrized Hamiltonian H = H_int + H_drive @@ -217,16 +217,16 @@ import jax from functools import partial -device = qml.device("default.qubit", wires=1) +device = qp.device("default.qubit", wires=1) @partial(jax.jit, static_argnames="H") @partial(jax.vmap, in_axes=(0, None, 0, None)) -@qml.qnode(device=device, interface="jax") +@qp.qnode(device=device, interface="jax") def evolve_states(state, H, params, t): - qml.StatePrep(state, wires=wires) - qml.evolve(H)(params, t, atol=1e-5) - return qml.state() + qp.StatePrep(state, wires=wires) + qp.evolve(H)(params, t, atol=1e-5) + return qp.state() state_size = 2 ** len(wires) @@ -283,7 +283,7 @@ def evolve_states(state, H, params, t): # named tuple) and the code below will assume this container is being passed. # -target = jnp.array(qml.RX(jnp.pi / 2, 0).matrix()) # RX(pi/2) gate +target = jnp.array(qp.RX(jnp.pi / 2, 0).matrix()) # RX(pi/2) gate @partial(jax.jit, static_argnames=["H", "config"]) @@ -327,7 +327,7 @@ def sample_random_states(subkey, n_states, dim): def get_pulse_matrix(H, params, time): """Compute the unitary matrix associated to the time evolution of H.""" - return qml.evolve(H)(params, time, atol=1e-5).matrix() + return qp.evolve(H)(params, time, atol=1e-5).matrix() @jax.jit @@ -757,9 +757,9 @@ def evaluate_program(pulse_program, H, target, config, subkey): """Compute the average gate fidelity over 1000 random initial states.""" states = sample_random_states(subkey, 1000, state_size) target_states = jnp.einsum("ab,cb->ca", target, states) - pulse_matrix = qml.matrix(qml.evolve(H)(pulse_program, config.pulse_duration)) + pulse_matrix = qp.matrix(qp.evolve(H)(pulse_program, config.pulse_duration)) final_states = jnp.einsum("ab,cb->ca", pulse_matrix, states) - fidelities = qml.math.fidelity_statevector(final_states, target_states) + fidelities = qp.math.fidelity_statevector(final_states, target_states) return fidelities @@ -774,7 +774,7 @@ def evaluate_program(pulse_program, H, target, config, subkey): def vector_to_bloch(vector): """Transform a vector into Bloch sphere coordinates.""" rho = jnp.outer(vector, vector.conj()) - X, Y, Z = qml.PauliX(0).matrix(), qml.PauliY(0).matrix(), qml.PauliZ(0).matrix() + X, Y, Z = qp.PauliX(0).matrix(), qp.PauliY(0).matrix(), qp.PauliZ(0).matrix() x, y, z = ( jnp.trace(rho @ X).real.item(), jnp.trace(rho @ Y).real.item(), @@ -812,12 +812,12 @@ def plot_rotation_axes(rotation_axes, color=["#70CEFF"], fig=None, ax=None): ts = jnp.linspace(0, pulse_duration - 1e-3, 100) fig, axs = plt.subplots(ncols=3, figsize=(14, 4), constrained_layout=True) -axs[0].plot(ts, qml.pulse.pwc(pulse_duration)(pulse_program[0], ts), color="#70CEFF", linewidth=3) +axs[0].plot(ts, qp.pulse.pwc(pulse_duration)(pulse_program[0], ts), color="#70CEFF", linewidth=3) axs[0].set_ylabel("Amplitude (GHz)", fontsize=14) axs[0].set_yticks(values_ampl) axs[0].set_ylim([values_ampl[0], values_ampl[-1]]) -axs[1].plot(ts, qml.pulse.pwc(pulse_duration)(pulse_program[1], ts), color="#FFE096", linewidth=3) +axs[1].plot(ts, qp.pulse.pwc(pulse_duration)(pulse_program[1], ts), color="#FFE096", linewidth=3) axs[1].set_ylabel("Phase (rad)", fontsize=14) axs[1].set_yticks( values_phase, @@ -857,7 +857,7 @@ def plot_rotation_axes(rotation_axes, color=["#70CEFF"], fig=None, ax=None): couplings = [0.02] wires = [0, 1] -H_int = qml.pulse.transmon_interaction(qubit_freqs, connections, couplings, wires) +H_int = qp.pulse.transmon_interaction(qubit_freqs, connections, couplings, wires) ###################################################################### # The CNOT gate is typically constituted by a series of single-qubit pulses and cross-resonant (CR) @@ -883,9 +883,9 @@ def plot_rotation_axes(rotation_axes, color=["#70CEFF"], fig=None, ax=None): def get_drive(timespan, freq, wire): """Parametrized Hamiltonian driving the qubit in wire with a fixed frequency.""" - amplitude = qml.pulse.pwc(timespan) - phase = qml.pulse.pwc(timespan) - return qml.pulse.transmon_drive(amplitude, phase, freq, wire) + amplitude = qp.pulse.pwc(timespan) + phase = qp.pulse.pwc(timespan) + return qp.pulse.transmon_drive(amplitude, phase, freq, wire) pulse_durations = jnp.array( @@ -926,23 +926,23 @@ def get_drive(timespan, freq, wire): @jax.jit @partial(jax.vmap, in_axes=(0, None, 0, None)) -@qml.qnode(device=device, interface="jax") +@qp.qnode(device=device, interface="jax") def evolve_states(state, params, t): params_sq, params_cr = params - qml.StatePrep(state, wires=wires) + qp.StatePrep(state, wires=wires) # Single qubit pulses - qml.evolve(H_int + H_sq_ini)(params_sq, t, atol=1e-5) + qp.evolve(H_int + H_sq_ini)(params_sq, t, atol=1e-5) # Echoed CR - qml.evolve(H_int + H_cr_pos)(params_cr, t, atol=1e-5) - qml.PauliX(0) # Flip control qubit - qml.evolve(H_int - H_cr_neg)(params_cr, t, atol=1e-5) # Negative CR - qml.PauliX(0) # Recover control qubit + qp.evolve(H_int + H_cr_pos)(params_cr, t, atol=1e-5) + qp.PauliX(0) # Flip control qubit + qp.evolve(H_int - H_cr_neg)(params_cr, t, atol=1e-5) # Negative CR + qp.PauliX(0) # Recover control qubit # Single qubit pulses - qml.evolve(H_int + H_sq_end)(params_sq, t, atol=1e-5) + qp.evolve(H_int + H_sq_end)(params_sq, t, atol=1e-5) - return qml.state() + return qp.state() ###################################################################### diff --git a/demonstrations_v2/tutorial_rl_pulse/metadata.json b/demonstrations_v2/tutorial_rl_pulse/metadata.json index a0dbaaf21f..dc6d8e17bf 100644 --- a/demonstrations_v2/tutorial_rl_pulse/metadata.json +++ b/demonstrations_v2/tutorial_rl_pulse/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-04-09T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Getting Started", "Optimization", diff --git a/demonstrations_v2/tutorial_rosalin/demo.py b/demonstrations_v2/tutorial_rosalin/demo.py index b179d3eebc..918fbe718e 100644 --- a/demonstrations_v2/tutorial_rosalin/demo.py +++ b/demonstrations_v2/tutorial_rosalin/demo.py @@ -111,7 +111,7 @@ First, let's import NumPy and PennyLane, and define our Hamiltonian. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np # set the random seed @@ -120,11 +120,11 @@ coeffs = [2, 4, -1, 5, 2] obs = [ - qml.PauliX(1), - qml.PauliZ(1), - qml.PauliX(0) @ qml.PauliX(1), - qml.PauliY(0) @ qml.PauliY(1), - qml.PauliZ(0) @ qml.PauliZ(1) + qp.PauliX(1), + qp.PauliZ(1), + qp.PauliX(0) @ qp.PauliX(1), + qp.PauliY(0) @ qp.PauliY(1), + qp.PauliZ(0) @ qp.PauliZ(1) ] @@ -135,10 +135,10 @@ num_wires = 2 # create a device that estimates expectation values using a finite number of shots -non_analytic_dev = qml.device("default.qubit", wires=num_wires, seed=432423) +non_analytic_dev = qp.device("default.qubit", wires=num_wires, seed=432423) # create a device that calculates exact expectation values -analytic_dev = qml.device("default.qubit", wires=num_wires) +analytic_dev = qp.device("default.qubit", wires=num_wires) ############################################################################## # Now, let's set the total number of shots, and determine the probability @@ -185,11 +185,11 @@ from pennylane.templates.layers import StronglyEntanglingLayers -@qml.set_shots(100) -@qml.qnode(non_analytic_dev, diff_method="parameter-shift", interface="autograd") +@qp.set_shots(100) +@qp.qnode(non_analytic_dev, diff_method="parameter-shift", interface="autograd") def qnode(weights, observable): StronglyEntanglingLayers(weights, wires=non_analytic_dev.wires) - return qml.expval(observable) + return qp.expval(observable) def cost(params): # sample from the multinomial distribution @@ -200,7 +200,7 @@ def cost(params): for o, c, s in zip(obs, coeffs, shots_per_term): # evaluate the QNode corresponding to # the Hamiltonian term, and add it on to our running sum - result += c * qml.set_shots(qnode, shots=int(s))(params, o) + result += c * qp.set_shots(qnode, shots=int(s))(params, o) return result @@ -218,7 +218,7 @@ def cost(params): # Performing the optimization, with the number of shots randomly # determined at each optimization step: -opt = qml.AdamOptimizer(0.05) +opt = qp.AdamOptimizer(0.05) params = init_params cost_wrs = [] @@ -235,11 +235,11 @@ def cost(params): # Here, we will split the 8000 total shots evenly across all Hamiltonian terms, # also known as *uniform deterministic sampling*. -@qml.set_shots(100) -@qml.qnode(non_analytic_dev, diff_method="parameter-shift", interface="autograd") +@qp.set_shots(100) +@qp.qnode(non_analytic_dev, diff_method="parameter-shift", interface="autograd") def qnode(weights, obs): StronglyEntanglingLayers(weights, wires=non_analytic_dev.wires) - return qml.expval(obs) + return qp.expval(obs) def cost(params): shots_per_term = int(total_shots / len(coeffs)) @@ -250,11 +250,11 @@ def cost(params): # evaluate the QNode corresponding to # the Hamiltonian term, and add it on to our running sum - result += c * qml.set_shots(qnode, shots=shots_per_term)(params, o) + result += c * qp.set_shots(qnode, shots=shots_per_term)(params, o) return result -opt = qml.AdamOptimizer(0.05) +opt = qp.AdamOptimizer(0.05) params = init_params cost_adam = [] @@ -438,7 +438,7 @@ def estimate_hamiltonian(self, params, shots): set to 'sample' mode. """ # note that convergence depends on seed for random number generation - rosalin_device = qml.device("default.qubit", wires=num_wires, seed=93754352) + rosalin_device = qp.device("default.qubit", wires=num_wires, seed=93754352) # determine the shot probability per term prob_shots = np.abs(coeffs) / np.sum(np.abs(coeffs)) @@ -450,11 +450,11 @@ def estimate_hamiltonian(self, params, shots): results = [] - @qml.set_shots(100) - @qml.qnode(rosalin_device, diff_method="parameter-shift", interface="autograd") + @qp.set_shots(100) + @qp.qnode(rosalin_device, diff_method="parameter-shift", interface="autograd") def qnode(weights, observable): StronglyEntanglingLayers(weights, wires=rosalin_device.wires) - return qml.sample(observable) + return qp.sample(observable) for o, c, p, s in zip(self.obs, self.coeffs, prob_shots, shots_per_term): @@ -464,7 +464,7 @@ def qnode(weights, observable): # evaluate the QNode corresponding to # the Hamiltonian term - res = qml.set_shots(qnode, shots=int(s))(params, o) + res = qp.set_shots(qnode, shots=int(s))(params, o) # Note that, unlike above, we divide each term by the # probability per shot. This is because we are sampling one at a time. @@ -555,10 +555,10 @@ def step(self, params): # also create a separate cost function using an 'exact' quantum device, so that we can keep track of the # *exact* cost function value at each iteration. -@qml.qnode(analytic_dev, interface="autograd") +@qp.qnode(analytic_dev, interface="autograd") def cost_analytic(weights): StronglyEntanglingLayers(weights, wires=analytic_dev.wires) - return qml.expval(qml.Hamiltonian(coeffs, obs)) + return qp.expval(qp.Hamiltonian(coeffs, obs)) ############################################################################## # Creating the optimizer and beginning the optimization: @@ -589,15 +589,15 @@ def cost_analytic(weights): # Thus, Adam is using 2400 shots per update step. params = init_params -opt = qml.AdamOptimizer(0.07) +opt = qp.AdamOptimizer(0.07) -adam_dev = qml.device('default.qubit', seed=595905) +adam_dev = qp.device('default.qubit', seed=595905) -@qml.set_shots(adam_shots_per_eval) -@qml.qnode(adam_dev, diff_method="parameter-shift", interface="autograd") +@qp.set_shots(adam_shots_per_eval) +@qp.qnode(adam_dev, diff_method="parameter-shift", interface="autograd") def cost(weights): StronglyEntanglingLayers(weights, wires=non_analytic_dev.wires) - return qml.expval(qml.Hamiltonian(coeffs, obs)) + return qp.expval(qp.Hamiltonian(coeffs, obs)) cost_adam = [cost_analytic(params)] shots_adam = [0] diff --git a/demonstrations_v2/tutorial_rosalin/metadata.json b/demonstrations_v2/tutorial_rosalin/metadata.json index 9a97a4c86f..f48d9739b4 100644 --- a/demonstrations_v2/tutorial_rosalin/metadata.json +++ b/demonstrations_v2/tutorial_rosalin/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-05-19T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_rotoselect/demo.py b/demonstrations_v2/tutorial_rotoselect/demo.py index 981ea26c62..c067da0f7c 100644 --- a/demonstrations_v2/tutorial_rotoselect/demo.py +++ b/demonstrations_v2/tutorial_rotoselect/demo.py @@ -122,14 +122,14 @@ # in order to obtain exact values for any expectation values calculated. In contrast to real # devices, simulators have the capability of doing these calculations without sampling. -import pennylane as qml +import pennylane as qp from pennylane import numpy as np np.random.seed(9432092) n_wires = 2 -dev = qml.device("lightning.qubit", wires=2) +dev = qp.device("lightning.qubit", wires=2) ############################################################################## # Creating a fixed quantum circuit @@ -147,23 +147,23 @@ def ansatz(params): - qml.RX(params[0], wires=0) - qml.RY(params[1], wires=1) - qml.CNOT(wires=[0, 1]) + qp.RX(params[0], wires=0) + qp.RY(params[1], wires=1) + qp.CNOT(wires=[0, 1]) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def circuit(params): ansatz(params) - return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1)) + return qp.expval(qp.PauliZ(0)), qp.expval(qp.PauliY(1)) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def circuit2(params): ansatz(params) - return qml.expval(qml.PauliX(0)) + return qp.expval(qp.PauliX(0)) def cost(params): @@ -231,7 +231,7 @@ def rotosolve_cycle(cost, params): # converges on the minimum after the first cycle for this simple circuit. params_gd = init_params.copy() -opt = qml.GradientDescentOptimizer(stepsize=0.5) +opt = qp.GradientDescentOptimizer(stepsize=0.5) costs_gd = [] for i in range(n_steps): costs_gd.append(cost(params_gd)) @@ -316,31 +316,31 @@ def rotosolve_cycle(cost, params): def RGen(param, generator, wires): if generator == "X": - qml.RX(param, wires=wires) + qp.RX(param, wires=wires) elif generator == "Y": - qml.RY(param, wires=wires) + qp.RY(param, wires=wires) elif generator == "Z": - qml.RZ(param, wires=wires) + qp.RZ(param, wires=wires) def ansatz_rsel(params, generators): RGen(params[0], generators[0], wires=0) RGen(params[1], generators[1], wires=1) - qml.CNOT(wires=[0, 1]) + qp.CNOT(wires=[0, 1]) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def circuit_rsel(params, generators): ansatz_rsel(params, generators) - return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1)) + return qp.expval(qp.PauliZ(0)), qp.expval(qp.PauliY(1)) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def circuit_rsel2(params, generators): ansatz_rsel(params, generators) - return qml.expval(qml.PauliX(0)) + return qp.expval(qp.PauliX(0)) def cost_rsel(params, generators): diff --git a/demonstrations_v2/tutorial_rotoselect/metadata.json b/demonstrations_v2/tutorial_rotoselect/metadata.json index d3125fd7f1..4ac44e75c1 100644 --- a/demonstrations_v2/tutorial_rotoselect/metadata.json +++ b/demonstrations_v2/tutorial_rotoselect/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-16T00:00:00+00:00", - "dateOfLastModification": "2025-12-10T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization", "Compilation" diff --git a/demonstrations_v2/tutorial_sc_qubits/demo.py b/demonstrations_v2/tutorial_sc_qubits/demo.py index 47b9a2cfc5..50afa15633 100644 --- a/demonstrations_v2/tutorial_sc_qubits/demo.py +++ b/demonstrations_v2/tutorial_sc_qubits/demo.py @@ -381,8 +381,8 @@ # # Let us see how this works in practice using PennyLane. The ``default.gaussian`` device allows us to simulate # coherent states of light. These states start implicitly in the vacuum (no photons) state. -# The PennyLane function ``qml.Displacement(x,0)`` applies a *displacement operator*, which creates -# a coherent state :math:`\left\lvert \bar{x}, 0\right\rangle.` The rotation operator ``qml.Rotation(phi)`` rotates the state +# The PennyLane function ``qp.Displacement(x,0)`` applies a *displacement operator*, which creates +# a coherent state :math:`\left\lvert \bar{x}, 0\right\rangle.` The rotation operator ``qp.Rotation(phi)`` rotates the state # :math:`\left\lvert \bar{x}, 0\right\rangle` in :math:`(x, p)` space. When applied after a large displacement, # it changes the value of :math:`\bar{x}` only slightly, but noticeably changes the value of :math:`\bar{p}` by shifting it # off from zero, as shown in the figure [#Blais2021]_: @@ -400,12 +400,12 @@ # taking :math:`\omega_r=0,` which simply corresponds to taking :math:`\omega_r` as a reference frequency, so a rotation by # angle :math:`\phi` actually means a rotation by :math:`\omega_r+\phi.` In PennyLane, the operations read: -import pennylane as qml +import pennylane as qp import numpy as np import matplotlib.pyplot as plt # Call the default.gaussian device with 50 shots -dev = qml.device("default.gaussian", wires=1) +dev = qp.device("default.gaussian", wires=1) # Fix parameters epsilon, chi = 1.0, 0.1 @@ -413,20 +413,20 @@ # Implement displacement and rotation and measure both X and P observables -@qml.set_shots(50) -@qml.qnode(dev) +@qp.set_shots(50) +@qp.qnode(dev) def measure_P_shots(time, state): - qml.Displacement(epsilon * time, 0, wires=0) - qml.Rotation((-1) ** state * chi * time, wires=0) - return qml.sample(qml.QuadP(0)) + qp.Displacement(epsilon * time, 0, wires=0) + qp.Rotation((-1) ** state * chi * time, wires=0) + return qp.sample(qp.QuadP(0)) -@qml.set_shots(50) -@qml.qnode(dev) +@qp.set_shots(50) +@qp.qnode(dev) def measure_X_shots(time, state): - qml.Displacement(epsilon * time, 0, wires=0) - qml.Rotation((-1) ** state * chi * time, wires=0) - return qml.sample(qml.QuadX(0)) + qp.Displacement(epsilon * time, 0, wires=0) + qp.Rotation((-1) ** state * chi * time, wires=0) + return qp.sample(qp.QuadX(0)) ############################################################################## @@ -491,46 +491,46 @@ def measure_X_shots(time, state): # applies a :math:`Y`-rotation. # # Let us check this using PennyLane. For qubits, we can define -# Hamiltonians using ``qml.Hamiltonian`` and evolve an initial state using ``ApproxTimeEvolution``: +# Hamiltonians using ``qp.Hamiltonian`` and evolve an initial state using ``ApproxTimeEvolution``: from pennylane.templates import ApproxTimeEvolution -dev2 = qml.device("lightning.qubit", wires=1) +dev2 = qp.device("lightning.qubit", wires=1) # Implement Hamiltonian evolution given phase phi and time t, from a given initial state -@qml.qnode(dev2) +@qp.qnode(dev2) def H_evolve(state, phi, time): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) coeffs = [np.cos(phi), np.sin(phi)] - ops = [qml.PauliX(0), qml.PauliY(0)] - Ham = qml.Hamiltonian(coeffs, ops) + ops = [qp.PauliX(0), qp.PauliY(0)] + Ham = qp.Hamiltonian(coeffs, ops) ApproxTimeEvolution(Ham, time, 1) - return qml.state() + return qp.state() # Implement X rotation exactly -@qml.qnode(dev2) +@qp.qnode(dev2) def Sc_X_rot(state, phi): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) - qml.RX(phi, wires=0) - return qml.state() + qp.RX(phi, wires=0) + return qp.state() # Implement Y rotation exactly -@qml.qnode(dev2) +@qp.qnode(dev2) def Sc_Y_rot(state, phi): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) - qml.RY(phi, wires=0) - return qml.state() + qp.RY(phi, wires=0) + return qp.state() # Print to compare results @@ -607,28 +607,28 @@ def Sc_Y_rot(state, phi): # # when applied for a time :math:`t=3\pi/2J,` as shown with the following PennyLane code: # -dev3 = qml.device("lightning.qubit", wires=2) +dev3 = qp.device("lightning.qubit", wires=2) # Define Hamiltonian coeffs = [0.5, 0.5] -ops = [qml.PauliX(0) @ qml.PauliX(1), qml.PauliY(0) @ qml.PauliY(1)] +ops = [qp.PauliX(0) @ qp.PauliX(1), qp.PauliY(0) @ qp.PauliY(1)] -Two_qubit_H = qml.Hamiltonian(coeffs, ops) +Two_qubit_H = qp.Hamiltonian(coeffs, ops) # Implement Hamiltonian evolution for time t and some initial computational basis state -@qml.qnode(dev3) +@qp.qnode(dev3) def Sc_ISWAP(basis_state, time): - qml.BasisState(basis_state, wires=range(2)) + qp.BasisState(basis_state, wires=range(2)) ApproxTimeEvolution(Two_qubit_H, time, 1) - return qml.state() + return qp.state() # Implement ISWAP exactly -@qml.qnode(dev3) +@qp.qnode(dev3) def iswap(basis_state): - qml.BasisState(basis_state, wires=range(2)) - qml.ISWAP(wires=[0, 1]) - return qml.state() + qp.BasisState(basis_state, wires=range(2)) + qp.ISWAP(wires=[0, 1]) + return qp.state() # Print to compare results @@ -679,17 +679,17 @@ def iswap(basis_state): # We can verify that the circuit above gives us the ``CNOT`` gate up to a global phase using PennyLane: # def cnot_with_iswap(): - qml.RZ(-np.pi / 2, wires=0) - qml.RX(np.pi / 2, wires=1) - qml.RZ(np.pi / 2, wires=1) - qml.ISWAP(wires=[0, 1]) - qml.RX(np.pi / 2, wires=0) - qml.ISWAP(wires=[0, 1]) - qml.RZ(np.pi / 2, wires=1) + qp.RZ(-np.pi / 2, wires=0) + qp.RX(np.pi / 2, wires=1) + qp.RZ(np.pi / 2, wires=1) + qp.ISWAP(wires=[0, 1]) + qp.RX(np.pi / 2, wires=0) + qp.ISWAP(wires=[0, 1]) + qp.RZ(np.pi / 2, wires=1) # Get matrix of circuit above -matrix = qml.matrix(cnot_with_iswap, wire_order=[0, 1])() +matrix = qp.matrix(cnot_with_iswap, wire_order=[0, 1])() # Multiply by a global phase to obtain CNOT (np.exp(1j * np.pi / 4) * matrix).round(2) @@ -729,22 +729,22 @@ def cnot_with_iswap(): # # where :math:`\phi` is the phase of the wave. As promised, we can obtain an entangled state by concatenating # the evolution under this Hamiltonian for a time :math:`t=\tfrac{\pi}{4\Omega}` with :math:`R_x` and :math:`R_y` rotations -# and a ``qml.Hadamard`` gate: +# and a ``qp.Hadamard`` gate: # -@qml.qnode(dev3) +@qp.qnode(dev3) def H_evolve(state, phi, time): # Prepare initial state - qml.BasisState(state, wires=range(2)) + qp.BasisState(state, wires=range(2)) # Define Hamiltonian coeffs = [np.cos(phi), np.sin(phi)] - ops = [qml.PauliZ(0) @ qml.PauliX(1), qml.PauliZ(0) @ qml.PauliY(1)] - Ham = qml.Hamiltonian(coeffs, ops) + ops = [qp.PauliZ(0) @ qp.PauliX(1), qp.PauliZ(0) @ qp.PauliY(1)] + Ham = qp.Hamiltonian(coeffs, ops) # Combine Hamiltonian evolution with single-qubit gates - qml.Hadamard(wires=0) - qml.RX(-np.pi / 2, wires=1) + qp.Hadamard(wires=0) + qp.RX(-np.pi / 2, wires=1) ApproxTimeEvolution(Ham, time, 1) - qml.RZ(-np.pi / 2, wires=0) - return qml.state() + qp.RZ(-np.pi / 2, wires=0) + return qp.state() # Verify that we return maximally entangled state up to a global phase diff --git a/demonstrations_v2/tutorial_sc_qubits/metadata.json b/demonstrations_v2/tutorial_sc_qubits/metadata.json index e109bc232c..436117e895 100644 --- a/demonstrations_v2/tutorial_sc_qubits/metadata.json +++ b/demonstrations_v2/tutorial_sc_qubits/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-03-22T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Hardware", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/demo.py b/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/demo.py index e03d4ab9dc..89ab99a3be 100644 --- a/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/demo.py +++ b/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/demo.py @@ -134,19 +134,19 @@ """ -import pennylane as qml +import pennylane as qp import numpy as np from pennylane import X, Y, Z, I -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") S = [X(0), Y(0), Z(0), I(0)] H = X(0) + Y(0) -@qml.qnode(dev) +@qp.qnode(dev) def evolve(H, t): - qml.evolve(H, t) - return [qml.expval(Om) for Om in S] + qp.evolve(H, t) + return [qp.expval(Om) for Om in S] t = 1. O_t_standard = np.array(evolve(H, t)) @@ -236,7 +236,7 @@ def evolve(H, t): # be implemented on a quantum computer. # -H_S_qubit = qml.pauli_decompose(H_S) +H_S_qubit = qp.pauli_decompose(H_S) H_S_qubit ############################################################################## @@ -247,11 +247,11 @@ def evolve(H, t): A = np.linalg.norm(O_0) -@qml.qnode(dev) +@qp.qnode(dev) def shadow_evolve(H_S_qubit, O_0, t): - qml.StatePrep(O_0 / A, wires=range(2)) - qml.evolve(H_S_qubit, t) - return qml.state() + qp.StatePrep(O_0 / A, wires=range(2)) + qp.evolve(H_S_qubit, t) + return qp.state() O_t_shadow = shadow_evolve(H_S_qubit, O_0, t) * A @@ -263,7 +263,7 @@ def shadow_evolve(H_S_qubit, O_0, t): # # The first result is coming from three independent measurements on a quantum computer after evolution with system Hamiltonian :math:`H.` # This is conceptually very different from the second result where -# :math:`\boldsymbol{O}` is encoded in the state of the shadow system (note the ``qml.state()`` return), which we evolved according to :math:`H_S.` +# :math:`\boldsymbol{O}` is encoded in the state of the shadow system (note the ``qp.state()`` return), which we evolved according to :math:`H_S.` # # In the first case, the measurement is directly obtained, however, # in the shadow Hamiltonian simulation, we need to access the amplitudes of the underlying state. diff --git a/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/metadata.json b/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/metadata.json index 17ef1b5b3d..b1f0d93b9a 100644 --- a/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/metadata.json +++ b/demonstrations_v2/tutorial_shadow_hamiltonian_simulation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-08-06T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Algorithms"