From 89b4a3d391e00b64e1aa4ff19db018eae78b55f5 Mon Sep 17 00:00:00 2001 From: David Date: Fri, 17 Apr 2026 19:28:33 -0400 Subject: [PATCH] qml to qp Batch 7 --- .../tutorial_optimal_control/demo.py | 28 ++-- .../tutorial_optimal_control/metadata.json | 2 +- demonstrations_v2/tutorial_pasqal/demo.py | 20 +-- .../tutorial_pasqal/metadata.json | 2 +- .../tutorial_period_finding/demo.py | 28 ++-- .../tutorial_period_finding/metadata.json | 2 +- .../tutorial_phase_kickback/demo.py | 20 +-- .../tutorial_phase_kickback/metadata.json | 2 +- demonstrations_v2/tutorial_photonics/demo.py | 148 +++++++++--------- .../tutorial_photonics/metadata.json | 2 +- .../demo.py | 42 ++--- .../metadata.json | 2 +- .../tutorial_pulse_programming101/demo.py | 56 +++---- .../metadata.json | 2 +- demonstrations_v2/tutorial_qaoa_intro/demo.py | 62 ++++---- .../tutorial_qaoa_intro/metadata.json | 2 +- .../tutorial_qaoa_maxcut/demo.py | 28 ++-- .../tutorial_qaoa_maxcut/metadata.json | 2 +- demonstrations_v2/tutorial_qcbm/demo.py | 34 ++-- demonstrations_v2/tutorial_qcbm/metadata.json | 2 +- .../tutorial_qchem_external/demo.py | 18 +-- .../tutorial_qchem_external/metadata.json | 2 +- demonstrations_v2/tutorial_qft/demo.py | 32 ++-- demonstrations_v2/tutorial_qft/metadata.json | 2 +- .../tutorial_qft_and_groups/demo.py | 24 +-- .../tutorial_qft_and_groups/metadata.json | 2 +- .../tutorial_qft_arithmetics/demo.py | 92 +++++------ .../tutorial_qft_arithmetics/metadata.json | 2 +- demonstrations_v2/tutorial_qgrnn/demo.py | 32 ++-- .../tutorial_qgrnn/metadata.json | 2 +- .../demo.py | 26 +-- .../metadata.json | 2 +- .../tutorial_qksd_qsp_qualtran/demo.py | 60 +++---- .../tutorial_qksd_qsp_qualtran/metadata.json | 2 +- .../tutorial_qnn_module_torch/demo.py | 18 +-- .../tutorial_qnn_module_torch/metadata.json | 2 +- .../demo.py | 14 +- .../metadata.json | 2 +- demonstrations_v2/tutorial_qpe/demo.py | 18 +-- demonstrations_v2/tutorial_qpe/metadata.json | 2 +- .../tutorial_qsvt_hardware/demo.py | 42 ++--- .../tutorial_qsvt_hardware/metadata.json | 2 +- .../tutorial_quantum_analytic_descent/demo.py | 18 +-- .../metadata.json | 2 +- .../demo.py | 48 +++--- .../metadata.json | 2 +- 46 files changed, 477 insertions(+), 477 deletions(-) diff --git a/demonstrations_v2/tutorial_optimal_control/demo.py b/demonstrations_v2/tutorial_optimal_control/demo.py index 635b8dfa90..36d73a53a9 100644 --- a/demonstrations_v2/tutorial_optimal_control/demo.py +++ b/demonstrations_v2/tutorial_optimal_control/demo.py @@ -444,9 +444,9 @@ def smooth_rectangles(params, t, k=2.0, max_amp=1.0, eps=0.0, T=1.0): # up the subsequent executions a lot. For optimization workflows of small-scale # functions, this almost always pays off. -import pennylane as qml +import pennylane as qp -X, Y, Z = qml.PauliX, qml.PauliY, qml.PauliZ +X, Y, Z = qp.PauliX, qp.PauliY, qp.PauliZ num_wires = 2 # Hamiltonian terms of the drift and parametrized parts of H @@ -455,20 +455,20 @@ def smooth_rectangles(params, t, k=2.0, max_amp=1.0, eps=0.0, T=1.0): # Coefficients: 1 for drift Hamiltonian and smooth rectangles for parametrized part coeffs = [1.0, 1.0] + [S_k for op in ops_param] # Build H -H = qml.dot(coeffs, ops_H_d + ops_param) +H = qp.dot(coeffs, ops_H_d + ops_param) # Set tolerances for the ODE solver atol = rtol = 1e-10 # Target unitary is CNOT. We get its matrix and note that we do not need the dagger # because CNOT is Hermitian. -target = qml.CNOT([0, 1]).matrix() +target = qp.CNOT([0, 1]).matrix() target_name = "CNOT" print(f"Our target unitary is a {target_name} gate, with matrix\n{target.astype('int')}") def pulse_matrix(params): """Compute the unitary time evolution matrix of the pulse for given parameters.""" - return qml.evolve(H, atol=atol, rtol=rtol)(params, T).matrix() + return qp.evolve(H, atol=atol, rtol=rtol)(params, T).matrix() @jax.jit @@ -644,20 +644,20 @@ def plot_optimal_pulses(hist, pulse_fn, ops, T, target_name): # Coefficients: 1. for drift Hamiltonian and smooth rectangles for parametrized part coeffs = [1.0, 1.0, 1.0] + [S_k for op in ops_param] # Build H -H = qml.dot(coeffs, ops_H_d + ops_param) +H = qp.dot(coeffs, ops_H_d + ops_param) # Set tolerances for the ODE solver atol = rtol = 1e-10 # Target unitary is Toffoli. We get its matrix and note that we do not need the dagger # because Toffoli is Hermitian and unitary. -target = qml.Toffoli([0, 1, 2]).matrix() +target = qp.Toffoli([0, 1, 2]).matrix() target_name = "Toffoli" print(f"Our target unitary is a {target_name} gate, with matrix\n{target.astype('int')}") def pulse_matrix(params): """Compute the unitary time evolution matrix of the pulse for given parameters.""" - return qml.evolve(H, atol=atol, rtol=rtol)(params, T).matrix() + return qp.evolve(H, atol=atol, rtol=rtol)(params, T).matrix() @jax.jit @@ -697,18 +697,18 @@ def profit(params): # flip the third qubit, returning a probability of one in the last entry # and zeros elsewhere. -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def node(params): # Prepare |110> - qml.PauliX(0) - qml.PauliX(1) + qp.PauliX(0) + qp.PauliX(1) # Apply pulse sequence - qml.evolve(H, atol=atol, rtol=rtol)(params, T) + qp.evolve(H, atol=atol, rtol=rtol)(params, T) # Return quantum state - return qml.probs() + return qp.probs() probs = node(max_params) diff --git a/demonstrations_v2/tutorial_optimal_control/metadata.json b/demonstrations_v2/tutorial_optimal_control/metadata.json index 66c1448139..51663872b5 100644 --- a/demonstrations_v2/tutorial_optimal_control/metadata.json +++ b/demonstrations_v2/tutorial_optimal_control/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-08-08T00:00:00+00:00", - "dateOfLastModification": "2025-12-10T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_pasqal/demo.py b/demonstrations_v2/tutorial_pasqal/demo.py index 2731d65864..0d646ee6ca 100644 --- a/demonstrations_v2/tutorial_pasqal/demo.py +++ b/demonstrations_v2/tutorial_pasqal/demo.py @@ -152,11 +152,11 @@ # We will need to provide this device with the ``ThreeDQubit`` object that we created # above. We also need to instantiate the device with a fixed control radius. -import pennylane as qml +import pennylane as qp num_wires = len(qubits) control_radius = 32.4 -dev = qml.device("cirq.pasqal", control_radius=control_radius, +dev = qp.device("cirq.pasqal", control_radius=control_radius, qubits=qubits, wires=num_wires) ############################################################################## @@ -263,28 +263,28 @@ peak_qubit = 8 def controlled_rotation(phi, wires): - qml.RY(phi, wires=wires[1]) - qml.CNOT(wires=wires) - qml.RY(-phi, wires=wires[1]) - qml.CNOT(wires=wires) + qp.RY(phi, wires=wires[1]) + qp.CNOT(wires=wires) + qp.RY(-phi, wires=wires[1]) + qp.CNOT(wires=wires) -@qml.qnode(dev, interface="tf") +@qp.qnode(dev, interface="tf") def circuit(weights, data): # Input classical data loaded into qubits at second level for idx in range(4): if data[idx]: - qml.PauliX(wires=idx) + qp.PauliX(wires=idx) # Interact qubits from second and third levels for idx in range(4): - qml.CNOT(wires=[idx, idx + 4]) + qp.CNOT(wires=[idx, idx + 4]) # Interact qubits from third level with peak using parameterized gates for idx, wire in enumerate(range(4, 8)): controlled_rotation(weights[idx], wires=[wire, peak_qubit]) - return qml.expval(qml.PauliZ(wires=peak_qubit)) + return qp.expval(qp.PauliZ(wires=peak_qubit)) ############################################################################## diff --git a/demonstrations_v2/tutorial_pasqal/metadata.json b/demonstrations_v2/tutorial_pasqal/metadata.json index a86cb969b4..3909d9b049 100644 --- a/demonstrations_v2/tutorial_pasqal/metadata.json +++ b/demonstrations_v2/tutorial_pasqal/metadata.json @@ -8,7 +8,7 @@ "executable_stable": false, "executable_latest": false, "dateOfPublication": "2020-10-13T00:00:00+00:00", - "dateOfLastModification": "2026-02-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Hardware", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_period_finding/demo.py b/demonstrations_v2/tutorial_period_finding/demo.py index a8cedd5348..74f632394b 100644 --- a/demonstrations_v2/tutorial_period_finding/demo.py +++ b/demonstrations_v2/tutorial_period_finding/demo.py @@ -98,7 +98,7 @@ # Implementation of period finding in PennyLane # ---------------- -import pennylane as qml +import pennylane as qp import numpy as np import matplotlib.pyplot as plt @@ -194,7 +194,7 @@ def Oracle(f): # check that this is a unitary assert np.allclose(U @ np.linalg.inv(U), np.eye(2**7)) - return qml.QubitUnitary(U, wires=range(7)) + return qp.QubitUnitary(U, wires=range(7)) ##################################################################### @@ -208,28 +208,28 @@ def Oracle(f): # reason we define a device with 2 shots. We also add some snapshots to the circuit that we will look at later. -dev = qml.device("default.qubit", wires=7) +dev = qp.device("default.qubit", wires=7) -@qml.set_shots(2) -@qml.qnode(dev) +@qp.set_shots(2) +@qp.qnode(dev) def circuit(): """Circuit to implement the period finding algorithm.""" for i in range(4): - qml.Hadamard(wires=i) + qp.Hadamard(wires=i) - qml.Snapshot("initial_state") + qp.Snapshot("initial_state") Oracle(f) - qml.Snapshot("loaded_function") + qp.Snapshot("loaded_function") - qml.QFT(wires=range(4)) + qp.QFT(wires=range(4)) - qml.Snapshot("fourier_spectrum") + qp.Snapshot("fourier_spectrum") - return qml.sample(wires=range(4)) + return qp.sample(wires=range(4)) # take two samples from the circuit @@ -271,9 +271,9 @@ def circuit(): # look at the states that were prepared by making use of the snapshots we recorded during the # circuit simulation. -dev = qml.device("default.qubit", wires=7) -qnode = qml.set_shots(qml.QNode(circuit, dev), shots = 1) -intermediate_states = qml.snapshots(circuit)() +dev = qp.device("default.qubit", wires=7) +qnode = qp.set_shots(qp.QNode(circuit, dev), shots = 1) +intermediate_states = qp.snapshots(circuit)() ##################################################################### # We can plot them as discrete functions, where the size of a point indicates the absolute value diff --git a/demonstrations_v2/tutorial_period_finding/metadata.json b/demonstrations_v2/tutorial_period_finding/metadata.json index a3a560e988..3384381242 100644 --- a/demonstrations_v2/tutorial_period_finding/metadata.json +++ b/demonstrations_v2/tutorial_period_finding/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-04-16T10:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms" ], diff --git a/demonstrations_v2/tutorial_phase_kickback/demo.py b/demonstrations_v2/tutorial_phase_kickback/demo.py index aa0ec72bab..8fffa6d831 100644 --- a/demonstrations_v2/tutorial_phase_kickback/demo.py +++ b/demonstrations_v2/tutorial_phase_kickback/demo.py @@ -45,11 +45,11 @@ # circuits. Here we will work with 5 qubits, we will use qubit [0] as the control ancilla qubit, and qubits [1,2,3,4] will be our target qubits where we will encode :math:`|\psi\rangle.` # -import pennylane as qml +import pennylane as qp import numpy as np num_wires = 5 -dev = qml.device("default.qubit", wires=num_wires) +dev = qp.device("default.qubit", wires=num_wires) ###################################################################### # Building the quantum lock @@ -83,7 +83,7 @@ def quantum_lock(secret_key): - return qml.FlipSign(secret_key, wires=list(range(1, num_wires))) + return qp.FlipSign(secret_key, wires=list(range(1, num_wires))) ###################################################################### @@ -93,7 +93,7 @@ def quantum_lock(secret_key): def build_key(key): - return qml.BasisState(key, wires=list(range(1, num_wires))) + return qp.BasisState(key, wires=list(range(1, num_wires))) ###################################################################### @@ -101,14 +101,14 @@ def build_key(key): # -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def quantum_locking_mechanism(lock, key): build_key(key) - qml.Hadamard(wires=0) # Hadamard on ancilla qubit - qml.ctrl(lock, control=0) # Controlled unitary operation - qml.Hadamard(wires=0) # Hadamard again on ancilla qubit - return qml.sample(wires=0) + qp.Hadamard(wires=0) # Hadamard on ancilla qubit + qp.ctrl(lock, control=0) # Controlled unitary operation + qp.Hadamard(wires=0) # Hadamard again on ancilla qubit + return qp.sample(wires=0) def check_key(lock, key): diff --git a/demonstrations_v2/tutorial_phase_kickback/metadata.json b/demonstrations_v2/tutorial_phase_kickback/metadata.json index 7bb354424b..3c3e228636 100644 --- a/demonstrations_v2/tutorial_phase_kickback/metadata.json +++ b/demonstrations_v2/tutorial_phase_kickback/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-08-01T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Getting Started", "Algorithms", diff --git a/demonstrations_v2/tutorial_photonics/demo.py b/demonstrations_v2/tutorial_photonics/demo.py index 4ff7294302..d71d21a651 100644 --- a/demonstrations_v2/tutorial_photonics/demo.py +++ b/demonstrations_v2/tutorial_photonics/demo.py @@ -128,7 +128,7 @@ # states of light. Let's first call the usual imports, # -import pennylane as qml +import pennylane as qp from pennylane import numpy as np import matplotlib.pyplot as plt @@ -136,7 +136,7 @@ # # and define the device. -dev = qml.device("default.gaussian", wires=1) +dev = qp.device("default.gaussian", wires=1) ############################################################################## # @@ -154,16 +154,16 @@ # We plot 1000 measurement results for both :math:`x` and :math:`p.` -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def vacuum_measure_x(): - return qml.sample(qml.QuadX(0)) # Samples X quadratures + return qp.sample(qp.QuadX(0)) # Samples X quadratures -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def vacuum_measure_p(): - return qml.sample(qml.QuadP(0)) # Samples P quadrature + return qp.sample(qp.QuadP(0)) # Samples P quadrature # Sample measurements in phase space @@ -197,27 +197,27 @@ def vacuum_measure_p(): # origin with a spread of approximately 1. We can check these eyeballed values explicitly, # using a device without shots this time. -dev_exact = qml.device("default.gaussian", wires=1) # No explicit shots gives analytic calculations +dev_exact = qp.device("default.gaussian", wires=1) # No explicit shots gives analytic calculations -@qml.qnode(dev_exact) +@qp.qnode(dev_exact) def vacuum_mean_x(): - return qml.expval(qml.QuadX(0)) # Returns exact expecation value of x + return qp.expval(qp.QuadX(0)) # Returns exact expecation value of x -@qml.qnode(dev_exact) +@qp.qnode(dev_exact) def vacuum_mean_p(): - return qml.expval(qml.QuadP(0)) # Returns exact expectation value of p + return qp.expval(qp.QuadP(0)) # Returns exact expectation value of p -@qml.qnode(dev_exact) +@qp.qnode(dev_exact) def vacuum_var_x(): - return qml.var(qml.QuadX(0)) # Returns exact variance of x + return qp.var(qp.QuadX(0)) # Returns exact variance of x -@qml.qnode(dev_exact) +@qp.qnode(dev_exact) def vacuum_var_p(): - return qml.var(qml.QuadP(0)) # Returns exact variance of p + return qp.var(qp.QuadP(0)) # Returns exact variance of p # Print calculated statistical quantities @@ -273,18 +273,18 @@ def vacuum_var_p(): # Let us plot sample quadrature measurements for a coherent state. -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def measure_coherent_x(alpha, phi): - qml.CoherentState(alpha, phi, wires=0) # Prepares coherent state - return qml.sample(qml.QuadX(0)) # Measures X quadrature + qp.CoherentState(alpha, phi, wires=0) # Prepares coherent state + return qp.sample(qp.QuadX(0)) # Measures X quadrature -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def measure_coherent_p(alpha, phi): - qml.CoherentState(alpha, phi, wires=0) # Prepares coherent state - return qml.sample(qml.QuadP(0)) # Measures P quadrature + qp.CoherentState(alpha, phi, wires=0) # Prepares coherent state + return qp.sample(qp.QuadP(0)) # Measures P quadrature # Choose alpha and phi and sample 1000 measurements @@ -357,20 +357,20 @@ def measure_coherent_p(alpha, phi): # Let's see the effect of this operation on an intial coherent state. -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def displace_coherent_x(alpha, phi, x): - qml.CoherentState(alpha, phi, wires = 0) # Create coherent state - qml.Displacement(x, 0, wires = 0) # Second argument is the displacement direction in phase space - return qml.sample(qml.QuadX(0)) + qp.CoherentState(alpha, phi, wires = 0) # Create coherent state + qp.Displacement(x, 0, wires = 0) # Second argument is the displacement direction in phase space + return qp.sample(qp.QuadX(0)) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def displace_coherent_p(alpha, phi, x): - qml.CoherentState(alpha, phi, wires = 0) - qml.Displacement(x, 0, wires = 0) - return qml.sample(qml.QuadP(0)) + qp.CoherentState(alpha, phi, wires = 0) + qp.Displacement(x, 0, wires = 0) + return qp.sample(qp.QuadP(0)) # We plot both the initial and displaced state @@ -424,25 +424,25 @@ def displace_coherent_p(alpha, phi, x): # Let us be mindful that this will only work when the amplitude of the input state is much smaller # than that of the auxiliary coherent state. -dev2 = qml.device("default.gaussian", wires=2) +dev2 = qp.device("default.gaussian", wires=2) -@qml.set_shots(1000) -@qml.qnode(dev2) +@qp.set_shots(1000) +@qp.qnode(dev2) def disp_optics(z, x): - qml.CoherentState(z, 0, wires = 0) # High-amplitude auxiliary coherent state - qml.CoherentState(3, np.pi / 3, wires = 1) # Input state (e.g. low amplitude coherent state) - qml.Beamsplitter(np.arccos(1 - x ** 2 / z ** 2), 0, wires=[0, 1]) # Beamsplitter - return qml.sample(qml.QuadX(1)) # Measure x quadrature + qp.CoherentState(z, 0, wires = 0) # High-amplitude auxiliary coherent state + qp.CoherentState(3, np.pi / 3, wires = 1) # Input state (e.g. low amplitude coherent state) + qp.Beamsplitter(np.arccos(1 - x ** 2 / z ** 2), 0, wires=[0, 1]) # Beamsplitter + return qp.sample(qp.QuadX(1)) # Measure x quadrature -@qml.set_shots(1000) -@qml.qnode(dev2) +@qp.set_shots(1000) +@qp.qnode(dev2) def mom_optics(z, x): - qml.CoherentState(z, 0, wires = 0) - qml.CoherentState(3, np.pi / 3, wires = 1) - qml.Beamsplitter(np.arccos(1 - x ** 2 / z ** 2), 0, wires = [0, 1]) - return qml.sample(qml.QuadP(1)) # Measure p quadrature + qp.CoherentState(z, 0, wires = 0) + qp.CoherentState(3, np.pi / 3, wires = 1) + qp.Beamsplitter(np.arccos(1 - x ** 2 / z ** 2), 0, wires = [0, 1]) + return qp.sample(qp.QuadP(1)) # Measure p quadrature # Plot quadrature measurement before and after implementation of displacement @@ -506,18 +506,18 @@ def mom_optics(z, x): # of quadrature measurements. -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def measure_squeezed_x(r): - qml.Squeezing(r, 0, wires = 0) - return qml.sample(qml.QuadX(0)) + qp.Squeezing(r, 0, wires = 0) + return qp.sample(qp.QuadX(0)) -@qml.set_shots(1000) -@qml.qnode(dev) +@qp.set_shots(1000) +@qp.qnode(dev) def measure_squeezed_p(r): - qml.Squeezing(r, 0, wires = 0) - return qml.sample(qml.QuadP(0)) + qp.Squeezing(r, 0, wires = 0) + return qp.sample(qp.QuadP(0)) # Choose alpha and phi and sample 1000 measurements @@ -583,13 +583,13 @@ def measure_squeezed_p(r): # are superpositions of Fock States, including Gaussian states! # For example, let's measure the expected photon number for some squeezed state: -dev3 = qml.device("default.gaussian", wires=1) +dev3 = qp.device("default.gaussian", wires=1) -@qml.qnode(dev3) +@qp.qnode(dev3) def measure_n_coherent(alpha, phi): - qml.Squeezing(alpha, phi, wires = 0) - return qml.expval(qml.NumberOperator(0)) + qp.Squeezing(alpha, phi, wires = 0) + return qp.expval(qp.NumberOperator(0)) coherent_expval = measure_n_coherent(1, np.pi / 3) @@ -614,28 +614,28 @@ def measure_n_coherent(alpha, phi): # # Let's code this setup using PennyLane and check that it amounts to the measurement of quadratures. -dev_exact2 = qml.device("default.gaussian", wires = 2) +dev_exact2 = qp.device("default.gaussian", wires = 2) -@qml.qnode(dev_exact2) +@qp.qnode(dev_exact2) def measurement(a, phi): - qml.Displacement(a, phi, wires = 0) # Implement displacement using PennyLane - return qml.expval(qml.QuadX(0)) + qp.Displacement(a, phi, wires = 0) # Implement displacement using PennyLane + return qp.expval(qp.QuadX(0)) -@qml.qnode(dev_exact2) +@qp.qnode(dev_exact2) def measurement2_0(a, theta, alpha, phi): - qml.Displacement(a, theta, wires = 0) # We choose the initial to be a displaced vacuum - qml.CoherentState(alpha, phi, wires = 1) # Prepare coherent as second qumode - qml.Beamsplitter(np.pi / 4, 0, wires=[0, 1]) # Interfere both states - return qml.expval(qml.NumberOperator(0)) # Read out N + qp.Displacement(a, theta, wires = 0) # We choose the initial to be a displaced vacuum + qp.CoherentState(alpha, phi, wires = 1) # Prepare coherent as second qumode + qp.Beamsplitter(np.pi / 4, 0, wires=[0, 1]) # Interfere both states + return qp.expval(qp.NumberOperator(0)) # Read out N -@qml.qnode(dev_exact2) +@qp.qnode(dev_exact2) def measurement2_1(a, theta, alpha, phi): - qml.Displacement(a, theta, wires = 0) # We choose the initial to be a displaced vacuum - qml.CoherentState(alpha, phi, wires = 1) # Prepare coherent as second qumode - qml.Beamsplitter(np.pi / 4, 0, wires=[0, 1]) # Interfere both states - return qml.expval(qml.NumberOperator(1)) # Read out N + qp.Displacement(a, theta, wires = 0) # We choose the initial to be a displaced vacuum + qp.CoherentState(alpha, phi, wires = 1) # Prepare coherent as second qumode + qp.Beamsplitter(np.pi / 4, 0, wires=[0, 1]) # Interfere both states + return qp.expval(qp.NumberOperator(1)) # Read out N print( diff --git a/demonstrations_v2/tutorial_photonics/metadata.json b/demonstrations_v2/tutorial_photonics/metadata.json index fe69c53263..850cabed1d 100644 --- a/demonstrations_v2/tutorial_photonics/metadata.json +++ b/demonstrations_v2/tutorial_photonics/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-05-31T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Hardware", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/demo.py b/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/demo.py index 77e5e2500b..6485c2677e 100644 --- a/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/demo.py +++ b/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/demo.py @@ -83,7 +83,7 @@ # testing. # -import pennylane as qml +import pennylane as qp from pennylane import numpy as np import jax from jax import numpy as jnp @@ -182,35 +182,35 @@ def feature_map(features): # Apply Hadamard gates to all qubits to create an equal superposition state for i in range(len(features[0])): - qml.Hadamard(i) + qp.Hadamard(i) # Apply angle embeddings based on the feature values for i in range(len(features)): # For odd-indexed features, use Z-rotation in the angle embedding if i % 2: - qml.AngleEmbedding(features=features[i], wires=range(8), rotation="Z") + qp.AngleEmbedding(features=features[i], wires=range(8), rotation="Z") # For even-indexed features, use X-rotation in the angle embedding else: - qml.AngleEmbedding(features=features[i], wires=range(8), rotation="X") + qp.AngleEmbedding(features=features[i], wires=range(8), rotation="X") # Define the ansatz (quantum circuit ansatz) for parameterized quantum operations def ansatz(params): # Apply RY rotations with the first set of parameters for i in range(8): - qml.RY(params[i], wires=i) + qp.RY(params[i], wires=i) # Apply CNOT gates with adjacent qubits (cyclically connected) to create entanglement for i in range(8): - qml.CNOT(wires=[(i - 1) % 8, (i) % 8]) + qp.CNOT(wires=[(i - 1) % 8, (i) % 8]) # Apply RY rotations with the second set of parameters for i in range(8): - qml.RY(params[i + 8], wires=i) + qp.RY(params[i + 8], wires=i) # Apply CNOT gates with qubits in reverse order (cyclically connected) # to create additional entanglement for i in range(8): - qml.CNOT(wires=[(8 - 2 - i) % 8, (8 - i - 1) % 8]) + qp.CNOT(wires=[(8 - 2 - i) % 8, (8 - i - 1) % 8]) ###################################################################### # Variational approach # --------------------- @@ -222,14 +222,14 @@ def ansatz(params): # ansatz. # -dev = qml.device("default.qubit", wires=8) +dev = qp.device("default.qubit", wires=8) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(params, features): feature_map(features) ansatz(params) - return qml.expval(qml.PauliZ(0)) + return qp.expval(qp.PauliZ(0)) def variational_classifier(weights, bias, x): @@ -237,7 +237,7 @@ def variational_classifier(weights, bias, x): def square_loss(labels, predictions): - return np.mean((labels - qml.math.stack(predictions)) ** 2) + return np.mean((labels - qp.math.stack(predictions)) ** 2) def accuracy(labels, predictions): @@ -355,10 +355,10 @@ def generate_paulis(identities: int, paulis: int, output: str, qubits: int, loca print(str(locality) + "-local: ") # Define a quantum device with 8 qubits using the default simulator. - dev = qml.device("default.qubit", wires=8) + dev = qp.device("default.qubit", wires=8) # Define a quantum node (qnode) with the quantum circuit that will be executed on the device. - @qml.qnode(dev) + @qp.qnode(dev) def circuit(features): # Generate all possible Pauli strings for the given locality. measurements = local_pauli_group(8, locality) @@ -367,7 +367,7 @@ def circuit(features): feature_map(features) # Measure the expectation values of the generated Pauli operators. - return [qml.expval(qml.pauli.string_to_pauli_word(measurement)) for measurement in measurements] + return [qp.expval(qp.pauli.string_to_pauli_word(measurement)) for measurement in measurements] # Vectorize the quantum circuit function to apply it to multiple data points in parallel. vcircuit = jax.vmap(circuit) @@ -498,14 +498,14 @@ def generate_shifts(thetas: int, order: int): # n_wires = 8 -dev = qml.device("default.qubit", wires=n_wires) +dev = qp.device("default.qubit", wires=n_wires) @jax.jit -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit(features, params, n_wires=8): feature_map(features) ansatz(params) - return qml.expval(qml.PauliZ(0)) + return qp.expval(qp.PauliZ(0)) ###################################################################### # For each image sample, we measure the outputs of each parameterised circuit for each feature, and @@ -612,20 +612,20 @@ def circuit(features, params, n_wires=8): print("Locality: " + str(locality) + " Order: " + str(order)) # Define a quantum device with 8 qubits using the default simulator. - dev = qml.device("default.qubit", wires=8) + dev = qp.device("default.qubit", wires=8) # Generate the parameter shifts required for the given derivative order and transpose them. params = deriv_params(16, order).T # Define a quantum node (qnode) with the quantum circuit that will be executed on the device. - @qml.qnode(dev) + @qp.qnode(dev) def circuit(features, params): # Generate the Pauli group for the given locality. measurements = local_pauli_group(8, locality) feature_map(features) ansatz(params) # Measure the expectation values of the generated Pauli operators. - return [qml.expval(qml.pauli.string_to_pauli_word(measurement)) for measurement in measurements] + return [qp.expval(qp.pauli.string_to_pauli_word(measurement)) for measurement in measurements] # Vectorize the quantum circuit function to apply it to multiple data points in parallel. vcircuit = jax.vmap(circuit) diff --git a/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/metadata.json b/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/metadata.json index 5b17127241..d0f17a8a10 100644 --- a/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/metadata.json +++ b/demonstrations_v2/tutorial_post-variational_quantum_neural_networks/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-10-07T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning", "Algorithms", diff --git a/demonstrations_v2/tutorial_pulse_programming101/demo.py b/demonstrations_v2/tutorial_pulse_programming101/demo.py index f6cf3c50a1..55ae9b705b 100644 --- a/demonstrations_v2/tutorial_pulse_programming101/demo.py +++ b/demonstrations_v2/tutorial_pulse_programming101/demo.py @@ -59,7 +59,7 @@ The Hamiltonian depends on the set of parameters :math:`p = \{p_i\}.` One way to do this in PennyLane is in the following way: """ -import pennylane as qml +import pennylane as qp import numpy as np import jax.numpy as jnp import jax @@ -80,7 +80,7 @@ def f2(p, t): return p[0] * jnp.sin(p[1] * t) -Ht = f1 * qml.PauliX(0) + f2 * qml.PauliY(1) +Ht = f1 * qp.PauliX(0) + f2 * qp.PauliY(1) ############################################################################## # This constructs a :class:`~pennylane.pulse.ParametrizedHamiltonian`. Note that the ``callable`` functions ``f1`` and ``f2`` @@ -95,16 +95,16 @@ def f2(p, t): ############################################################################## # We can construct general Hamiltonians of the form :math:`\sum_i H_i^d + \sum_i f_i(p_i, t) H_i` -# using :func:`qml.dot `. Such a time-dependent Hamiltonian consists of time-independent drift terms :math:`H_i^d` +# using :func:`qp.dot `. Such a time-dependent Hamiltonian consists of time-independent drift terms :math:`H_i^d` # and time-dependent control terms :math:`f_i(p_i, t) H_i` with scalar complex-valued functions :math:`f_i(p, t).` # In the following we are going to construct :math:`\sum_i X_i X_{i+1} + \sum_i f_i(p_i, t) Z_i` with :math:`f_i(p_i, t) = \sin(p_i^0 t) + \sin(p_i^1 t) \forall i` as an example: coeffs = [1.0] * 2 coeffs += [lambda p, t: jnp.sin(p[0] * t) + jnp.sin(p[1] * t) for _ in range(3)] -ops = [qml.PauliX(i) @ qml.PauliX(i + 1) for i in range(2)] -ops += [qml.PauliZ(i) for i in range(3)] +ops = [qp.PauliX(i) @ qp.PauliX(i + 1) for i in range(2)] +ops += [qp.PauliZ(i) for i in range(3)] -Ht = qml.dot(coeffs, ops) +Ht = qp.dot(coeffs, ops) # random coefficients key = jax.random.PRNGKey(777) @@ -136,17 +136,17 @@ def f2(p, t): # gate :math:`U(t_0, t_1),` which implicitly depends on the parameters ``p`.` The objective of the program # is then to compute the expectation value of some objective Hamiltonian ``H_obj`` (here :math:`\sum_i Z_i` as a simple example). -dev = qml.device("default.qubit", range(4)) +dev = qp.device("default.qubit", range(4)) ts = jnp.array([0.0, 3.0]) -H_obj = sum([qml.PauliZ(i) for i in range(4)]) +H_obj = sum([qp.PauliZ(i) for i in range(4)]) @jax.jit -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def qnode(params): - qml.evolve(Ht)(params, ts) - return qml.expval(H_obj) + qp.evolve(Ht)(params, ts) + return qp.expval(H_obj) print(qnode(params)) @@ -181,7 +181,7 @@ def qnode(params): # by providing a ``timespan`` argument which is expected to be either a total time (``float``) or a start and end time (``tuple``). timespan = 10.0 -coeffs = [qml.pulse.pwc(timespan) for _ in range(2)] +coeffs = [qp.pulse.pwc(timespan) for _ in range(2)] ############################################################################## # This creates a callable with signature ``(p, t)`` that returns ``p[int(len(p)*t/duration)]``, such that the passed parameters are the function values @@ -208,12 +208,12 @@ def qnode(params): ############################################################################## # We can use these callables as before to construct a :func:`~.pennylane.pulse.ParametrizedHamiltonian`. -ops = [qml.PauliX(i) for i in range(2)] -H = qml.pulse.ParametrizedHamiltonian(coeffs, ops) +ops = [qp.PauliX(i) for i in range(2)] +H = qp.pulse.ParametrizedHamiltonian(coeffs, ops) print(H(theta, 0.5)) ############################################################################## -# Note that this construction is equivalent to using :func:`qml.dot `. +# Note that this construction is equivalent to using :func:`qp.dot `. # # Variational quantum eigensolver with pulse programming # ------------------------------------------------------ @@ -223,12 +223,12 @@ def qnode(params): # We are using :math:`\text{HeH}^+` as a simple example and load it from the `PennyLane quantum datasets `_ website. # We are going to use the tapered Hamiltonian, which makes use of symmetries to reduce the number of qubits, see :doc:`demos/tutorial_qubit_tapering` for details. -data = qml.data.load("qchem", molname="HeH+", basis="STO-3G", bondlength=1.5)[0] +data = qp.data.load("qchem", molname="HeH+", basis="STO-3G", bondlength=1.5)[0] H_obj = data.tapered_hamiltonian H_obj_coeffs, H_obj_ops = H_obj.terms() # casting the Hamiltonian coefficients to a jax Array -H_obj = qml.Hamiltonian(jnp.array(H_obj_coeffs), H_obj_ops) +H_obj = qp.Hamiltonian(jnp.array(H_obj_coeffs), H_obj_ops) E_exact = data.fci_energy n_wires = len(H_obj.wires) @@ -244,18 +244,18 @@ def qnode(params): def a(wires): - return 0.5 * qml.PauliX(wires) + 0.5j * qml.PauliY(wires) + return 0.5 * qp.PauliX(wires) + 0.5j * qp.PauliY(wires) def ad(wires): - return 0.5 * qml.PauliX(wires) - 0.5j * qml.PauliY(wires) + return 0.5 * qp.PauliX(wires) - 0.5j * qp.PauliY(wires) omega = 2 * jnp.pi * jnp.array([4.8080, 4.8333]) g = 2 * jnp.pi * jnp.array([0.01831, 0.02131]) -H_D = qml.dot(omega, [ad(i) @ a(i) for i in range(n_wires)]) -H_D += qml.dot( +H_D = qp.dot(omega, [ad(i) @ a(i) for i in range(n_wires)]) +H_D += qp.dot( g, [ad(i) @ a((i + 1) % n_wires) + ad((i + 1) % n_wires) @ a(i) for i in range(n_wires)], ) @@ -288,7 +288,7 @@ def normalize(x): def drive_field(T, omega, sign=1.0): def wrapped(p, t): # The first len(p)-1 values of the trainable params p characterize the pwc function - amp = qml.pulse.pwc(T)(p[:-1], t) + amp = qp.pulse.pwc(T)(p[:-1], t) # The amplitude is normalized to maximally reach +/-20MHz (0.02GHz) amp = 0.02 * normalize(amp) @@ -308,7 +308,7 @@ def wrapped(p, t): ops = [a(i) for i in range(n_wires)] ops += [ad(i) for i in range(n_wires)] -H_C = qml.dot(fs, ops) +H_C = qp.dot(fs, ops) ############################################################################## # Overall, we end up with the time-dependent parametrized Hamiltonian :math:`H(p, t) = H_D + H_C(p, t)` @@ -323,15 +323,15 @@ def wrapped(p, t): # We need to wrap the ``qnode`` in a function so that we can convert the expectation value to a real number. # This will enable use to make use of gradient descent methods that require real-valued loss functions. -dev = qml.device("default.qubit", wires=range(n_wires)) +dev = qp.device("default.qubit", wires=range(n_wires)) def qnode(theta, t=duration): - @qml.qnode(dev) + @qp.qnode(dev) def _qnode_inner(theta, t=duration): - qml.BasisState(jnp.array(data.tapered_hf_state), wires=H_obj.wires) - qml.evolve(H_pulse)(params=(*theta, *theta), t=t) - return qml.expval(H_obj) + qp.BasisState(jnp.array(data.tapered_hf_state), wires=H_obj.wires) + qp.evolve(H_pulse)(params=(*theta, *theta), t=t) + return qp.expval(H_obj) expectation_value = _qnode_inner(theta, t) # Execute the qnode return jnp.real(expectation_value) # Typecast to real number diff --git a/demonstrations_v2/tutorial_pulse_programming101/metadata.json b/demonstrations_v2/tutorial_pulse_programming101/metadata.json index 065394b0d8..b421e10003 100644 --- a/demonstrations_v2/tutorial_pulse_programming101/metadata.json +++ b/demonstrations_v2/tutorial_pulse_programming101/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-03-08T00:00:00+00:00", - "dateOfLastModification": "2025-12-10T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Hardware", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_qaoa_intro/demo.py b/demonstrations_v2/tutorial_qaoa_intro/demo.py index 8c86f00dae..508580e713 100644 --- a/demonstrations_v2/tutorial_qaoa_intro/demo.py +++ b/demonstrations_v2/tutorial_qaoa_intro/demo.py @@ -79,9 +79,9 @@ # In PennyLane, this is implemented using the :func:`~.pennylane.ApproxTimeEvolution` # template. For example, let's say we have the following Hamiltonian: -import pennylane as qml +import pennylane as qp -H = qml.Hamiltonian([1, 1, 0.5], [qml.PauliX(0), qml.PauliZ(1), qml.PauliX(0) @ qml.PauliX(1)]) +H = qp.Hamiltonian([1, 1, 0.5], [qp.PauliX(0), qp.PauliZ(1), qp.PauliX(0) @ qp.PauliX(1)]) print(H) @@ -90,19 +90,19 @@ # We can implement the approximate time-evolution operator corresponding to this # Hamiltonian: -dev = qml.device("default.qubit", wires=2) +dev = qp.device("default.qubit", wires=2) t = 1 n = 2 -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): - qml.ApproxTimeEvolution(H, t, n) - return [qml.expval(qml.PauliZ(i)) for i in range(2)] + qp.ApproxTimeEvolution(H, t, n) + return [qp.expval(qp.PauliZ(i)) for i in range(2)] -print(qml.draw(circuit, level="device")()) +print(qp.draw(circuit, level="device")()) ###################################################################### # Layering circuits @@ -139,18 +139,18 @@ def circuit(): def circ(theta): - qml.RX(theta, wires=0) - qml.Hadamard(wires=1) - qml.CNOT(wires=[0, 1]) + qp.RX(theta, wires=0) + qp.Hadamard(wires=1) + qp.CNOT(wires=[0, 1]) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(param): circ(param) - return [qml.expval(qml.PauliZ(i)) for i in range(2)] + return [qp.expval(qp.PauliZ(i)) for i in range(2)] -print(qml.draw(circuit)(0.5)) +print(qp.draw(circuit)(0.5)) ###################################################################### # @@ -158,13 +158,13 @@ def circuit(param): # -@qml.qnode(dev) +@qp.qnode(dev) def circuit(params, **kwargs): - qml.layer(circ, 3, params) - return [qml.expval(qml.PauliZ(i)) for i in range(2)] + qp.layer(circ, 3, params) + return [qp.expval(qp.PauliZ(i)) for i in range(2)] -print(qml.draw(circuit)([0.3, 0.4, 0.5])) +print(qp.draw(circuit)([0.3, 0.4, 0.5])) ###################################################################### # @@ -308,8 +308,8 @@ def qaoa_layer(gamma, alpha): def circuit(params, **kwargs): for w in wires: - qml.Hadamard(wires=w) - qml.layer(qaoa_layer, depth, params[0], params[1]) + qp.Hadamard(wires=w) + qp.layer(qaoa_layer, depth, params[0], params[1]) ###################################################################### @@ -325,13 +325,13 @@ def circuit(params, **kwargs): # PennyLane-Qulacs plugin to run the circuit on the Qulacs simulator: # -dev = qml.device("qulacs.simulator", wires=wires) +dev = qp.device("qulacs.simulator", wires=wires) -@qml.qnode(dev) +@qp.qnode(dev) def cost_function(params): circuit(params) - return qml.expval(cost_h) + return qp.expval(cost_h) ###################################################################### @@ -341,7 +341,7 @@ def cost_function(params): # parameters: -optimizer = qml.GradientDescentOptimizer() +optimizer = qp.GradientDescentOptimizer() steps = 70 params = np.array([[0.5, 0.5], [0.5, 0.5]], requires_grad=True) @@ -375,10 +375,10 @@ def cost_function(params): # -@qml.qnode(dev) +@qp.qnode(dev) def probability_circuit(gamma, alpha): circuit([gamma, alpha]) - return qml.probs(wires=wires) + return qp.probs(wires=wires) probs = probability_circuit(params[0], params[1]) @@ -451,14 +451,14 @@ def qaoa_layer(gamma, alpha): def circuit(params, **kwargs): for w in wires: - qml.Hadamard(wires=w) - qml.layer(qaoa_layer, depth, params[0], params[1]) + qp.Hadamard(wires=w) + qp.layer(qaoa_layer, depth, params[0], params[1]) -@qml.qnode(dev) +@qp.qnode(dev) def cost_function(params): circuit(params) - return qml.expval(new_cost_h) + return qp.expval(new_cost_h) params = np.array([[0.5, 0.5], [0.5, 0.5]], requires_grad=True) @@ -476,10 +476,10 @@ def cost_function(params): # -@qml.qnode(dev) +@qp.qnode(dev) def probability_circuit(gamma, alpha): circuit([gamma, alpha]) - return qml.probs(wires=wires) + return qp.probs(wires=wires) probs = probability_circuit(params[0], params[1]) diff --git a/demonstrations_v2/tutorial_qaoa_intro/metadata.json b/demonstrations_v2/tutorial_qaoa_intro/metadata.json index dac985e37e..e1b5db2eb5 100644 --- a/demonstrations_v2/tutorial_qaoa_intro/metadata.json +++ b/demonstrations_v2/tutorial_qaoa_intro/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-11-18T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_qaoa_maxcut/demo.py b/demonstrations_v2/tutorial_qaoa_maxcut/demo.py index c9bcc2b671..ff757b58ae 100644 --- a/demonstrations_v2/tutorial_qaoa_maxcut/demo.py +++ b/demonstrations_v2/tutorial_qaoa_maxcut/demo.py @@ -130,7 +130,7 @@ version of NumPy. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np np.random.seed(42) @@ -153,15 +153,15 @@ # unitary operator U_B with parameter beta def U_B(beta): for wire in range(n_wires): - qml.RX(2 * beta, wires=wire) + qp.RX(2 * beta, wires=wire) # unitary operator U_C with parameter gamma def U_C(gamma): for edge in graph: - qml.CNOT(wires=edge) - qml.RZ(gamma, wires=edge[1]) - qml.CNOT(wires=edge) + qp.CNOT(wires=edge) + qp.RZ(gamma, wires=edge[1]) + qp.CNOT(wires=edge) # Could also do # IsingZZ(gamma, wires=edge) @@ -180,7 +180,7 @@ def bitstring_to_int(bit_string_sample): # ~~~~~~~ # Next, we create a quantum device with 4 qubits. -dev = qml.device("lightning.qubit", wires=n_wires) +dev = qp.device("lightning.qubit", wires=n_wires) ############################################################################## # We also require a quantum node which will apply the operators according to the angle parameters, @@ -194,12 +194,12 @@ def bitstring_to_int(bit_string_sample): # by setting ``return_samples=True``. -@qml.set_shots(20) -@qml.qnode(dev) +@qp.set_shots(20) +@qp.qnode(dev) def circuit(gammas, betas, return_samples=False): # apply Hadamards to get the n qubit |+> state for wire in range(n_wires): - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) # p instances of unitary operators for gamma, beta in zip(gammas, betas): U_C(gamma) @@ -207,10 +207,10 @@ def circuit(gammas, betas, return_samples=False): if return_samples: # sample bitstrings to obtain cuts - return qml.sample() + return qp.sample() # during the optimization phase we are evaluating the objective using expval - C = qml.sum(*(qml.Z(w1) @ qml.Z(w2) for w1, w2 in graph)) - return qml.expval(C) + C = qp.sum(*(qp.Z(w1) @ qp.Z(w2) for w1, w2 in graph)) + return qp.expval(C) def objective(params): @@ -237,7 +237,7 @@ def qaoa_maxcut(n_layers=1): init_params = 0.01 * np.random.rand(2, n_layers, requires_grad=True) # initialize optimizer: Adagrad works well empirically - opt = qml.AdagradOptimizer(stepsize=0.5) + opt = qp.AdagradOptimizer(stepsize=0.5) # optimize parameters in objective params = init_params.copy() @@ -248,7 +248,7 @@ def qaoa_maxcut(n_layers=1): print(f"Objective after step {i+1:3d}: {-objective(params): .7f}") # sample 100 bitstrings by setting return_samples=True and the QNode shot count to 100 - bitstrings = qml.set_shots(circuit, shots=100)(*params, return_samples=True) + bitstrings = qp.set_shots(circuit, shots=100)(*params, return_samples=True) # convert the samples bitstrings to integers sampled_ints = [bitstring_to_int(string) for string in bitstrings] diff --git a/demonstrations_v2/tutorial_qaoa_maxcut/metadata.json b/demonstrations_v2/tutorial_qaoa_maxcut/metadata.json index f749ff5587..6146fc0749 100644 --- a/demonstrations_v2/tutorial_qaoa_maxcut/metadata.json +++ b/demonstrations_v2/tutorial_qaoa_maxcut/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-11T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_qcbm/demo.py b/demonstrations_v2/tutorial_qcbm/demo.py index 375c2dc519..9a497502d3 100644 --- a/demonstrations_v2/tutorial_qcbm/demo.py +++ b/demonstrations_v2/tutorial_qcbm/demo.py @@ -233,23 +233,23 @@ def get_bars_and_stripes(n): # will act as a generative model, thus, realize a Born machine. # -import pennylane as qml +import pennylane as qp np.random.seed(42) n_qubits = size -dev = qml.device("default.qubit", wires=n_qubits) +dev = qp.device("default.qubit", wires=n_qubits) n_layers = 6 -wshape = qml.StronglyEntanglingLayers.shape(n_layers=n_layers, n_wires=n_qubits) +wshape = qp.StronglyEntanglingLayers.shape(n_layers=n_layers, n_wires=n_qubits) weights = np.random.random(size=wshape) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(weights): - qml.StronglyEntanglingLayers(weights=weights, ranges=[1] * n_layers, wires=range(n_qubits)) - return qml.probs() + qp.StronglyEntanglingLayers(weights=weights, ranges=[1] * n_layers, wires=range(n_qubits)) + return qp.probs() jit_circuit = jax.jit(circuit) @@ -384,13 +384,13 @@ def update_step(params, opt_state): def circuit(weights): - qml.StronglyEntanglingLayers(weights=weights, ranges=[1] * n_layers, wires=range(n_qubits)) - return qml.sample() + qp.StronglyEntanglingLayers(weights=weights, ranges=[1] * n_layers, wires=range(n_qubits)) + return qp.sample() for N in [2000, 20000]: - dev = qml.device("default.qubit", wires=n_qubits) - circ = qml.set_shots(qml.QNode(circuit, device=dev), shots = N) + dev = qp.device("default.qubit", wires=n_qubits) + circ = qp.set_shots(qp.QNode(circuit, device=dev), shots = N) preds = circ(weights) mask = np.any(np.all(preds[:, None] == data, axis=2), axis=1) # Check for row-wise equality chi = np.sum(mask) / N @@ -462,25 +462,25 @@ def mixture_gaussian_pdf(x, mus, sigmas): # we will create an ansatz and measure probabilities. # -dev = qml.device("default.qubit", wires=n_qubits) +dev = qp.device("default.qubit", wires=n_qubits) n_layers = 4 -wshape = qml.StronglyEntanglingLayers.shape(n_layers=n_layers, n_wires=n_qubits) +wshape = qp.StronglyEntanglingLayers.shape(n_layers=n_layers, n_wires=n_qubits) weights = np.random.random(size=wshape) -@qml.set_shots(N) -@qml.qnode(dev) +@qp.set_shots(N) +@qp.qnode(dev) def circuit(weights): - qml.StronglyEntanglingLayers( + qp.StronglyEntanglingLayers( weights=weights, ranges=[1] * n_layers, wires=range(n_qubits) ) - return qml.probs() + return qp.probs() jit_circuit = jax.jit(circuit) -qml.draw_mpl(circuit, level="device")(weights) +qp.draw_mpl(circuit, level="device")(weights) plt.show() ###################################################################### diff --git a/demonstrations_v2/tutorial_qcbm/metadata.json b/demonstrations_v2/tutorial_qcbm/metadata.json index bc9fd2a217..8dede33249 100644 --- a/demonstrations_v2/tutorial_qcbm/metadata.json +++ b/demonstrations_v2/tutorial_qcbm/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-05-22T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_qchem_external/demo.py b/demonstrations_v2/tutorial_qchem_external/demo.py index 0e37c0aef2..79bab90bbf 100644 --- a/demonstrations_v2/tutorial_qchem_external/demo.py +++ b/demonstrations_v2/tutorial_qchem_external/demo.py @@ -46,16 +46,16 @@ backend as: """ -import pennylane as qml +import pennylane as qp import numpy as np symbols = ["H", "O", "H"] geometry = np.array([[-0.0399, -0.0038, 0.0000], [ 1.5780, 0.8540, 0.0000], [ 2.7909, -0.5159, 0.0000]]) -molecule = qml.qchem.Molecule(symbols, geometry) +molecule = qp.qchem.Molecule(symbols, geometry) -H, qubits = qml.qchem.molecular_hamiltonian(molecule, method="pyscf") +H, qubits = qp.qchem.molecular_hamiltonian(molecule, method="pyscf") print(H) ############################################################################## @@ -72,7 +72,7 @@ from openfermion.ops import QubitOperator H = 0.1 * QubitOperator('X0 X1') + 0.2 * QubitOperator('Z0') -H = qml.qchem.import_operator(H) +H = qp.qchem.import_operator(H) print(f'Type: \n {type(H)} \n') print(f'Hamiltonian: \n {H}') @@ -135,13 +135,13 @@ # for creating and manipulating # :doc:`fermionic operators `: -H_fermionic = qml.qchem.fermionic_observable(core_constant, one_mo, two_mo) +H_fermionic = qp.qchem.fermionic_observable(core_constant, one_mo, two_mo) ############################################################################## # The Hamiltonian can be mapped to the qubit basis with the :func:`~.pennylane.jordan_wigner` # function: -H = qml.jordan_wigner(H_fermionic) +H = qp.jordan_wigner(H_fermionic) ############################################################################## # Importing initial states @@ -173,7 +173,7 @@ # Then, we use the :func:`~.pennylane.qchem.import_state` function to obtain the # state vector. -state = qml.qchem.import_state(mycc) +state = qp.qchem.import_state(mycc) print(state) ############################################################################## @@ -190,14 +190,14 @@ from openfermion import FermionOperator openfermion_op = 0.5 * FermionOperator('0^ 2') + FermionOperator('0 2^') -pennylane_op = qml.from_openfermion(openfermion_op) +pennylane_op = qp.from_openfermion(openfermion_op) print(pennylane_op) ############################################################################## # The resulting operator can be used in PennyLane like any other fermionic object. We now take this # PennyLane fermionic operator and convert it back to an OpenFermion operator. -openfermion_op = qml.to_openfermion(pennylane_op) +openfermion_op = qp.to_openfermion(pennylane_op) print(openfermion_op) ############################################################################## diff --git a/demonstrations_v2/tutorial_qchem_external/metadata.json b/demonstrations_v2/tutorial_qchem_external/metadata.json index fced5a817b..1d83ddf04f 100644 --- a/demonstrations_v2/tutorial_qchem_external/metadata.json +++ b/demonstrations_v2/tutorial_qchem_external/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-01-03T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry", "Devices and Performance" diff --git a/demonstrations_v2/tutorial_qft/demo.py b/demonstrations_v2/tutorial_qft/demo.py index 550a5fd14c..a8c5bb5806 100644 --- a/demonstrations_v2/tutorial_qft/demo.py +++ b/demonstrations_v2/tutorial_qft/demo.py @@ -33,7 +33,7 @@ """ from scipy.linalg import dft -import pennylane as qml +import pennylane as qp import numpy as np n = 2 @@ -41,7 +41,7 @@ print("DFT matrix for n = 2:\n") print(np.round(1 / np.sqrt(2 ** n) * dft(2 ** n), 2)) -qft_inverse = qml.adjoint(qml.QFT([0,1])) +qft_inverse = qp.adjoint(qp.QFT([0,1])) print("\n inverse QFT matrix for n = 2:\n") print(np.round(qft_inverse.matrix(), 2)) @@ -90,19 +90,19 @@ # In PennyLane, we rearrange the qubits in the opposite ordering; that is why we # apply SWAP gates at the end. Let's see how the decomposition looks like using the drawer: -import pennylane as qml +import pennylane as qp from functools import partial import matplotlib.pyplot as plt plt.style.use('pennylane.drawer.plot') # This line is to expand the circuit to see the operators -@partial(qml.transforms.decompose, max_expansion=1) +@partial(qp.transforms.decompose, max_expansion=1) def circuit(): - qml.QFT(wires=range(4)) + qp.QFT(wires=range(4)) -qml.draw_mpl(circuit, decimals = 2, style = "pennylane")() +qp.draw_mpl(circuit, decimals = 2, style = "pennylane")() plt.show() ############################################# @@ -124,17 +124,17 @@ def circuit(): def prep(): """quntum function that prepares the state.""" - qml.PauliX(wires=0) + qp.PauliX(wires=0) for wire in range(1, 6): - qml.Hadamard(wires=wire) - qml.ControlledSequence(qml.PhaseShift(-2 * np.pi / 10, wires=0), control=range(1, 6)) - qml.PauliX(wires=0) + qp.Hadamard(wires=wire) + qp.ControlledSequence(qp.PhaseShift(-2 * np.pi / 10, wires=0), control=range(1, 6)) + qp.PauliX(wires=0) -dev = qml.device("default.qubit") -@qml.qnode(dev) +dev = qp.device("default.qubit") +@qp.qnode(dev) def circuit(): prep() - return qml.state() + return qp.state() state = circuit().real[:32] @@ -149,12 +149,12 @@ def circuit(): # which is able to transform the state into the frequency domain. This is shown in the code below: # -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): prep() - qml.QFT(wires=range(1, 6)) + qp.QFT(wires=range(1, 6)) - return qml.probs(wires=range(1, 6)) + return qp.probs(wires=range(1, 6)) state = circuit()[:32] diff --git a/demonstrations_v2/tutorial_qft/metadata.json b/demonstrations_v2/tutorial_qft/metadata.json index e7d0474270..981be66533 100644 --- a/demonstrations_v2/tutorial_qft/metadata.json +++ b/demonstrations_v2/tutorial_qft/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-04-16T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_qft_and_groups/demo.py b/demonstrations_v2/tutorial_qft_and_groups/demo.py index 939a835451..8a47e89cac 100644 --- a/demonstrations_v2/tutorial_qft_and_groups/demo.py +++ b/demonstrations_v2/tutorial_qft_and_groups/demo.py @@ -227,7 +227,7 @@ def g_hat(k): # This works because the Fourier transform, if normalised appropriately, is a unitary transform! # # Let us verify this by comparing the DFT of a function, as coded up above, with the result of a quantum circuit -# that implements ``qml.QFT``. However, now we need a function that, written as a vector, can be interpreted +# that implements ``qp.QFT``. However, now we need a function that, written as a vector, can be interpreted # as a normalised quantum state. We therefore apply a slight modification to our function ``f`` from before. # @@ -249,16 +249,16 @@ def h_hat(k): # the output state vector from the simulator. # -import pennylane as qml +import pennylane as qp -dev = qml.device("default.qubit", wires=4, shots=None) +dev = qp.device("default.qubit", wires=4, shots=None) -@qml.qnode(dev) +@qp.qnode(dev) def qft(state): """Prepare a state \sum_x f(x) |x> and apply the discrete Fourier transform.""" - qml.StatePrep(state, wires=range(4)) - qml.QFT(wires=range(4)) - return qml.state() + qp.StatePrep(state, wires=range(4)) + qp.QFT(wires=range(4)) + return qp.state() ##################################################################### @@ -272,7 +272,7 @@ def qft(state): print("QFT and DFT coincide:", np.allclose(h_hat_state, h_hat_vec)) ##################################################################### -# But of course, ``qml.QFT`` only implements the Fourier transform with respect to the group :math:`Z_N`, which +# But of course, ``qp.QFT`` only implements the Fourier transform with respect to the group :math:`Z_N`, which # interprets computational basis states as integers. # As mentioned before, we can alternatively interpret bit strings as a collection of binary variables, which changes the group # to :math:`Z_2^n`. Both map into a Fourier basis, but with respect a different @@ -280,13 +280,13 @@ def qft(state): # -@qml.qnode(dev) +@qp.qnode(dev) def qft2(state): """Prepare a state \sum_x f(x) |x> and apply the Fourier transform over Z_2^4.""" - qml.StatePrep(state, wires=range(4)) + qp.StatePrep(state, wires=range(4)) for i in range(4): - qml.Hadamard(wires=i) - return qml.state() + qp.Hadamard(wires=i) + return qp.state() h_hat_state2 = qft2(h_vec) print("QFTs over different groups coincide:", np.allclose(h_hat_state, h_hat_state2)) diff --git a/demonstrations_v2/tutorial_qft_and_groups/metadata.json b/demonstrations_v2/tutorial_qft_and_groups/metadata.json index b018708fb9..1cf6d91b16 100644 --- a/demonstrations_v2/tutorial_qft_and_groups/metadata.json +++ b/demonstrations_v2/tutorial_qft_and_groups/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-09-18T10:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms" ], diff --git a/demonstrations_v2/tutorial_qft_arithmetics/demo.py b/demonstrations_v2/tutorial_qft_arithmetics/demo.py index 4bf57edc8e..2d9110a3de 100644 --- a/demonstrations_v2/tutorial_qft_arithmetics/demo.py +++ b/demonstrations_v2/tutorial_qft_arithmetics/demo.py @@ -94,25 +94,25 @@ representation that helps better visualize and interpret quantum gates such as rotations. We can use -the :class:`qml.BasisEmbedding ` +the :class:`qp.BasisEmbedding ` template to obtain the binary representation in a simple way. Let's see how we would code the number :math:`6.` """ -import pennylane as qml +import pennylane as qp import matplotlib.pyplot as plt -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) -@qml.compile -@qml.qnode(dev) +@qp.compile +@qp.qnode(dev) def basis_embedding_circuit(m): - qml.BasisEmbedding(m, wires=range(3)) - return qml.state() + qp.BasisEmbedding(m, wires=range(3)) + return qp.state() m = 6 # number to be encoded -qml.draw_mpl(basis_embedding_circuit, show_all_wires=True)(m) +qp.draw_mpl(basis_embedding_circuit, show_all_wires=True)(m) plt.show() ###################################################################### @@ -168,28 +168,28 @@ def basis_embedding_circuit(m): # Let's see how this process would look in PennyLane. # -import pennylane as qml +import pennylane as qp import numpy as np n_wires = 4 -dev = qml.device("default.qubit", wires=n_wires) +dev = qp.device("default.qubit", wires=n_wires) def add_k_fourier(k, wires): for j in range(len(wires)): - qml.RZ(k * np.pi / (2**j), wires=wires[j]) + qp.RZ(k * np.pi / (2**j), wires=wires[j]) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def sum(m, k): - qml.BasisEmbedding(m, wires=range(n_wires)) # m encoding + qp.BasisEmbedding(m, wires=range(n_wires)) # m encoding - qml.QFT(wires=range(n_wires)) # step 1 + qp.QFT(wires=range(n_wires)) # step 1 add_k_fourier(k, range(n_wires)) # step 2 - qml.adjoint(qml.QFT)(wires=range(n_wires)) # step 3 + qp.adjoint(qp.QFT)(wires=range(n_wires)) # step 3 - return qml.sample() + return qp.sample() print(f"The ket representation of the sum of 3 and 4 is {sum(3,4)}") @@ -233,41 +233,41 @@ def sum(m, k): wires_k = [3, 4, 5] # qubits needed to encode k wires_solution = [6, 7, 8, 9] # qubits needed to encode the solution -dev = qml.device("default.qubit", wires=wires_m + wires_k + wires_solution) +dev = qp.device("default.qubit", wires=wires_m + wires_k + wires_solution) n_wires = len(dev.wires) # total number of qubits used def addition(wires_m, wires_k, wires_solution): # prepare solution qubits to counting - qml.QFT(wires=wires_solution) + qp.QFT(wires=wires_solution) # add m to the counter for i in range(len(wires_m)): - qml.ctrl(add_k_fourier, control=wires_m[i])(2 **(len(wires_m) - i - 1), wires_solution) + qp.ctrl(add_k_fourier, control=wires_m[i])(2 **(len(wires_m) - i - 1), wires_solution) # add k to the counter for i in range(len(wires_k)): - qml.ctrl(add_k_fourier, control=wires_k[i])(2 **(len(wires_k) - i - 1), wires_solution) + qp.ctrl(add_k_fourier, control=wires_k[i])(2 **(len(wires_k) - i - 1), wires_solution) # return to computational basis - qml.adjoint(qml.QFT)(wires=wires_solution) + qp.adjoint(qp.QFT)(wires=wires_solution) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def sum2(m, k, wires_m, wires_k, wires_solution): # m and k codification - qml.BasisEmbedding(m, wires=wires_m) - qml.BasisEmbedding(k, wires=wires_k) + qp.BasisEmbedding(m, wires=wires_m) + qp.BasisEmbedding(k, wires=wires_k) # apply the addition circuit addition(wires_m, wires_k, wires_solution) - return qml.sample(wires=wires_solution) + return qp.sample(wires=wires_solution) print(f"The ket representation of the sum of 7 and 3 is " f"{sum2(7, 3, wires_m, wires_k, wires_solution)}") -qml.draw_mpl(sum2, show_all_wires=True)(7, 3, wires_m, wires_k, wires_solution) +qp.draw_mpl(sum2, show_all_wires=True)(7, 3, wires_m, wires_k, wires_solution) plt.show() ###################################################################### @@ -300,39 +300,39 @@ def sum2(m, k, wires_m, wires_k, wires_solution): wires_k = [3, 4, 5] # qubits needed to encode k wires_solution = [6, 7, 8, 9, 10] # qubits needed to encode the solution -dev = qml.device("default.qubit", wires=wires_m + wires_k + wires_solution) +dev = qp.device("default.qubit", wires=wires_m + wires_k + wires_solution) n_wires = len(dev.wires) def multiplication(wires_m, wires_k, wires_solution): # prepare sol-qubits to counting - qml.QFT(wires=wires_solution) + qp.QFT(wires=wires_solution) # add m to the counter for i in range(len(wires_k)): for j in range(len(wires_m)): coeff = 2 ** (len(wires_m) + len(wires_k) - i - j - 2) - qml.ctrl(add_k_fourier, control=[wires_k[i], wires_m[j]])(coeff, wires_solution) + qp.ctrl(add_k_fourier, control=[wires_k[i], wires_m[j]])(coeff, wires_solution) # return to computational basis - qml.adjoint(qml.QFT)(wires=wires_solution) + qp.adjoint(qp.QFT)(wires=wires_solution) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def mul(m, k): # m and k codification - qml.BasisEmbedding(m, wires=wires_m) - qml.BasisEmbedding(k, wires=wires_k) + qp.BasisEmbedding(m, wires=wires_m) + qp.BasisEmbedding(k, wires=wires_k) # Apply multiplication multiplication(wires_m, wires_k, wires_solution) - return qml.sample(wires=wires_solution) + return qp.sample(wires=wires_solution) print(f"The ket representation of the multiplication of 3 and 7 is {mul(3,7)}") -qml.draw_mpl(mul, show_all_wires=True)(3, 7) +qp.draw_mpl(mul, show_all_wires=True)(3, 7) plt.show() @@ -375,32 +375,32 @@ def mul(m, k): wires_k = [3, 4, 5] # qubits needed to encode k wires_solution = [6, 7, 8, 9, 10] # qubits needed to encode the solution -dev = qml.device("default.qubit", wires=wires_m + wires_k + wires_solution) +dev = qp.device("default.qubit", wires=wires_m + wires_k + wires_solution) n_wires = len(dev.wires) -@qml.qnode(dev) +@qp.qnode(dev) def factorization(n, wires_m, wires_k, wires_solution): # Superposition of the input for wire in wires_m: - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) for wire in wires_k: - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) # Apply the multiplication multiplication(wires_m, wires_k, wires_solution) # Change sign of n - qml.FlipSign(n, wires=wires_solution) + qp.FlipSign(n, wires=wires_solution) # Uncompute multiplication - qml.adjoint(multiplication)(wires_m, wires_k, wires_solution) + qp.adjoint(multiplication)(wires_m, wires_k, wires_solution) # Apply Grover operator - qml.GroverOperator(wires=wires_m + wires_k) + qp.GroverOperator(wires=wires_m + wires_k) - return qml.probs(wires=wires_m) + return qp.probs(wires=wires_m) plt.bar(range(2 ** len(wires_m)), factorization(n, wires_m, wires_k, wires_solution)) diff --git a/demonstrations_v2/tutorial_qft_arithmetics/metadata.json b/demonstrations_v2/tutorial_qft_arithmetics/metadata.json index 026ea5158c..85db5b038d 100644 --- a/demonstrations_v2/tutorial_qft_arithmetics/metadata.json +++ b/demonstrations_v2/tutorial_qft_arithmetics/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-11-07T00:00:00+00:00", - "dateOfLastModification": "2025-11-05T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Getting Started", "Algorithms", diff --git a/demonstrations_v2/tutorial_qgrnn/demo.py b/demonstrations_v2/tutorial_qgrnn/demo.py index db0de46c7e..2275af712c 100644 --- a/demonstrations_v2/tutorial_qgrnn/demo.py +++ b/demonstrations_v2/tutorial_qgrnn/demo.py @@ -192,7 +192,7 @@ # -import pennylane as qml +import pennylane as qp from matplotlib import pyplot as plt from pennylane import numpy as np import scipy @@ -275,7 +275,7 @@ def create_hamiltonian_matrix(n_qubits, graph, weights, bias): interaction_term = 1 for qubit in range(0, n_qubits): if qubit in edge: - interaction_term = np.kron(interaction_term, qml.matrix(qml.PauliZ(0))) + interaction_term = np.kron(interaction_term, qp.matrix(qp.PauliZ(0))) else: interaction_term = np.kron(interaction_term, np.identity(2)) full_matrix += weights[i] * interaction_term @@ -285,8 +285,8 @@ def create_hamiltonian_matrix(n_qubits, graph, weights, bias): z_term = x_term = 1 for j in range(0, n_qubits): if j == i: - z_term = np.kron(z_term, qml.matrix(qml.PauliZ(0))) - x_term = np.kron(x_term, qml.matrix(qml.PauliX(0))) + z_term = np.kron(z_term, qp.matrix(qp.PauliZ(0))) + x_term = np.kron(x_term, qp.matrix(qp.PauliX(0))) else: z_term = np.kron(z_term, np.identity(2)) x_term = np.kron(x_term, np.identity(2)) @@ -374,7 +374,7 @@ def create_hamiltonian_matrix(n_qubits, graph, weights, bias): def state_evolve(hamiltonian, qubits, time): U = scipy.linalg.expm(-1j * hamiltonian * time) - qml.QubitUnitary(U, wires=qubits) + qp.QubitUnitary(U, wires=qubits) ###################################################################### @@ -404,15 +404,15 @@ def qgrnn_layer(weights, bias, qubits, graph, trotter_step): # Applies a layer of RZZ gates (based on a graph) for i, edge in enumerate(graph.edges): - qml.MultiRZ(2 * weights[i] * trotter_step, wires=(edge[0], edge[1])) + qp.MultiRZ(2 * weights[i] * trotter_step, wires=(edge[0], edge[1])) # Applies a layer of RZ gates for i, qubit in enumerate(qubits): - qml.RZ(2 * bias[i] * trotter_step, wires=qubit) + qp.RZ(2 * bias[i] * trotter_step, wires=qubit) # Applies a layer of RX gates for qubit in qubits: - qml.RX(2 * trotter_step, wires=qubit) + qp.RX(2 * trotter_step, wires=qubit) ###################################################################### @@ -431,10 +431,10 @@ def qgrnn_layer(weights, bias, qubits, graph, trotter_step): def swap_test(control, register1, register2): - qml.Hadamard(wires=control) + qp.Hadamard(wires=control) for reg1_qubit, reg2_qubit in zip(register1, register2): - qml.CSWAP(wires=(control, reg1_qubit, reg2_qubit)) - qml.Hadamard(wires=control) + qp.CSWAP(wires=(control, reg1_qubit, reg2_qubit)) + qp.Hadamard(wires=control) ###################################################################### @@ -482,7 +482,7 @@ def swap_test(control, register1, register2): def qgrnn(weights, bias, time=None): # Prepares the low energy state in the two registers - qml.StatePrep(np.kron(low_energy_state, low_energy_state), wires=reg1 + reg2) + qp.StatePrep(np.kron(low_energy_state, low_energy_state), wires=reg1 + reg2) # Evolves the first qubit register with the time-evolution circuit to # prepare a piece of quantum data @@ -497,7 +497,7 @@ def qgrnn(weights, bias, time=None): swap_test(control, reg1, reg2) # Returns the results of the SWAP test - return qml.expval(qml.PauliZ(control)) + return qp.expval(qp.PauliZ(control)) ###################################################################### @@ -551,14 +551,14 @@ def cost_function(weight_params, bias_params): # # Defines the new device -qgrnn_dev = qml.device("default.qubit", wires=2 * qubit_number + 1) +qgrnn_dev = qp.device("default.qubit", wires=2 * qubit_number + 1) # Defines the new QNode -qgrnn_qnode = qml.QNode(qgrnn, qgrnn_dev) +qgrnn_qnode = qp.QNode(qgrnn, qgrnn_dev) steps = 300 -optimizer = qml.AdamOptimizer(stepsize=0.5) +optimizer = qp.AdamOptimizer(stepsize=0.5) weights = rng.random(size=len(new_ising_graph.edges), requires_grad=True) - 0.5 bias = rng.random(size=qubit_number, requires_grad=True) - 0.5 diff --git a/demonstrations_v2/tutorial_qgrnn/metadata.json b/demonstrations_v2/tutorial_qgrnn/metadata.json index 1d6f12a1f3..7677903d6a 100644 --- a/demonstrations_v2/tutorial_qgrnn/metadata.json +++ b/demonstrations_v2/tutorial_qgrnn/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-07-27T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/demo.py b/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/demo.py index fbb1de821e..3f090e5e11 100644 --- a/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/demo.py +++ b/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/demo.py @@ -65,16 +65,16 @@ import matplotlib.pyplot as plt import numpy as np -import pennylane as qml +import pennylane as qp def equal_superposition(wires): for wire in wires: - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) def oracle(wires, omega): - qml.FlipSign(omega, wires=wires) + qp.FlipSign(omega, wires=wires) def num_grover_iterations(N, M): @@ -95,9 +95,9 @@ def grover_circuit(num_qubits): for _ in range(num_grover_iterations(N, M)): for omg in omega: oracle(wires, omg) - qml.templates.GroverOperator(wires) + qp.templates.GroverOperator(wires) - return qml.probs(wires=wires) + return qp.probs(wires=wires) ###################################################################### @@ -108,10 +108,10 @@ def grover_circuit(num_qubits): NUM_QUBITS = 12 -dev = qml.device("default.qubit", wires=NUM_QUBITS) +dev = qp.device("default.qubit", wires=NUM_QUBITS) -@qml.qnode(dev) +@qp.qnode(dev) def circuit_default_qubit(): return grover_circuit(NUM_QUBITS) @@ -157,10 +157,10 @@ def print_most_probable_states_descending(probs, N): # performant state simulators written in C++. See the :doc:`Catalyst documentation # ` for the full list of devices supported by Catalyst. -dev = qml.device("lightning.qubit", wires=NUM_QUBITS) +dev = qp.device("lightning.qubit", wires=NUM_QUBITS) -@qml.qnode(dev) +@qp.qnode(dev) def circuit_lightning(): return grover_circuit(NUM_QUBITS) @@ -168,7 +168,7 @@ def circuit_lightning(): ###################################################################### # Then, to QJIT compile our circuit with Catalyst, we simply wrap it with :func:`~pennylane.qjit`. -circuit_qjit = qml.qjit(circuit_lightning) +circuit_qjit = qp.qjit(circuit_lightning) ###################################################################### @@ -264,15 +264,15 @@ def circuit_lightning(): repeat=NUM_REPS, ) runtimes_compilation = timeit.repeat( - "qml.qjit(circuit_lightning)", - setup="import pennylane as qml", + "qp.qjit(circuit_lightning)", + setup="import pennylane as qp", globals={"circuit_lightning": circuit_lightning}, number=1, repeat=1, ) runtimes_qjit_call = timeit.repeat( "_circuit_qjit()", - setup="import pennylane as qml; _circuit_qjit = qml.qjit(circuit_lightning);", + setup="import pennylane as qp; _circuit_qjit = qp.qjit(circuit_lightning);", globals={"circuit_lightning": circuit_lightning}, number=1, repeat=NUM_REPS, diff --git a/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/metadata.json b/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/metadata.json index 860c5649db..aac80d7a0d 100644 --- a/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/metadata.json +++ b/demonstrations_v2/tutorial_qjit_compile_grovers_algorithm_with_catalyst/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-11-07T00:00:00+00:00", - "dateOfLastModification": "2025-12-10T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Devices and Performance", diff --git a/demonstrations_v2/tutorial_qksd_qsp_qualtran/demo.py b/demonstrations_v2/tutorial_qksd_qsp_qualtran/demo.py index 6826cbf66e..226d797cc9 100644 --- a/demonstrations_v2/tutorial_qksd_qsp_qualtran/demo.py +++ b/demonstrations_v2/tutorial_qksd_qsp_qualtran/demo.py @@ -63,12 +63,12 @@ # `PennyLane Datasets `_ or the :mod:`pennylane.qchem` # module. We use the pre-calculated results below to create a :class:`~pennylane.ops.Hamiltonian` object. -import pennylane as qml +import pennylane as qp import numpy as np coeffs = [-2.6055398817649027, 0.4725512342017669, 0.06908378485045799, 0.06908378485045799, 0.42465877221739423, 0.040785962774025165, 0.02016371425557293, 0.33650704944175736, 0.059002396986463035, 0.059002396986463035, 0.2401948108687125, 0.2696430914655511, 0.04971997220167805, 0.04971997220167805, 0.2751875205710399, 0.30033122257656397, 0.22551650339251875] -paulis = [qml.GlobalPhase(0, 0), qml.Z(0), qml.Y(0) @ qml.Z(1) @ qml.Y(2), qml.X(0) @ qml.Z(1) @ qml.X(2), qml.Z(1), qml.Z(2), qml.Z(3), qml.Z(0) @ qml.Z(1), qml.Y(0) @ qml.Y(2), qml.X(0) @ qml.X(2), qml.Z(0) @ qml.Z(2), qml.Z(0) @ qml.Z(3), qml.Y(0) @ qml.Z(1) @ qml.Y(2) @ qml.Z(3), qml.X(0) @ qml.Z(1) @ qml.X(2) @ qml.Z(3), qml.Z(1) @ qml.Z(2), qml.Z(1) @ qml.Z(3), qml.Z(2) @ qml.Z(3)] -hamiltonian = qml.Hamiltonian(coeffs, paulis) +paulis = [qp.GlobalPhase(0, 0), qp.Z(0), qp.Y(0) @ qp.Z(1) @ qp.Y(2), qp.X(0) @ qp.Z(1) @ qp.X(2), qp.Z(1), qp.Z(2), qp.Z(3), qp.Z(0) @ qp.Z(1), qp.Y(0) @ qp.Y(2), qp.X(0) @ qp.X(2), qp.Z(0) @ qp.Z(2), qp.Z(0) @ qp.Z(3), qp.Y(0) @ qp.Z(1) @ qp.Y(2) @ qp.Z(3), qp.X(0) @ qp.Z(1) @ qp.X(2) @ qp.Z(3), qp.Z(1) @ qp.Z(2), qp.Z(1) @ qp.Z(3), qp.Z(2) @ qp.Z(3)] +hamiltonian = qp.Hamiltonian(coeffs, paulis) ###################################################################### # Next, we will define the Krylov subspace, :math:`\mathcal{K}`. @@ -175,15 +175,15 @@ def rotation_about_reflection_axis(angle, wires): """Rotation operation, S(phi_k)""" - qml.ctrl(qml.PauliX(wires[0]), wires[1:], (0,) * len(wires[1:])) - qml.RZ(angle, wires[0]) - qml.ctrl(qml.PauliX(wires[0]), wires[1:], (0,) * len(wires[1:])) + qp.ctrl(qp.PauliX(wires[0]), wires[1:], (0,) * len(wires[1:])) + qp.RZ(angle, wires[0]) + qp.ctrl(qp.PauliX(wires[0]), wires[1:], (0,) * len(wires[1:])) def qsp(lcu, angles, rot_wires, prep_wires): """Applies QSP by alternating between S(phi_k) and U_{QSP}""" for angle in angles[::-1][:-1]: rotation_about_reflection_axis(angle, rot_wires) - qml.PrepSelPrep(lcu, control=prep_wires) + qp.PrepSelPrep(lcu, control=prep_wires) rotation_about_reflection_axis(angles[0], rot_wires) ###################################################################### @@ -192,19 +192,19 @@ def qsp(lcu, angles, rot_wires, prep_wires): # polynomial. def qsp_poly_complex(lcu, angles_real, angles_imag, ctrl_wire, rot_wires, prep_wires): - qml.H(ctrl_wire) - qml.ctrl(qsp, ctrl_wire, 0)(lcu, angles_real, rot_wires, prep_wires) - qml.ctrl(qsp, ctrl_wire, 1)(lcu, angles_imag, rot_wires, prep_wires) - qml.H(ctrl_wire) + qp.H(ctrl_wire) + qp.ctrl(qsp, ctrl_wire, 0)(lcu, angles_real, rot_wires, prep_wires) + qp.ctrl(qsp, ctrl_wire, 1)(lcu, angles_imag, rot_wires, prep_wires) + qp.H(ctrl_wire) ###################################################################### # Additionally, we require a template to perform the :math:`R_0` reflection for our measurements. def reflection(wire, ctrl_wires): """Reflection operator, R_0""" - qml.ctrl(qml.X(wire), ctrl_wires, [0] * len(ctrl_wires)) - qml.Z(wire) - qml.ctrl(qml.X(wire), ctrl_wires, [0] * len(ctrl_wires)) + qp.ctrl(qp.X(wire), ctrl_wires, [0] * len(ctrl_wires)) + qp.Z(wire) + qp.ctrl(qp.X(wire), ctrl_wires, [0] * len(ctrl_wires)) ###################################################################### # We will also need to split even- and odd-parity polynomial terms, which is captured in the @@ -221,10 +221,10 @@ def reflection(wire, ctrl_wires): # and return measurements of the elements of # the one-particle reduced density matrix: -dev = qml.device("lightning.qubit") -ref_state = qml.qchem.hf_state(electrons=4, orbitals=4) +dev = qp.device("lightning.qubit") +ref_state = qp.qchem.hf_state(electrons=4, orbitals=4) -@qml.qnode(dev) +@qp.qnode(dev) def krylov_qsp(lcu, even_real, even_imag, odd_real, odd_imag, obs, measure_reflection=False): """Prepares the Krylov ground-state by applying QSP with the input angles. Then measures the expectation value of the desired observable. @@ -239,22 +239,22 @@ def krylov_qsp(lcu, even_real, even_imag, odd_real, odd_imag, obs, measure_refle #prepare the reference state for i in hamiltonian.wires: - qml.X(i) + qp.X(i) if measure_reflection: # preprocessing for reflection measurement - qml.X(rdm_ctrl_wire) + qp.X(rdm_ctrl_wire) - qml.H(ctrl_wires[0]) - qml.ctrl(qsp_poly_complex, ctrl_wires[0], 0)(lcu, even_real, even_imag, ctrl_wires[1], + qp.H(ctrl_wires[0]) + qp.ctrl(qsp_poly_complex, ctrl_wires[0], 0)(lcu, even_real, even_imag, ctrl_wires[1], rot_wires, prep_wires) - qml.ctrl(qsp_poly_complex, ctrl_wires[0], 1)(lcu, odd_real, odd_imag, ctrl_wires[1], + qp.ctrl(qsp_poly_complex, ctrl_wires[0], 1)(lcu, odd_real, odd_imag, ctrl_wires[1], rot_wires, prep_wires) - qml.H(ctrl_wires[0]) + qp.H(ctrl_wires[0]) # measurements if measure_reflection: - return qml.expval(qml.prod(reflection)(rdm_ctrl_wire, set(ctrl_wires+prep_wires))@obs) - return qml.expval(obs) + return qp.expval(qp.prod(reflection)(rdm_ctrl_wire, set(ctrl_wires+prep_wires))@obs) + return qp.expval(obs) ###################################################################### @@ -262,8 +262,8 @@ def krylov_qsp(lcu, even_real, even_imag, odd_real, odd_imag, obs, measure_refle # We can obtain the Jordan-Wigner mapping of the fermionic operators via PennyLane using the # :func:`~pennylane.fermi.from_string` and :func:`~pennylane.jordan_wigner` functions as follows: -Epq = qml.fermi.from_string('0+ 0-') -obs = qml.jordan_wigner(Epq) +Epq = qp.fermi.from_string('0+ 0-') +obs = qp.jordan_wigner(Epq) ###################################################################### # For this demo, we used a Krylov subspace dimension of :math:`D=15` and pre-computed QSP angles @@ -301,7 +301,7 @@ def krylov_qsp(lcu, even_real, even_imag, odd_real, odd_imag, obs, measure_refle # We first convert the PennyLane circuit to a Qualtran bloq using :func:`~pennylane.to_bloq` and # then use the call graph to count the required gates: -bloq = qml.to_bloq(krylov_qsp, map_ops=False, +bloq = qp.to_bloq(krylov_qsp, map_ops=False, even_real=even_real, even_imag=even_imag, odd_real=odd_real, odd_imag=odd_imag, lcu=hamiltonian, obs=obs) @@ -333,7 +333,7 @@ def krylov_qsp(lcu, even_real, even_imag, odd_real, odd_imag, obs, measure_refle ###################################################################### # We then repeat the gate counts and see they have increased: -bloq = qml.to_bloq(krylov_qsp, map_ops=False, even_real=even_real, +bloq = qp.to_bloq(krylov_qsp, map_ops=False, even_real=even_real, even_imag=even_imag, odd_real=odd_real, odd_imag=odd_imag, lcu=hamiltonian, obs=obs) @@ -352,7 +352,7 @@ def krylov_qsp(lcu, even_real, even_imag, odd_real, odd_imag, obs, measure_refle def count_cnots(krylov_dimension): even_real = even_imag = odd_real = odd_imag = np.random.random(krylov_dimension) - bloq = qml.to_bloq(krylov_qsp, map_ops=False, even_real=even_real, + bloq = qp.to_bloq(krylov_qsp, map_ops=False, even_real=even_real, even_imag=even_imag, odd_real=odd_real, odd_imag=odd_imag, lcu=hamiltonian, obs=obs) _, sigma = bloq.call_graph(generalizer=generalize_rotation_angle) diff --git a/demonstrations_v2/tutorial_qksd_qsp_qualtran/metadata.json b/demonstrations_v2/tutorial_qksd_qsp_qualtran/metadata.json index 516d7f939a..3819718bb2 100644 --- a/demonstrations_v2/tutorial_qksd_qsp_qualtran/metadata.json +++ b/demonstrations_v2/tutorial_qksd_qsp_qualtran/metadata.json @@ -17,7 +17,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-08-29T00:00:00+00:00", - "dateOfLastModification": "2026-01-23T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing" ], diff --git a/demonstrations_v2/tutorial_qnn_module_torch/demo.py b/demonstrations_v2/tutorial_qnn_module_torch/demo.py index bd7e4fb028..a9aafbf9df 100644 --- a/demonstrations_v2/tutorial_qnn_module_torch/demo.py +++ b/demonstrations_v2/tutorial_qnn_module_torch/demo.py @@ -76,16 +76,16 @@ # :doc:`default.qubit ` simulator and # operations from the :doc:`templates ` module. -import pennylane as qml +import pennylane as qp n_qubits = 2 -dev = qml.device("default.qubit", wires=n_qubits) +dev = qp.device("default.qubit", wires=n_qubits) -@qml.qnode(dev) +@qp.qnode(dev) def qnode(inputs, weights): - qml.AngleEmbedding(inputs, wires=range(n_qubits)) - qml.BasicEntanglerLayers(weights, wires=range(n_qubits)) - return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)] + qp.AngleEmbedding(inputs, wires=range(n_qubits)) + qp.BasicEntanglerLayers(weights, wires=range(n_qubits)) + return [qp.expval(qp.PauliZ(wires=i)) for i in range(n_qubits)] ############################################################################### # Interfacing with Torch @@ -113,7 +113,7 @@ def qnode(inputs, weights): # # Now that ``weight_shapes`` is defined, it is easy to then convert the QNode: -qlayer = qml.qnn.TorchLayer(qnode, weight_shapes) +qlayer = qp.qnn.TorchLayer(qnode, weight_shapes) ############################################################################### # With this done, the QNode can now be treated just like any other ``torch.nn`` layer and we can @@ -235,8 +235,8 @@ class HybridModel(torch.nn.Module): def __init__(self): super().__init__() self.clayer_1 = torch.nn.Linear(2, 4) - self.qlayer_1 = qml.qnn.TorchLayer(qnode, weight_shapes) - self.qlayer_2 = qml.qnn.TorchLayer(qnode, weight_shapes) + self.qlayer_1 = qp.qnn.TorchLayer(qnode, weight_shapes) + self.qlayer_2 = qp.qnn.TorchLayer(qnode, weight_shapes) self.clayer_2 = torch.nn.Linear(4, 2) self.softmax = torch.nn.Softmax(dim=1) diff --git a/demonstrations_v2/tutorial_qnn_module_torch/metadata.json b/demonstrations_v2/tutorial_qnn_module_torch/metadata.json index 7147ab3159..68c7945588 100644 --- a/demonstrations_v2/tutorial_qnn_module_torch/metadata.json +++ b/demonstrations_v2/tutorial_qnn_module_torch/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-11-02T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Devices and Performance", "Quantum Machine Learning" diff --git a/demonstrations_v2/tutorial_qnn_multivariate_regression/demo.py b/demonstrations_v2/tutorial_qnn_multivariate_regression/demo.py index 61b0ea9006..75cd2d7424 100644 --- a/demonstrations_v2/tutorial_qnn_multivariate_regression/demo.py +++ b/demonstrations_v2/tutorial_qnn_multivariate_regression/demo.py @@ -67,7 +67,7 @@ """ import matplotlib.pyplot as plt -import pennylane as qml +import pennylane as qp from pennylane import numpy as pnp import jax from jax import numpy as jnp @@ -75,7 +75,7 @@ pnp.random.seed(42) -dev = qml.device('default.qubit', wires=2) +dev = qp.device('default.qubit', wires=2) ###################################################################### # Now we will construct the data-encoding circuit block, :math:`S(\vec{x})`, as a product of :math:`R_z` rotations: @@ -86,18 +86,18 @@ # Specifically, we define the :math:`S(\vec{x})` operator using the :class:`~.pennylane.AngleEmbedding` function. def S(x): - qml.AngleEmbedding( x, wires=[0,1],rotation='Z') + qp.AngleEmbedding( x, wires=[0,1],rotation='Z') ###################################################################### # For the :math:`W(\vec{\theta})` operator, we will use an ansatz that is available in PennyLane, called :class:`~.pennylane.StronglyEntanglingLayers`. def W(params): - qml.StronglyEntanglingLayers(params, wires=[0,1]) + qp.StronglyEntanglingLayers(params, wires=[0,1]) ###################################################################### # Now we will build the circuit in PennyLane by alternating layers of :math:`W(\vec{\theta})` and :math:`S(\vec{x})` layers. On this prepared state, we estimate the expectation value of the :math:`Z\otimes Z` operator, using PennyLane's :func:`~.pennylane.expval` function. -@qml.qnode(dev,interface="jax") +@qp.qnode(dev,interface="jax") def quantum_neural_network(params, x): layers=len(params[:,0,0])-1 n_wires=len(params[0,:,0]) @@ -107,7 +107,7 @@ def quantum_neural_network(params, x): S(x) W(params[-1,:,:].reshape(1,n_wires,n_params_rot)) - return qml.expval(qml.PauliZ(wires=0)@qml.PauliZ(wires=1)) + return qp.expval(qp.PauliZ(wires=0)@qp.PauliZ(wires=1)) ###################################################################### # The function we will be fitting is :math:`f(x_1, x_2) = \frac{1}{2} \left( x_1^2 + x_2^2 \right)`, which we will define as ``target_function``: @@ -203,7 +203,7 @@ def optimization_jit(params, data, targets, print_training=False): wires=2 layers=4 -params_shape = qml.StronglyEntanglingLayers.shape(n_layers=layers+1,n_wires=wires) +params_shape = qp.StronglyEntanglingLayers.shape(n_layers=layers+1,n_wires=wires) params=pnp.random.default_rng().random(size=params_shape) best_params=optimization_jit(params, x_train, jnp.array(y_train), print_training=True) diff --git a/demonstrations_v2/tutorial_qnn_multivariate_regression/metadata.json b/demonstrations_v2/tutorial_qnn_multivariate_regression/metadata.json index f4e9f44d1c..733a5bd8ff 100644 --- a/demonstrations_v2/tutorial_qnn_multivariate_regression/metadata.json +++ b/demonstrations_v2/tutorial_qnn_multivariate_regression/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-10-01T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Computing", "Quantum Machine Learning", diff --git a/demonstrations_v2/tutorial_qpe/demo.py b/demonstrations_v2/tutorial_qpe/demo.py index 33b1e51edd..ea81e50736 100644 --- a/demonstrations_v2/tutorial_qpe/demo.py +++ b/demonstrations_v2/tutorial_qpe/demo.py @@ -207,11 +207,11 @@ """ -import pennylane as qml +import pennylane as qp import numpy as np def U(wires): - return qml.PhaseShift(2 * np.pi / 5, wires=wires) + return qp.PhaseShift(2 * np.pi / 5, wires=wires) ############################################################################## # We construct a uniform superposition by applying Hadamard gates followed by a :class:`~.ControlledSequence` @@ -220,21 +220,21 @@ def U(wires): # return the probability of each computational basis state. -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def circuit_qpe(estimation_wires): # initialize to state |1> - qml.PauliX(wires=0) + qp.PauliX(wires=0) for wire in estimation_wires: - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) - qml.ControlledSequence(U(wires=0), control=estimation_wires) + qp.ControlledSequence(U(wires=0), control=estimation_wires) - qml.adjoint(qml.QFT)(wires=estimation_wires) + qp.adjoint(qp.QFT)(wires=estimation_wires) - return qml.probs(wires=estimation_wires) + return qp.probs(wires=estimation_wires) ############################################################################## # Let's run the circuit and plot the results. We use 4 estimation qubits. diff --git a/demonstrations_v2/tutorial_qpe/metadata.json b/demonstrations_v2/tutorial_qpe/metadata.json index 47d1d47529..cd0738b721 100644 --- a/demonstrations_v2/tutorial_qpe/metadata.json +++ b/demonstrations_v2/tutorial_qpe/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-01-30T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_qsvt_hardware/demo.py b/demonstrations_v2/tutorial_qsvt_hardware/demo.py index 2130f6538e..eb70b82cb8 100644 --- a/demonstrations_v2/tutorial_qsvt_hardware/demo.py +++ b/demonstrations_v2/tutorial_qsvt_hardware/demo.py @@ -24,7 +24,7 @@ fundamental components of the QSVT algorithm: - **Projection angles**: A list of angles that will determine the coefficients of the polynomial to be applied. -- **Block encoding**: The strategy used to encode the Hamiltonian. We will use the :doc:`linear combinations of unitaries ` approach via the PennyLane :class:`~.qml.PrepSelPrep` operation. +- **Block encoding**: The strategy used to encode the Hamiltonian. We will use the :doc:`linear combinations of unitaries ` approach via the PennyLane :class:`~.qp.PrepSelPrep` operation. Calculating angles is not a trivial task, but we can use the PennyLane function :func:`~.pennylane.poly_to_angles` to obtain them. There are also tools such as `pyqsp `_ that can do the job for us. @@ -35,9 +35,9 @@ polynomial, ordered from lowest to highest power, as input. We also need to define the routine for which the angles are computed, which is ``'QSVT'`` here. """ -import pennylane as qml +import pennylane as qp poly = [0, -1.0, 0, 1/2, 0, 1/2] -angles_pl = qml.poly_to_angles(poly, "QSVT") +angles_pl = qp.poly_to_angles(poly, "QSVT") print(angles_pl) ###################################################################### @@ -66,7 +66,7 @@ # context of QSP and are not the same as the ones we have to use in QSVT. # We can use the :func:`~.pennylane.transform_angles` function to transform the angles: -angles_pyqsp = qml.transform_angles(ang_seq, "QSP", "QSVT") +angles_pyqsp = qp.transform_angles(ang_seq, "QSP", "QSVT") print(angles_pyqsp) ###################################################################### @@ -78,23 +78,23 @@ # QSVT on hardware # ----------------- # -# The :class:`~.qml.QSVT` template expects two inputs. The first one is the block encoding operator, :class:`~.qml.PrepSelPrep`, -# and the second one is a set of projection operators, :class:`~.qml.PCPhase`, that encode the angles properly. +# The :class:`~.qp.QSVT` template expects two inputs. The first one is the block encoding operator, :class:`~.qp.PrepSelPrep`, +# and the second one is a set of projection operators, :class:`~.qp.PCPhase`, that encode the angles properly. # We will see how to apply them later, but first let's define # a Hamiltonian and manually apply the polynomial of interest: -import pennylane as qml +import pennylane as qp import numpy as np from numpy.linalg import matrix_power as mpow coeffs = np.array([0.2, -0.7, -0.6]) coeffs /= np.linalg.norm(coeffs, ord=1) # Normalize the coefficients -obs = [qml.X(3), qml.X(3) @ qml.Z(4), qml.Z(3) @ qml.Y(4)] +obs = [qp.X(3), qp.X(3) @ qp.Z(4), qp.Z(3) @ qp.Y(4)] -H = qml.dot(coeffs, obs) +H = qp.dot(coeffs, obs) -H_mat = qml.matrix(H, wire_order=[3, 4]) +H_mat = qp.matrix(H, wire_order=[3, 4]) # We calculate p(H) = -H + 0.5 * H^3 + 0.5 * H^5 H_poly = -H_mat + 0.5 * mpow(H_mat, 3) + 0.5 * mpow(H_mat, 5) @@ -103,32 +103,32 @@ ###################################################################### # Now that we know what the target result is, let's see how to apply the polynomial with a quantum circuit instead. -# We start by defining the proper input operators for the :class:`~.qml.QSVT` template. +# We start by defining the proper input operators for the :class:`~.qp.QSVT` template. # We need |log2(len(coeffs))| = 2 control wires to encode the Hamiltonian control_wires = [1, 2] -block_encode = qml.PrepSelPrep(H, control=control_wires) +block_encode = qp.PrepSelPrep(H, control=control_wires) projectors = [ - qml.PCPhase(angles_pl[i], dim=2 ** len(H.wires), wires=control_wires + H.wires) + qp.PCPhase(angles_pl[i], dim=2 ** len(H.wires), wires=control_wires + H.wires) for i in range(len(angles_pl)) ] -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): - qml.Hadamard(0) - qml.ctrl(qml.QSVT, control=0, control_values=[1])(block_encode, projectors) - qml.ctrl(qml.adjoint(qml.QSVT), control=0, control_values=[0])(block_encode, projectors) - qml.Hadamard(0) + qp.Hadamard(0) + qp.ctrl(qp.QSVT, control=0, control_values=[1])(block_encode, projectors) + qp.ctrl(qp.adjoint(qp.QSVT), control=0, control_values=[0])(block_encode, projectors) + qp.Hadamard(0) - return qml.state() + return qp.state() -matrix = qml.matrix(circuit, wire_order=[0] + control_wires + H.wires)() +matrix = qp.matrix(circuit, wire_order=[0] + control_wires + H.wires)() print(np.round(matrix[: 2 ** len(H.wires), : 2 ** len(H.wires)], 4)) ###################################################################### diff --git a/demonstrations_v2/tutorial_qsvt_hardware/metadata.json b/demonstrations_v2/tutorial_qsvt_hardware/metadata.json index 648534b0d9..5c830a9513 100644 --- a/demonstrations_v2/tutorial_qsvt_hardware/metadata.json +++ b/demonstrations_v2/tutorial_qsvt_hardware/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-09-18T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_quantum_analytic_descent/demo.py b/demonstrations_v2/tutorial_quantum_analytic_descent/demo.py index a950327342..35765aa1b3 100644 --- a/demonstrations_v2/tutorial_quantum_analytic_descent/demo.py +++ b/demonstrations_v2/tutorial_quantum_analytic_descent/demo.py @@ -88,7 +88,7 @@ Let's look at a toy example to illustrate this structure of the cost function. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np import matplotlib.pyplot as plt import warnings @@ -98,14 +98,14 @@ np.random.seed(0) # Create a device with 2 qubits. -dev = qml.device("lightning.qubit", wires=2) +dev = qp.device("lightning.qubit", wires=2) # Define the variational form V and observable M and combine them into a QNode. -@qml.qnode(dev, diff_method="parameter-shift", max_diff=2) +@qp.qnode(dev, diff_method="parameter-shift", max_diff=2) def circuit(parameters): - qml.RX(parameters[0], wires=0) - qml.RX(parameters[1], wires=1) - return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1)) + qp.RX(parameters[0], wires=0) + qp.RX(parameters[1], wires=1) + return qp.expval(qp.PauliZ(0) @ qp.PauliZ(1)) ############################################################################### @@ -308,9 +308,9 @@ def get_model_data(fun, params): E_A = fun(params) # E_B contains the gradient. - E_B = qml.grad(fun)(params) + E_B = qp.grad(fun)(params) - hessian = qml.jacobian(qml.grad(fun))(params) + hessian = qp.jacobian(qp.grad(fun))(params) # E_C contains the slightly adapted diagonal of the Hessian. E_C = np.diag(hessian) + E_A / 2 @@ -577,7 +577,7 @@ def plot_cost_and_model(f, model, params, shift_radius=5 * np.pi / 8, num_points if iter_outer == 0: print(f"True energy at initial parameters: {np.round(coeffs[0], decimals=4)}\n") - opt = qml.AdamOptimizer(0.05) + opt = qp.AdamOptimizer(0.05) # Recall that the parameters of the model are relative coordinates. # Correspondingly, we initialize at 0, not at parameters. relative_parameters = np.zeros_like(parameters, requires_grad=True) diff --git a/demonstrations_v2/tutorial_quantum_analytic_descent/metadata.json b/demonstrations_v2/tutorial_quantum_analytic_descent/metadata.json index 91f0768ded..7353e73b2e 100644 --- a/demonstrations_v2/tutorial_quantum_analytic_descent/metadata.json +++ b/demonstrations_v2/tutorial_quantum_analytic_descent/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-06-30T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_quantum_chebyshev_transform/demo.py b/demonstrations_v2/tutorial_quantum_chebyshev_transform/demo.py index ba6131bd52..018ea3c1f0 100644 --- a/demonstrations_v2/tutorial_quantum_chebyshev_transform/demo.py +++ b/demonstrations_v2/tutorial_quantum_chebyshev_transform/demo.py @@ -159,7 +159,7 @@ To start, we will define a function for the CNOT ladder. """ -import pennylane as qml +import pennylane as qp # Number of qubits (non-auxiliary qubit). N = 4 @@ -167,11 +167,11 @@ def CNOT_ladder(): for wire in range(1, N + 1): - qml.CNOT([0, wire]) + qp.CNOT([0, wire]) ############################################# -# After the initial CNOT ladder comes an :math:`N+1` QFT circuit, which can be implemented using ``qml.QFT``. +# After the initial CNOT ladder comes an :math:`N+1` QFT circuit, which can be implemented using ``qp.QFT``. # # Next are phase rotations and shifts. # For the auxiliary qubit, there is a :math:`Z` rotation by and angle of :math:`-\pi(2^N - 1)/2^{N+1}` followed by a phase shift of :math:`-\pi/2^{(N+1)}` . @@ -185,10 +185,10 @@ def CNOT_ladder(): def rotate_phases(): """Rotates and shifts the phase of the auxiliary qubit and rotates the jth qubit by pi/2^(j+1) in Z.""" - qml.RZ(-pi * (2**N - 1) / 2 ** (N + 1), wires=0) - qml.PhaseShift(-pi / 2 ** (N + 1), wires=0) + qp.RZ(-pi * (2**N - 1) / 2 ** (N + 1), wires=0) + qp.PhaseShift(-pi / 2 ** (N + 1), wires=0) for wire in range(1, N + 1): - qml.RZ(pi / 2 ** (wire + 1), wires=wire) + qp.RZ(pi / 2 ** (wire + 1), wires=wire) ############################################# @@ -202,7 +202,7 @@ def permute_elements(): """Reorders amplitudes of the conditioned states.""" for wire in reversed(range(1, N + 1)): control_wires = [0] + list(range(wire + 1, N + 1)) - qml.MultiControlledX(wires=(*control_wires, wire)) + qp.MultiControlledX(wires=(*control_wires, wire)) ############################################# @@ -211,66 +211,66 @@ def permute_elements(): # # The last part is a phase adjustment of the auxiliary qubit: a rotation in :math:`Y` by :math:`\pi/2`, a phase shift of :math:`-\pi/2` and a multicontrolled :math:`X` rotation by :math:`\pi/2`. # All of the other qubits control the :math:`X` rotation, but the control is sandwiched by Pauli :math:`X` operators. -# We can implement the multicontrolled :math:`X` rotation by using the function ``qml.ctrl`` on ``qml.RX``, specifying the target wire in ``qml.RX`` and the control wires as the second argument of ``qml.ctrl``. +# We can implement the multicontrolled :math:`X` rotation by using the function ``qp.ctrl`` on ``qp.RX``, specifying the target wire in ``qp.RX`` and the control wires as the second argument of ``qp.ctrl``. def adjust_phases(): """Adjusts the phase of the auxiliary qubit.""" - qml.RY(-pi / 2, wires=0) - qml.PhaseShift(-pi / 2, wires=0) + qp.RY(-pi / 2, wires=0) + qp.PhaseShift(-pi / 2, wires=0) # First Pauli X gates. for wire in range(1, N + 1): - qml.PauliX(wires=wire) + qp.PauliX(wires=wire) # Controlled RX gate. - qml.ctrl(qml.RX(pi / 2, wires=0), range(1, N + 1)) + qp.ctrl(qp.RX(pi / 2, wires=0), range(1, N + 1)) # Second Pauli X gates. for wire in range(1, N + 1): - qml.PauliX(wires=wire) + qp.PauliX(wires=wire) ############################################# # All together, we can construct the circuit. -# We have added :class:`qml.BasisState` to initialize the input in any computational basis state with the optional argument ``state``. +# We have added :class:`qp.BasisState` to initialize the input in any computational basis state with the optional argument ``state``. def QChT(): """Performs the quantum Chebyshev transform.""" - qml.Hadamard(wires=0) + qp.Hadamard(wires=0) CNOT_ladder() - qml.QFT(wires=range(N + 1)) + qp.QFT(wires=range(N + 1)) rotate_phases() permute_elements() CNOT_ladder() adjust_phases() -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def circuit(state=0): - qml.BasisState(state=state, wires=range(1, N + 1)) + qp.BasisState(state=state, wires=range(1, N + 1)) QChT() - return qml.state() + return qp.state() ############################################# -# Finally, we can reproduce the circuit diagram shown at the beginning of this section using ``qml.draw_mpl``. +# Finally, we can reproduce the circuit diagram shown at the beginning of this section using ``qp.draw_mpl``. def circuit_to_draw(): - qml.BasisState(state=0, wires=range(1, N + 1)) + qp.BasisState(state=0, wires=range(1, N + 1)) QChT() -fig, ax = qml.draw_mpl(circuit_to_draw, decimals=2, style="pennylane")() +fig, ax = qp.draw_mpl(circuit_to_draw, decimals=2, style="pennylane")() fig.show() ############################################# -# Note we defined a new function for the circuit to simplify the drawing, removing the returned ``qml.state``. +# Note we defined a new function for the circuit to simplify the drawing, removing the returned ``qp.state``. # # Testing the quantum Chebyshev transform # ---------------- diff --git a/demonstrations_v2/tutorial_quantum_chebyshev_transform/metadata.json b/demonstrations_v2/tutorial_quantum_chebyshev_transform/metadata.json index 9275e8cc09..1fafcf66b6 100644 --- a/demonstrations_v2/tutorial_quantum_chebyshev_transform/metadata.json +++ b/demonstrations_v2/tutorial_quantum_chebyshev_transform/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-07-22T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Machine Learning"