diff --git a/demonstrations_v2/tutorial_shors_algorithm_catalyst/demo.py b/demonstrations_v2/tutorial_shors_algorithm_catalyst/demo.py index a29b8bd9df..3be6f4b9cf 100644 --- a/demonstrations_v2/tutorial_shors_algorithm_catalyst/demo.py +++ b/demonstrations_v2/tutorial_shors_algorithm_catalyst/demo.py @@ -173,10 +173,10 @@ def shors_algorithm(N): # compilation of the *entire* algorithm from beginning to end. On the surface, it # looks to be as simple as the following: -import pennylane as qml +import pennylane as qp -@qml.qjit +@qp.qjit def shors_algorithm(N): # Implementation goes here return p, q @@ -188,7 +188,7 @@ def shors_algorithm(N): # important parts such that the signature can be as minimal as this: -@qml.qjit(autograph=True, static_argnums=(1)) +@qp.qjit(autograph=True, static_argnums=(1)) def shors_algorithm(N, n_bits): # Implementation goes here return p, q @@ -667,7 +667,7 @@ def phase_to_order(phase, max_denominator): # Below, we have the implementations of the arithmetic circuits derived in the # previous section. -import pennylane as qml +import pennylane as qp import catalyst from catalyst import measure @@ -679,10 +679,10 @@ def QFT(wires): shifts = jnp.array([2 * jnp.pi * 2**-i for i in range(2, len(wires) + 1)]) for i in range(len(wires)): - qml.Hadamard(wires[i]) + qp.Hadamard(wires[i]) for j in range(len(shifts) - i): - qml.ControlledPhaseShift(shifts[j], wires=[wires[(i + 1) + j], wires[i]]) + qp.ControlledPhaseShift(shifts[j], wires=[wires[(i + 1) + j], wires[i]]) def fourier_adder_phase_shift(a, wires): @@ -694,30 +694,30 @@ def fourier_adder_phase_shift(a, wires): for i in range(len(wires)): if phases[i] != 0: - qml.PhaseShift(2 * jnp.pi * phases[i], wires=wires[i]) + qp.PhaseShift(2 * jnp.pi * phases[i], wires=wires[i]) def doubly_controlled_adder(N, a, control_wires, wires, aux_wire): """Sends |c>|x>QFT(|b>)|0> -> |c>|x>QFT(|b + c x a) mod N>)|0>.""" - qml.ctrl(fourier_adder_phase_shift, control=control_wires)(a, wires) + qp.ctrl(fourier_adder_phase_shift, control=control_wires)(a, wires) - qml.adjoint(fourier_adder_phase_shift)(N, wires) + qp.adjoint(fourier_adder_phase_shift)(N, wires) - qml.adjoint(QFT)(wires) - qml.CNOT(wires=[wires[0], aux_wire]) + qp.adjoint(QFT)(wires) + qp.CNOT(wires=[wires[0], aux_wire]) QFT(wires) - qml.ctrl(fourier_adder_phase_shift, control=aux_wire)(N, wires) + qp.ctrl(fourier_adder_phase_shift, control=aux_wire)(N, wires) - qml.adjoint(qml.ctrl(fourier_adder_phase_shift, control=control_wires))(a, wires) + qp.adjoint(qp.ctrl(fourier_adder_phase_shift, control=control_wires))(a, wires) - qml.adjoint(QFT)(wires) - qml.PauliX(wires=wires[0]) - qml.CNOT(wires=[wires[0], aux_wire]) - qml.PauliX(wires=wires[0]) + qp.adjoint(QFT)(wires) + qp.PauliX(wires=wires[0]) + qp.CNOT(wires=[wires[0], aux_wire]) + qp.PauliX(wires=wires[0]) QFT(wires) - qml.ctrl(fourier_adder_phase_shift, control=control_wires)(a, wires) + qp.ctrl(fourier_adder_phase_shift, control=control_wires)(a, wires) def controlled_ua(N, a, control_wire, target_wires, aux_wires, mult_a_mask, mult_a_inv_mask): @@ -735,14 +735,14 @@ def controlled_ua(N, a, control_wire, target_wires, aux_wires, mult_a_mask, mult N, pow_a, [control_wire, target_wires[n - i - 1]], aux_wires[:-1], aux_wires[-1] ) - qml.adjoint(QFT)(wires=aux_wires[:-1]) + qp.adjoint(QFT)(wires=aux_wires[:-1]) # Controlled SWAP the target and aux wires; note that the top-most aux wire # is only to catch overflow, so we ignore it here. for i in range(n): - qml.CNOT(wires=[aux_wires[i + 1], target_wires[i]]) - qml.Toffoli(wires=[control_wire, target_wires[i], aux_wires[i + 1]]) - qml.CNOT(wires=[aux_wires[i + 1], target_wires[i]]) + qp.CNOT(wires=[aux_wires[i + 1], target_wires[i]]) + qp.Toffoli(wires=[control_wire, target_wires[i], aux_wires[i + 1]]) + qp.CNOT(wires=[aux_wires[i + 1], target_wires[i]]) # Adjoint of controlled multiplication with the modular inverse of a a_mod_inv = modular_inverse(a, N) @@ -752,7 +752,7 @@ def controlled_ua(N, a, control_wire, target_wires, aux_wires, mult_a_mask, mult for i in range(n): if mult_a_inv_mask[i] > 0: pow_a_inv = (a_mod_inv * (2 ** (n - i - 1))) % N - qml.adjoint(doubly_controlled_adder)( + qp.adjoint(doubly_controlled_adder)( N, pow_a_inv, [control_wire, target_wires[i]], @@ -763,14 +763,14 @@ def controlled_ua(N, a, control_wire, target_wires, aux_wires, mult_a_mask, mult ###################################################################### # Finally, let's put it all together in the core portion of Shor's algorithm, -# under the ``@qml.qjit`` decorator. +# under the ``@qp.qjit`` decorator. from jax import random # ``n_bits`` is a static argument because ``jnp.arange`` does not currently # support dynamically-shaped arrays when jitted. -@qml.qjit(autograph=True, static_argnums=(3)) +@qp.qjit(autograph=True, static_argnums=(3)) def shors_algorithm(N, key, a, n_bits, n_trials): # If no explicit a is passed (denoted by a = 0), randomly choose a # non-trivial value of a that does not have a common factor with N. @@ -783,10 +783,10 @@ def shors_algorithm(N, key, a, n_bits, n_trials): target_wires = jnp.arange(n_bits) + 1 aux_wires = jnp.arange(n_bits + 2) + n_bits + 1 - dev = qml.device("lightning.qubit", wires=2 * n_bits + 3) + dev = qp.device("lightning.qubit", wires=2 * n_bits + 3) - @qml.set_shots(1) - @qml.qnode(dev) + @qp.set_shots(1) + @qp.qnode(dev) def run_qpe(): meas_results = jnp.zeros((n_bits,), dtype=jnp.int32) cumulative_phase = jnp.array(0.0) @@ -799,7 +799,7 @@ def run_qpe(): a_inv_mask = a_mask # Initialize the target register of QPE in |1> - qml.PauliX(wires=target_wires[-1]) + qp.PauliX(wires=target_wires[-1]) # The "first" QFT on the auxiliary register; required here because # QFT are largely omitted in the modular arithmetic routines due to @@ -807,14 +807,14 @@ def run_qpe(): QFT(wires=aux_wires[:-1]) # First iteration: add a - 1 using the Fourier adder. - qml.Hadamard(wires=est_wire) + qp.Hadamard(wires=est_wire) QFT(wires=target_wires) - qml.ctrl(fourier_adder_phase_shift, control=est_wire)(a - 1, target_wires) - qml.adjoint(QFT)(wires=target_wires) + qp.ctrl(fourier_adder_phase_shift, control=est_wire)(a - 1, target_wires) + qp.adjoint(QFT)(wires=target_wires) # Measure the estimation wire and store the phase - qml.Hadamard(wires=est_wire) + qp.Hadamard(wires=est_wire) meas_results[0] = measure(est_wire, reset=True) cumulative_phase = -2 * jnp.pi * jnp.sum(meas_results / jnp.roll(phase_divisors, 1)) @@ -838,7 +838,7 @@ def run_qpe(): jnp.unpackbits(next_pow_a.view("uint8"), bitorder="little")[:n_bits] ) - qml.Hadamard(wires=est_wire) + qp.Hadamard(wires=est_wire) controlled_ua(N, pow_cua, est_wire, target_wires, aux_wires, a_mask, a_inv_mask) @@ -846,15 +846,15 @@ def run_qpe(): a_inv_mask = jnp.zeros_like(a_inv_mask) # Rotate the estimation wire by the accumulated phase, then measure and reset it - qml.PhaseShift(cumulative_phase, wires=est_wire) - qml.Hadamard(wires=est_wire) + qp.PhaseShift(cumulative_phase, wires=est_wire) + qp.Hadamard(wires=est_wire) meas_results[pow_a_idx] = measure(est_wire, reset=True) cumulative_phase = ( -2 * jnp.pi * jnp.sum(meas_results / jnp.roll(phase_divisors, pow_a_idx + 1)) ) # The adjoint partner of the QFT from the beginning, to reset the auxiliary register - qml.adjoint(QFT)(wires=aux_wires[:-1]) + qp.adjoint(QFT)(wires=aux_wires[:-1]) return meas_results @@ -965,8 +965,8 @@ def run_qpe(): # circuits for many different :math:`N` using both the QJIT version, and the # plain PennyLane version below. Note the standard PennyLane version makes use # of many of the same subroutines and optimizations, but due to limitations on -# how PennyLane handles mid-circuit measurements, we must use ``qml.cond`` and -# explicit ``qml.PhaseShift`` gates. +# how PennyLane handles mid-circuit measurements, we must use ``qp.cond`` and +# explicit ``qp.PhaseShift`` gates. def shors_algorithm_no_qjit(N, key, a, n_bits, n_trials): @@ -974,10 +974,10 @@ def shors_algorithm_no_qjit(N, key, a, n_bits, n_trials): target_wires = list(range(1, n_bits + 1)) aux_wires = list(range(n_bits + 1, 2 * n_bits + 3)) - dev = qml.device("lightning.qubit", wires=2 * n_bits + 3) + dev = qp.device("lightning.qubit", wires=2 * n_bits + 3) - @qml.set_shots(1) - @qml.qnode(dev) + @qp.set_shots(1) + @qp.qnode(dev) def run_qpe(): a_mask = jnp.zeros(n_bits, dtype=jnp.int64) a_mask = a_mask.at[0].set(1) + jnp.array( @@ -987,18 +987,18 @@ def run_qpe(): measurements = [] - qml.PauliX(wires=target_wires[-1]) + qp.PauliX(wires=target_wires[-1]) QFT(wires=aux_wires[:-1]) - qml.Hadamard(wires=est_wire) + qp.Hadamard(wires=est_wire) QFT(wires=target_wires) - qml.ctrl(fourier_adder_phase_shift, control=est_wire)(a - 1, target_wires) - qml.adjoint(QFT)(wires=target_wires) + qp.ctrl(fourier_adder_phase_shift, control=est_wire)(a - 1, target_wires) + qp.adjoint(QFT)(wires=target_wires) - qml.Hadamard(wires=est_wire) - measurements.append(qml.measure(est_wire, reset=True)) + qp.Hadamard(wires=est_wire) + measurements.append(qp.measure(est_wire, reset=True)) powers_cua = jnp.array([repeated_squaring(a, 2**p, N) for p in range(n_bits)]) @@ -1016,7 +1016,7 @@ def run_qpe(): jnp.unpackbits(next_pow_a.view("uint8"), bitorder="little")[:n_bits] ) - qml.Hadamard(wires=est_wire) + qp.Hadamard(wires=est_wire) controlled_ua(N, pow_cua, est_wire, target_wires, aux_wires, a_mask, a_inv_mask) @@ -1025,16 +1025,16 @@ def run_qpe(): # The main difference with the QJIT version for meas_idx, meas in enumerate(measurements): - qml.cond(meas, qml.PhaseShift)( + qp.cond(meas, qp.PhaseShift)( -2 * jnp.pi / 2 ** (pow_a_idx + 2 - meas_idx), wires=est_wire ) - qml.Hadamard(wires=est_wire) - measurements.append(qml.measure(est_wire, reset=True)) + qp.Hadamard(wires=est_wire) + measurements.append(qp.measure(est_wire, reset=True)) - qml.adjoint(QFT)(wires=aux_wires[:-1]) + qp.adjoint(QFT)(wires=aux_wires[:-1]) - return qml.sample(measurements) + return qp.sample(measurements) p, q = jnp.array(0, dtype=jnp.int32), jnp.array(0, dtype=jnp.int32) successful_trials = jnp.array(0, dtype=jnp.int32) diff --git a/demonstrations_v2/tutorial_shors_algorithm_catalyst/metadata.json b/demonstrations_v2/tutorial_shors_algorithm_catalyst/metadata.json index 060fa92efe..acd9a76105 100644 --- a/demonstrations_v2/tutorial_shors_algorithm_catalyst/metadata.json +++ b/demonstrations_v2/tutorial_shors_algorithm_catalyst/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-04-04T09:00:00+00:00", - "dateOfLastModification": "2025-12-10T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_spsa/demo.py b/demonstrations_v2/tutorial_spsa/demo.py index 2d45d0a089..aca6176a11 100644 --- a/demonstrations_v2/tutorial_spsa/demo.py +++ b/demonstrations_v2/tutorial_spsa/demo.py @@ -163,25 +163,25 @@ """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np num_wires = 4 num_layers = 5 -device = qml.device("qiskit.aer", wires=num_wires) +device = qp.device("qiskit.aer", wires=num_wires) -ansatz = qml.StronglyEntanglingLayers +ansatz = qp.StronglyEntanglingLayers -all_pauliz_tensor_prod = qml.prod(*[qml.PauliZ(i) for i in range(num_wires)]) +all_pauliz_tensor_prod = qp.prod(*[qp.PauliZ(i) for i in range(num_wires)]) def circuit(param): ansatz(param, wires=list(range(num_wires))) - return qml.expval(all_pauliz_tensor_prod) + return qp.expval(all_pauliz_tensor_prod) -cost_function = qml.set_shots(qml.QNode(circuit, device), shots = 1000) +cost_function = qp.set_shots(qp.QNode(circuit, device), shots = 1000) np.random.seed(50) @@ -262,7 +262,7 @@ def run_optimizer(opt, cost_function, init_param, num_steps, interval, execs_per # `__ num_steps_spsa = 200 -opt = qml.SPSAOptimizer(maxiter=num_steps_spsa, c=0.15, a=0.2) +opt = qp.SPSAOptimizer(maxiter=num_steps_spsa, c=0.15, a=0.2) # We spend 2 circuit evaluations per step: execs_per_step = 2 cost_history_spsa, exec_history_spsa = run_optimizer( @@ -275,7 +275,7 @@ def run_optimizer(opt, cost_function, init_param, num_steps, interval, execs_per # convergence. num_steps_grad = 15 -opt = qml.GradientDescentOptimizer(stepsize=0.3) +opt = qp.GradientDescentOptimizer(stepsize=0.3) # We spend 2 circuit evaluations per parameter per step: execs_per_step = 2 * np.prod(param_shape) cost_history_grad, exec_history_grad = run_optimizer( @@ -344,21 +344,21 @@ def run_optimizer(opt, cost_function, init_param, num_steps, interval, execs_per molecule = qchem.Molecule(symbols, coordinates) h2_ham, num_qubits = qchem.molecular_hamiltonian(molecule) h2_ham_coeffs, h2_ham_ops = h2_ham.terms() -h2_ham = qml.Hamiltonian(qml.math.real(h2_ham_coeffs), h2_ham_ops) +h2_ham = qp.Hamiltonian(qp.math.real(h2_ham_coeffs), h2_ham_ops) true_energy = -1.136189454088 # Variational ansatz for H_2 - see Intro VQE demo for more details def ansatz(param, wires): - qml.BasisState(np.array([1, 1, 0, 0]), wires=wires) + qp.BasisState(np.array([1, 1, 0, 0]), wires=wires) for i in wires: - qml.Rot(*param[0, i], wires=i) - qml.CNOT(wires=[2, 3]) - qml.CNOT(wires=[2, 0]) - qml.CNOT(wires=[3, 1]) + qp.Rot(*param[0, i], wires=i) + qp.CNOT(wires=[2, 3]) + qp.CNOT(wires=[2, 0]) + qp.CNOT(wires=[3, 1]) for i in wires: - qml.Rot(*param[1, i], wires=i) + qp.Rot(*param[1, i], wires=i) ############################################################################## @@ -376,24 +376,24 @@ def ansatz(param, wires): # The above line only needs to be run once. # List the providers to pick an available backend: # IBMProvider().backends() # List all available backends -# dev = qml.device("qiskit.ibmq", wires=num_qubits, backend="ibmq_lima") +# dev = qp.device("qiskit.ibmq", wires=num_qubits, backend="ibmq_lima") from qiskit_ibm_runtime.fake_provider import FakeLimaV2 as FakeLima from qiskit_aer import noise # Load a fake backed to create a noise model, and create a device using that model noise_model = noise.NoiseModel.from_backend(FakeLima()) -noisy_device = qml.device( +noisy_device = qp.device( "qiskit.aer", wires=num_qubits, noise_model=noise_model ) def circuit(param): ansatz(param, range(num_qubits)) - return qml.expval(h2_ham) + return qp.expval(h2_ham) -cost_function = qml.set_shots(qml.QNode(circuit, noisy_device), shots = 1000) +cost_function = qp.set_shots(qp.QNode(circuit, noisy_device), shots = 1000) # This random seed was used in the original VQE demo and is known to allow the # gradient descent algorithm to converge to the global minimum. @@ -402,7 +402,7 @@ def circuit(param): init_param = np.random.normal(0, np.pi, param_shape, requires_grad=True) # Initialize the optimizer - optimal step size was found through a grid search -opt = qml.GradientDescentOptimizer(stepsize=2.2) +opt = qp.GradientDescentOptimizer(stepsize=2.2) # We spend 2 * 15 circuit evaluations per parameter per step, as there are # 15 Hamiltonian terms @@ -458,7 +458,7 @@ def circuit(param): # executions. num_steps_spsa = 160 -opt = qml.SPSAOptimizer(maxiter=num_steps_spsa, c=0.3, a=1.5) +opt = qp.SPSAOptimizer(maxiter=num_steps_spsa, c=0.3, a=1.5) # We spend 2 * 15 circuit evaluations per step, as there are 15 Hamiltonian terms execs_per_step = 2 * 15 diff --git a/demonstrations_v2/tutorial_spsa/metadata.json b/demonstrations_v2/tutorial_spsa/metadata.json index f30460d51c..728f8dba44 100644 --- a/demonstrations_v2/tutorial_spsa/metadata.json +++ b/demonstrations_v2/tutorial_spsa/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-03-19T00:00:00+00:00", - "dateOfLastModification": "2025-10-15T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_stabilizer_codes/demo.py b/demonstrations_v2/tutorial_stabilizer_codes/demo.py index df4477acb1..0065626129 100644 --- a/demonstrations_v2/tutorial_stabilizer_codes/demo.py +++ b/demonstrations_v2/tutorial_stabilizer_codes/demo.py @@ -67,27 +67,27 @@ """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np def encode(alpha, beta): - qml.StatePrep([alpha, beta], wires=0) - qml.CNOT(wires=[0, 1]) - qml.CNOT(wires=[0, 2]) + qp.StatePrep([alpha, beta], wires=0) + qp.CNOT(wires=[0, 1]) + qp.CNOT(wires=[0, 2]) def encoded_state(alpha, beta): encode(alpha, beta) - return qml.state() + return qp.state() -encode_qnode = qml.QNode(encoded_state, qml.device("default.qubit")) +encode_qnode = qp.QNode(encoded_state, qp.device("default.qubit")) alpha = 1 / np.sqrt(2) beta = 1 / np.sqrt(2) -encode_qnode = qml.QNode(encoded_state, qml.device("default.qubit")) +encode_qnode = qp.QNode(encoded_state, qp.device("default.qubit")) print("|000> component: ", encode_qnode(alpha, beta)[0]) print("|111> component: ", encode_qnode(alpha, beta)[7]) @@ -138,22 +138,22 @@ def encoded_state(alpha, beta): def error_detection(): - qml.CNOT(wires=[0, 3]) - qml.CNOT(wires=[1, 3]) - qml.CNOT(wires=[1, 4]) - qml.CNOT(wires=[2, 4]) + qp.CNOT(wires=[0, 3]) + qp.CNOT(wires=[1, 3]) + qp.CNOT(wires=[1, 4]) + qp.CNOT(wires=[2, 4]) -@qml.set_shots(1) -@qml.qnode(qml.device("default.qubit", wires=5)) # A single sample flags error +@qp.set_shots(1) +@qp.qnode(qp.device("default.qubit", wires=5)) # A single sample flags error def syndrome_measurement(error_wire): encode(alpha, beta) - qml.PauliX(wires=error_wire) # Unwanted Pauli Operator + qp.PauliX(wires=error_wire) # Unwanted Pauli Operator error_detection() - return qml.sample(wires=[3, 4]) + return qp.sample(wires=[3, 4]) print("Syndrome if error on wire 0: ", syndrome_measurement(0)) @@ -190,28 +190,28 @@ def syndrome_measurement(error_wire): # We can use PennyLane's mid-circuit measurement features to implement the full three-qubit repetition code. -@qml.qnode(qml.device("default.qubit", wires=5)) +@qp.qnode(qp.device("default.qubit", wires=5)) def error_correction(error_wire): encode(alpha, beta) - qml.PauliX(wires=error_wire) + qp.PauliX(wires=error_wire) error_detection() # Mid circuit measurements - m3 = qml.measure(3) - m4 = qml.measure(4) + m3 = qp.measure(3) + m4 = qp.measure(4) # Operations conditional on measurements - qml.cond(m3 & ~m4, qml.PauliX)(wires=0) - qml.cond(m3 & m4, qml.PauliX)(wires=1) - qml.cond(~m3 & m4, qml.PauliX)(wires=2) + qp.cond(m3 & ~m4, qp.PauliX)(wires=0) + qp.cond(m3 & m4, qp.PauliX)(wires=1) + qp.cond(~m3 & m4, qp.PauliX)(wires=2) - return qml.density_matrix( + return qp.density_matrix( wires=[0, 1, 2] - ) # qml.state not supported, but density matrices are. + ) # qp.state not supported, but density matrices are. ############################################################################## @@ -220,23 +220,23 @@ def error_correction(error_wire): # With this result, we can verify that the fidelity of the encoded state is the same as the final state after correction # as follows. -dev = qml.device("default.qubit", wires=5) -error_correction_qnode = qml.QNode(error_correction, dev) -encoded_state = qml.math.dm_from_state_vector(encode_qnode(alpha, beta)) +dev = qp.device("default.qubit", wires=5) +error_correction_qnode = qp.QNode(error_correction, dev) +encoded_state = qp.math.dm_from_state_vector(encode_qnode(alpha, beta)) # Compute fidelity of final corrected state with initial encoded state print( "Fidelity when error on wire 0: ", - qml.math.fidelity(encoded_state, error_correction_qnode(0)).round(2), + qp.math.fidelity(encoded_state, error_correction_qnode(0)).round(2), ) print( "Fidelity when error on wire 1: ", - qml.math.fidelity(encoded_state, error_correction_qnode(1)).round(2), + qp.math.fidelity(encoded_state, error_correction_qnode(1)).round(2), ) print( "Fidelity when error on wire 2: ", - qml.math.fidelity(encoded_state, error_correction_qnode(2)).round(2), + qp.math.fidelity(encoded_state, error_correction_qnode(2)).round(2), ) ############################################################################## @@ -385,7 +385,7 @@ def generate_stabilizer_group(gens, num_wires): op = init_op for i, bit in enumerate(bits): if bit: - op = qml.prod(op, gens[i]).simplify() + op = qp.prod(op, gens[i]).simplify() group.append(op) return set(group) @@ -479,7 +479,7 @@ def classify_pauli(operator, logical_ops, generators, n_wires): if operator.simplify() in stabilizer_group: return f"{operator} is a Stabilizer." - if all(qml.is_commuting(operator, g) for g in generators): + if all(qp.is_commuting(operator, g) for g in generators): if operator in logical_ops: return f"{operator} is a Logical Operator." else: @@ -564,25 +564,25 @@ def classify_pauli(operator, logical_ops, generators, n_wires): def five_qubit_encode(alpha, beta): - qml.StatePrep([alpha, beta], wires=4) - qml.Hadamard(wires=0) - qml.S(wires=0) - qml.CZ(wires=[0, 1]) - qml.CZ(wires=[0, 3]) - qml.CY(wires=[0, 4]) - qml.Hadamard(wires=1) - qml.CZ(wires=[1, 2]) - qml.CZ(wires=[1, 3]) - qml.CNOT(wires=[1, 4]) - qml.Hadamard(wires=2) - qml.CZ(wires=[2, 0]) - qml.CZ(wires=[2, 1]) - qml.CNOT(wires=[2, 4]) - qml.Hadamard(wires=3) - qml.S(wires=3) - qml.CZ(wires=[3, 0]) - qml.CZ(wires=[3, 2]) - qml.CY(wires=[3, 4]) + qp.StatePrep([alpha, beta], wires=4) + qp.Hadamard(wires=0) + qp.S(wires=0) + qp.CZ(wires=[0, 1]) + qp.CZ(wires=[0, 3]) + qp.CY(wires=[0, 4]) + qp.Hadamard(wires=1) + qp.CZ(wires=[1, 2]) + qp.CZ(wires=[1, 3]) + qp.CNOT(wires=[1, 4]) + qp.Hadamard(wires=2) + qp.CZ(wires=[2, 0]) + qp.CZ(wires=[2, 1]) + qp.CNOT(wires=[2, 4]) + qp.Hadamard(wires=3) + qp.S(wires=3) + qp.CZ(wires=[3, 0]) + qp.CZ(wires=[3, 2]) + qp.CY(wires=[3, 4]) ############################################################################## @@ -612,13 +612,13 @@ def five_qubit_encode(alpha, beta): def five_qubit_error_detection(): for wire in range(5, 9): - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) for i in range(len(stabilizers)): - qml.ctrl(stabilizers[i], control=[i + 5]) + qp.ctrl(stabilizers[i], control=[i + 5]) for wire in range(5, 9): - qml.Hadamard(wires=wire) + qp.Hadamard(wires=wire) ############################################################################# @@ -627,11 +627,11 @@ def five_qubit_error_detection(): # measures the syndrome, as we did in the three-qubit code. # -dev = qml.device("default.qubit", wires=9) +dev = qp.device("default.qubit", wires=9) -@qml.set_shots(1) -@qml.qnode(dev) +@qp.set_shots(1) +@qp.qnode(dev) def five_qubit_syndromes(alpha, beta, error_op, error_wire): five_qubit_encode(alpha, beta) @@ -639,7 +639,7 @@ def five_qubit_syndromes(alpha, beta, error_op, error_wire): five_qubit_error_detection() - return qml.sample(wires=range(5, 9)) + return qp.sample(wires=range(5, 9)) ############################################################################# @@ -650,7 +650,7 @@ def five_qubit_syndromes(alpha, beta, error_op, error_wire): ops_and_syndromes = [] for wire in (0, 1, 2, 3, 4): - for error_op in (qml.PauliX, qml.PauliY, qml.PauliZ): + for error_op in (qp.PauliX, qp.PauliY, qp.PauliZ): ops_and_syndromes.append( ( error_op, @@ -678,7 +678,7 @@ def five_qubit_syndromes(alpha, beta, error_op, error_wire): # PennyLane's mid-circuit measurement capabilities, which only allows for Boolean operators. # def syndrome_booleans(syndrome, measurements): - syndrome = qml.math.squeeze(syndrome) + syndrome = qp.math.squeeze(syndrome) if syndrome[0] == 0: m = ~measurements[0] else: @@ -697,10 +697,10 @@ def syndrome_booleans(syndrome, measurements): # # Combining all these pieces, we can write the full error correcting code. # -dev = qml.device("default.qubit", wires=9) +dev = qp.device("default.qubit", wires=9) -@qml.qnode(dev) +@qp.qnode(dev) def five_qubit_code(alpha, beta, error_op, error_wire): five_qubit_encode(alpha, beta) @@ -708,17 +708,17 @@ def five_qubit_code(alpha, beta, error_op, error_wire): five_qubit_error_detection() - m5 = qml.measure(5) - m6 = qml.measure(6) - m7 = qml.measure(7) - m8 = qml.measure(8) + m5 = qp.measure(5) + m6 = qp.measure(6) + m7 = qp.measure(7) + m8 = qp.measure(8) measurements = [m5, m6, m7, m8] for op, wire, synd in ops_and_syndromes: - qml.cond(syndrome_booleans(synd, measurements), op)(wires=wire) + qp.cond(syndrome_booleans(synd, measurements), op)(wires=wire) - return qml.density_matrix(wires=[0, 1, 2, 3, 4]) + return qp.density_matrix(wires=[0, 1, 2, 3, 4]) ############################################################################# @@ -728,18 +728,18 @@ def five_qubit_code(alpha, beta, error_op, error_wire): # -@qml.qnode(qml.device("default.qubit", wires=5)) +@qp.qnode(qp.device("default.qubit", wires=5)) def five_qubit_encoded_state(alpha, beta): five_qubit_encode(alpha, beta) - return qml.state() + return qp.state() -encoded_state = qml.math.dm_from_state_vector(five_qubit_encoded_state(alpha, beta)) +encoded_state = qp.math.dm_from_state_vector(five_qubit_encoded_state(alpha, beta)) for wire in range(5): - for error_op in (qml.PauliX, qml.PauliY, qml.PauliZ): + for error_op in (qp.PauliX, qp.PauliY, qp.PauliZ): print( f"Fidelity when error {error_op(wire).name[-1]}{wire}:", - qml.math.fidelity( + qp.math.fidelity( encoded_state, five_qubit_code(alpha, beta, error_op, wire) ).round(2), ) diff --git a/demonstrations_v2/tutorial_stabilizer_codes/metadata.json b/demonstrations_v2/tutorial_stabilizer_codes/metadata.json index 831026aa2a..39d7502672 100644 --- a/demonstrations_v2/tutorial_stabilizer_codes/metadata.json +++ b/demonstrations_v2/tutorial_stabilizer_codes/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-08-19T09:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Algorithms", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_state_preparation/demo.py b/demonstrations_v2/tutorial_state_preparation/demo.py index f91faefdb0..fe22833915 100644 --- a/demonstrations_v2/tutorial_state_preparation/demo.py +++ b/demonstrations_v2/tutorial_state_preparation/demo.py @@ -47,7 +47,7 @@ # # To start, we import PennyLane, NumPy, and PyTorch for the optimization: -import pennylane as qml +import pennylane as qp import numpy as np import torch from torch.autograd import Variable @@ -99,20 +99,20 @@ # a layer of the circuit ansatz def layer(params, j): for i in range(nr_qubits): - qml.RX(params[i, j, 0], wires=i) - qml.RY(params[i, j, 1], wires=i) - qml.RZ(params[i, j, 2], wires=i) + qp.RX(params[i, j, 0], wires=i) + qp.RY(params[i, j, 1], wires=i) + qp.RZ(params[i, j, 2], wires=i) - qml.CNOT(wires=[0, 1]) - qml.CNOT(wires=[0, 2]) - qml.CNOT(wires=[1, 2]) + qp.CNOT(wires=[0, 1]) + qp.CNOT(wires=[0, 2]) + qp.CNOT(wires=[1, 2]) ############################################################################## # Here, we use the ``default.qubit`` device to perform the optimization, but this can be changed to # any other supported device. -dev = qml.device("default.qubit", wires=3) +dev = qp.device("default.qubit", wires=3) ############################################################################## # When defining the QNode, we introduce as input a Hermitian operator @@ -124,7 +124,7 @@ def layer(params, j): # to use the PyTorch interface: -@qml.qnode(dev, interface="torch") +@qp.qnode(dev, interface="torch") def circuit(params, A): # repeatedly apply each layer in the circuit @@ -132,7 +132,7 @@ def circuit(params, A): layer(params, j) # returns the expectation of the input matrix A on the first qubit - return qml.expval(qml.Hermitian(A, wires=0)) + return qp.expval(qp.Hermitian(A, wires=0)) ############################################################################## diff --git a/demonstrations_v2/tutorial_state_preparation/metadata.json b/demonstrations_v2/tutorial_state_preparation/metadata.json index 61dfbdd860..37f7acaa4b 100644 --- a/demonstrations_v2/tutorial_state_preparation/metadata.json +++ b/demonstrations_v2/tutorial_state_preparation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-11T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Devices and Performance" ], diff --git a/demonstrations_v2/tutorial_stochastic_parameter_shift/demo.py b/demonstrations_v2/tutorial_stochastic_parameter_shift/demo.py index 9447e2203b..a0cde0a5e5 100644 --- a/demonstrations_v2/tutorial_stochastic_parameter_shift/demo.py +++ b/demonstrations_v2/tutorial_stochastic_parameter_shift/demo.py @@ -114,24 +114,24 @@ Let's jump into some code and take a look at the parameter-shift rule in action. """ -import pennylane as qml +import pennylane as qp import matplotlib.pyplot as plt from pennylane import numpy as np from scipy.linalg import expm np.random.seed(143) angles = np.linspace(0, 2 * np.pi, 50) -dev = qml.device('default.qubit', wires=2) +dev = qp.device('default.qubit', wires=2) ############################################################################## # We will consider a very simple circuit, containing just a single-qubit # rotation about the x-axis, followed by a measurement along the z-axis. -@qml.qnode(dev) +@qp.qnode(dev) def rotation_circuit(theta): - qml.RX(theta, wires=0) - return qml.expval(qml.PauliZ(0)) + qp.RX(theta, wires=0) + return qp.expval(qp.PauliZ(0)) ############################################################################## @@ -143,7 +143,7 @@ def rotation_circuit(theta): # # .. note:: # -# Check out the :mod:`qml.gradients ` module +# Check out the :mod:`qp.gradients ` module # to explore all quantum gradient transforms provided by PennyLane. def param_shift(theta): @@ -152,13 +152,13 @@ def param_shift(theta): r_minus = rotation_circuit(theta - np.pi / 2) return 0.5 * (r_plus - r_minus) -gradient = qml.grad(rotation_circuit, argnums=0) +gradient = qp.grad(rotation_circuit, argnums=0) expvals = [rotation_circuit(theta) for theta in angles] grad_vals = [gradient(theta) for theta in angles] param_shift_vals = [param_shift(theta) for theta in angles] plt.plot(angles, expvals, 'b', label="Expecation value") -plt.plot(angles, grad_vals, 'r', label="qml.grad function") +plt.plot(angles, grad_vals, 'r', label="qp.grad function") plt.plot(angles, param_shift_vals, 'mx', label="Parameter-shift rule") plt.xlabel("theta") plt.legend() @@ -291,11 +291,11 @@ def Generator(theta1, theta2, theta3): return G # A simple example circuit that contains the cross-resonance gate -@qml.qnode(dev) +@qp.qnode(dev) def crossres_circuit(gate_pars): G = Generator(*gate_pars) - qml.QubitUnitary(expm(-1j * G), wires=[0, 1]) - return qml.expval(qml.PauliZ(0)) + qp.QubitUnitary(expm(-1j * G), wires=[0, 1]) + return qp.expval(qp.PauliZ(0)) # Subcircuit implementing the gates necessary for the # stochastic parameter-shift rule. @@ -304,18 +304,18 @@ def crossres_circuit(gate_pars): def SPSRgates(gate_pars, s, sign): G = Generator(*gate_pars) # step a) - qml.QubitUnitary(expm(1j * (1 - s) * G), wires=[0, 1]) + qp.QubitUnitary(expm(1j * (1 - s) * G), wires=[0, 1]) # step b) - qml.QubitUnitary(expm(1j * sign * np.pi / 4 * X), wires=0) + qp.QubitUnitary(expm(1j * sign * np.pi / 4 * X), wires=0) # step c) - qml.QubitUnitary(expm(1j * s * G), wires=[0,1]) + qp.QubitUnitary(expm(1j * s * G), wires=[0,1]) # Function which can obtain all expectation vals needed # for the stochastic parameter-shift rule -@qml.qnode(dev) +@qp.qnode(dev) def spsr_circuit(gate_pars, s=None, sign=+1): SPSRgates(gate_pars, s, sign) - return qml.expval(qml.PauliZ(0)) + return qp.expval(qp.PauliZ(0)) # Fix the other parameters of the gate theta2, theta3 = -0.15, 1.6 diff --git a/demonstrations_v2/tutorial_stochastic_parameter_shift/metadata.json b/demonstrations_v2/tutorial_stochastic_parameter_shift/metadata.json index e1058082ab..39f6f0c2c4 100644 --- a/demonstrations_v2/tutorial_stochastic_parameter_shift/metadata.json +++ b/demonstrations_v2/tutorial_stochastic_parameter_shift/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-05-25T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_teleportation/demo.py b/demonstrations_v2/tutorial_teleportation/demo.py index 37ed6f2605..a834077b33 100644 --- a/demonstrations_v2/tutorial_teleportation/demo.py +++ b/demonstrations_v2/tutorial_teleportation/demo.py @@ -124,12 +124,12 @@ # We can use the following `quantum function `__ # to do the state preparation step: -import pennylane as qml +import pennylane as qp import numpy as np def state_preparation(state): - qml.StatePrep(state, wires=["S"]) + qp.StatePrep(state, wires=["S"]) ############################################################################## @@ -171,8 +171,8 @@ def state_preparation(state): def entangle_qubits(): - qml.Hadamard(wires="A") - qml.CNOT(wires=["A", "B"]) + qp.Hadamard(wires="A") + qp.CNOT(wires=["A", "B"]) ############################################################################## @@ -230,8 +230,8 @@ def entangle_qubits(): def basis_rotation(): - qml.CNOT(wires=["S", "A"]) - qml.Hadamard(wires="S") + qp.CNOT(wires=["S", "A"]) + qp.Hadamard(wires="S") ############################################################################## @@ -275,16 +275,16 @@ def basis_rotation(): # correction. In this situation, measurements are happening partway through the protocol, # and the results would be used to control the application of future quantum gates. This # is known as mid-circuit measurement, and such mid-circuit measurements are expressed -# in PennyLane using :func:`qml.measure `. Mid-circuit measurement +# in PennyLane using :func:`qp.measure `. Mid-circuit measurement # results can be used to control operations, and this is expressed in PennyLane using -# :func:`qml.cond `. +# :func:`qp.cond `. def measure_and_update(): - m0 = qml.measure("S") - m1 = qml.measure("A") - qml.cond(m1, qml.PauliX)("B") - qml.cond(m0, qml.PauliZ)("B") + m0 = qp.measure("S") + m1 = qp.measure("A") + qp.cond(m1, qp.PauliX)("B") + qp.cond(m0, qp.PauliZ)("B") ############################################################################## @@ -301,7 +301,7 @@ def teleport(state): state = np.array([1 / np.sqrt(2) + 0.3j, 0.4 - 0.5j]) -_ = qml.draw_mpl(teleport, style="pennylane")(state) +_ = qp.draw_mpl(teleport, style="pennylane")(state) ############################################################################## # @@ -316,19 +316,19 @@ def teleport(state): # specify ``level="device"`` when calling ``draw_mpl`` so it # runs the device pre-processing before drawing the circuit. -dev = qml.device("default.qubit", wires=["S", "A", "B"]) +dev = qp.device("default.qubit", wires=["S", "A", "B"]) -@qml.qnode(dev) +@qp.qnode(dev) def teleport(state): state_preparation(state) entangle_qubits() basis_rotation() measure_and_update() - return qml.density_matrix(wires=["B"]) + return qp.density_matrix(wires=["B"]) -_ = qml.draw_mpl(teleport, style="pennylane", level="device")(state) +_ = qp.draw_mpl(teleport, style="pennylane", level="device")(state) ############################################################################## # @@ -355,7 +355,7 @@ def teleport(state): # 1\rangle`. This means that our protocol has changed the state of Bob's qubit # into the one Alice wished to send him, which is truly incredible! # -# We can use :func:`qml.density_matrix ` to trace out +# We can use :func:`qp.density_matrix ` to trace out # and return Bob's subsystem as a density matrix, which is a more general # description of the state of his qubit. We will use this to verify that Alice's # state was successfully teleported to Bob's qubit. @@ -372,7 +372,7 @@ def teleport(state): def teleport_state(state): teleported_density_matrix = teleport(state) - original_density_matrix = qml.math.dm_from_state_vector(state) + original_density_matrix = qp.math.dm_from_state_vector(state) if not np.allclose(teleported_density_matrix, original_density_matrix): raise ValueError( diff --git a/demonstrations_v2/tutorial_teleportation/metadata.json b/demonstrations_v2/tutorial_teleportation/metadata.json index ba9fe90a44..f0f73aa2f6 100644 --- a/demonstrations_v2/tutorial_teleportation/metadata.json +++ b/demonstrations_v2/tutorial_teleportation/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-10-20T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Getting Started", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_tensor_network_basics/demo.py b/demonstrations_v2/tutorial_tensor_network_basics/demo.py index f459bc2e96..78398596b7 100644 --- a/demonstrations_v2/tutorial_tensor_network_basics/demo.py +++ b/demonstrations_v2/tutorial_tensor_network_basics/demo.py @@ -379,9 +379,9 @@ # # As we will explore in the next section, we can use tensor networks to simulate quantum circuits. In particular, the calculation of an expectation value corresponds to the contraction of the tensor network into a single tensor (scalar). In ``Pennylane``, this simulation can be performed using the :class:`~pennylane.devices.default_tensor.DefaultTensor` device, and the method used to find the contraction path can be chosen via the ``contraction_optimizer`` keyword argument. -import pennylane as qml +import pennylane as qp -dev = qml.device("default.tensor", method="tn", contraction_optimizer="auto-hq") +dev = qp.device("default.tensor", method="tn", contraction_optimizer="auto-hq") ############################################################################## # The different types of values accepted for ``contraction_optimizer`` are determined by the ``optimize`` parameter in ``Quimb`` (see `docs `_) as this is the backend behind the :class:`~pennylane.devices.default_tensor.DefaultTensor` device. See our `simulate quantum circuits with tensor networks demo `_ to learn more about the use of this device in ``Pennylane``. diff --git a/demonstrations_v2/tutorial_tensor_network_basics/metadata.json b/demonstrations_v2/tutorial_tensor_network_basics/metadata.json index dafbcb9d77..4177c4fb87 100644 --- a/demonstrations_v2/tutorial_tensor_network_basics/metadata.json +++ b/demonstrations_v2/tutorial_tensor_network_basics/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-01-23T09:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Getting Started", "Quantum Computing", diff --git a/demonstrations_v2/tutorial_testing_symmetry/demo.py b/demonstrations_v2/tutorial_testing_symmetry/demo.py index bc8963d699..b01ec214ae 100644 --- a/demonstrations_v2/tutorial_testing_symmetry/demo.py +++ b/demonstrations_v2/tutorial_testing_symmetry/demo.py @@ -107,37 +107,37 @@ for basis states :math:`\vert x_0 x_1 x_2 x_3\rangle` and extends by linearity. The simplest way to do this is by using -:class:`qml.Permute `. +:class:`qp.Permute `. We can convert this into a matrix by using -:class:`qml.matrix() `. +:class:`qp.matrix() `. We can obtain any other element :math:`g\in G` by simply iterating :math:`c` the appropriate number of times. """ -import pennylane as qml +import pennylane as qp from pennylane import numpy as np # Create wires for the system system = range(4) # The generator of the group -c = qml.Permute([3, 0, 1, 2], wires=system) -c_mat = qml.matrix(c) +c = qp.Permute([3, 0, 1, 2], wires=system) +c_mat = qp.matrix(c) ###################################################################### # To create the Hamiltonians, we use -# :class:`qml.Hamiltonian `: +# :class:`qp.Hamiltonian `: # # Create Hamiltonians -obs = [qml.PauliX(system[0]), qml.PauliX(system[1]), qml.PauliX(system[2]), qml.PauliX(system[3])] +obs = [qp.PauliX(system[0]), qp.PauliX(system[1]), qp.PauliX(system[2]), qp.PauliX(system[3])] coeffs1, coeffs2, coeffs3 = [1, 1, 1, 1], [1, 1.1, 0.9, 1], [1, 2, 3, 0] Hsymm, Hnsym, Hasym = ( - qml.Hamiltonian(coeffs1, obs), - qml.Hamiltonian(coeffs2, obs), - qml.Hamiltonian(coeffs3, obs), + qp.Hamiltonian(coeffs1, obs), + qp.Hamiltonian(coeffs2, obs), + qp.Hamiltonian(coeffs3, obs), ) @@ -203,8 +203,8 @@ # Prepare entangled state on system and copy def prep_entangle(): for wire in system: - qml.Hadamard(wire) - qml.CNOT(wires=[wire, wire + 4]) + qp.Hadamard(wire) + qp.CNOT(wires=[wire, wire + 4]) ###################################################################### @@ -212,17 +212,17 @@ def prep_entangle(): # the system’s evolution could be a “black box” we can query, or something # given to us analytically. In general, we can approximate time evolution # with -# :class:`qml.ApproxTimeEvolution `. +# :class:`qp.ApproxTimeEvolution `. # However, since our Hamiltonians consist of terms that *commute*, we will # be able to evolve exactly using -# :class:`qml.CommutingEvolution `. +# :class:`qp.CommutingEvolution `. # We will reiterate this below. # That's it for part (a)! # Use Choi-Jamiołkowski isomorphism def choi_state(hamiltonian, time): prep_entangle() - qml.CommutingEvolution(hamiltonian, time) + qp.CommutingEvolution(hamiltonian, time) ###################################################################### # Controlled symmetries @@ -286,7 +286,7 @@ def choi_state(hamiltonian, time): # :math:`\vert+\rangle_G` state at the end, we undo these Hadamards and # try to measure “:math:`00`”. Finally, it’s straightforward to implement # the controlled gate :math:`CU` using controlled -# operations (namely :class:`qml.ControlledQubitUnitary`) +# operations (namely :class:`qp.ControlledQubitUnitary`) # on each qubit: # # .. figure:: ../_static/demonstration_assets/testing_symmetry/cu.png @@ -297,30 +297,30 @@ def choi_state(hamiltonian, time): # Create group register and device aux = range(8, 10) -dev = qml.device("lightning.qubit", wires=10) +dev = qp.device("lightning.qubit", wires=10) # Create plus state def prep_plus(): - qml.Hadamard(wires=aux[0]) - qml.Hadamard(wires=aux[1]) + qp.Hadamard(wires=aux[0]) + qp.Hadamard(wires=aux[1]) # Implement controlled symmetry operations on system def CU_sys(): - qml.ControlledQubitUnitary(c_mat @ c_mat, wires=[aux[0]] + list(system)) - qml.ControlledQubitUnitary(c_mat, wires=[aux[1]] + list(system)) + qp.ControlledQubitUnitary(c_mat @ c_mat, wires=[aux[0]] + list(system)) + qp.ControlledQubitUnitary(c_mat, wires=[aux[1]] + list(system)) # Implement controlled symmetry operations on copy def CU_cpy(): - qml.ControlledQubitUnitary(c_mat @ c_mat, wires=[aux[0]] + list(copy)) - qml.ControlledQubitUnitary(c_mat, wires=[aux[1]] + list(copy)) + qp.ControlledQubitUnitary(c_mat @ c_mat, wires=[aux[0]] + list(copy)) + qp.ControlledQubitUnitary(c_mat, wires=[aux[1]] + list(copy)) ###################################################################### # Let’s combine everything and actually run our circuit! # # Circuit for average symmetry -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def avg_symm(hamiltonian, time): # Use Choi-Jamiołkowski isomorphism @@ -334,7 +334,7 @@ def avg_symm(hamiltonian, time): # Ready register for measurement prep_plus() - return qml.probs(wires=aux) + return qp.probs(wires=aux) print("For Hamiltonian Hsymm, the |+> state is observed with probability", avg_symm(Hsymm, 1)[0], ".") diff --git a/demonstrations_v2/tutorial_testing_symmetry/metadata.json b/demonstrations_v2/tutorial_testing_symmetry/metadata.json index 688ed12a2a..f0e3508bc4 100644 --- a/demonstrations_v2/tutorial_testing_symmetry/metadata.json +++ b/demonstrations_v2/tutorial_testing_symmetry/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-01-24T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_tn_circuits/demo.py b/demonstrations_v2/tutorial_tn_circuits/demo.py index 77bad8c5f1..54329612b3 100644 --- a/demonstrations_v2/tutorial_tn_circuits/demo.py +++ b/demonstrations_v2/tutorial_tn_circuits/demo.py @@ -115,14 +115,14 @@ """ import numpy as onp -import pennylane as qml +import pennylane as qp from pennylane import numpy as np def block(weights, wires): - qml.RX(weights[0], wires=wires[0]) - qml.RY(weights[1], wires=wires[1]) - qml.CNOT(wires=wires) + qp.RX(weights[0], wires=wires[0]) + qp.RY(weights[1], wires=wires[1]) + qp.CNOT(wires=wires) ############################################################################## @@ -131,25 +131,25 @@ def block(weights, wires): # shape of an MPS tensor network and computes the expectation value of a Pauli Z # operator on the bottom qubit. -dev = qml.device("default.qubit", wires=4) +dev = qp.device("default.qubit", wires=4) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(template_weights): - qml.MPS( + qp.MPS( wires=range(4), n_block_wires=2, block=block, n_params_block=2, template_weights=template_weights, ) - return qml.expval(qml.PauliZ(wires=3)) + return qp.expval(qp.PauliZ(wires=3)) np.random.seed(1) weights = np.random.random(size=[3, 2]) -qml.drawer.use_style("black_white") -fig, ax = qml.draw_mpl(circuit, level="device")(weights) +qp.drawer.use_style("black_white") +fig, ax = qp.draw_mpl(circuit, level="device")(weights) fig.set_size_inches((6, 3)) ############################################################################## @@ -159,26 +159,26 @@ def circuit(template_weights): def deep_block(weights, wires): - qml.StronglyEntanglingLayers(weights, wires) + qp.StronglyEntanglingLayers(weights, wires) ############################################################################## # We can use the :class:`~pennylane.MPS` template again and simply set # ``n_params_block = 3`` to suit the new block. -dev = qml.device("default.qubit", wires=4) +dev = qp.device("default.qubit", wires=4) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(template_weights): - qml.MPS( + qp.MPS( wires=range(4), n_block_wires=2, block=deep_block, n_params_block=3, template_weights=template_weights, ) - return qml.expval(qml.PauliZ(wires=3)) + return qp.expval(qp.PauliZ(wires=3)) ############################################################################## @@ -193,9 +193,9 @@ def circuit(template_weights): # Both this circuit and the previous circuit # can be represented by an MPS with a bond dimension of two. -shape = qml.StronglyEntanglingLayers.shape(n_layers=2, n_wires=2) +shape = qp.StronglyEntanglingLayers.shape(n_layers=2, n_wires=2) template_weights = [np.random.random(size=shape)] * 3 -fig, ax = qml.draw_mpl(circuit, level="device")(template_weights) +fig, ax = qp.draw_mpl(circuit, level="device")(template_weights) ############################################################################## # In addition to deep blocks, we can easily expand to wider blocks with more @@ -204,7 +204,7 @@ def circuit(template_weights): def wide_block(weights, wires): - qml.SimplifiedTwoDesign(initial_layer_weights=weights[0], weights=weights[1], wires=wires) + qp.SimplifiedTwoDesign(initial_layer_weights=weights[0], weights=weights[1], wires=wires) ############################################################################### @@ -215,25 +215,25 @@ def wide_block(weights, wires): # appear near the beginning of the circuit. Furthermore, this circuit has a higher bond # dimension than the previous ones and would correspond to an MPS with a bond dimension of four. -dev = qml.device("default.qubit", wires=8) +dev = qp.device("default.qubit", wires=8) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(template_weights): - qml.MPS( + qp.MPS( wires=range(8), n_block_wires=4, block=wide_block, n_params_block=2, template_weights=template_weights, ) - return qml.expval(qml.PauliZ(wires=7)) + return qp.expval(qp.PauliZ(wires=7)) -shapes = qml.SimplifiedTwoDesign.shape(n_layers=1, n_wires=4) +shapes = qp.SimplifiedTwoDesign.shape(n_layers=1, n_wires=4) weights = [onp.random.random(size=shape) for shape in shapes] template_weights = onp.array([weights] * 3, dtype="object") -fig, ax = qml.draw_mpl(circuit, level="device")(template_weights) +fig, ax = qp.draw_mpl(circuit, level="device")(template_weights) ############################################################################## # We can also broadcast a block to the tree tensor network architecture by using the @@ -241,28 +241,28 @@ def circuit(template_weights): def block(weights, wires): - qml.RX(weights[0], wires=wires[0]) - qml.RX(weights[1], wires=wires[1]) - qml.CNOT(wires=wires) + qp.RX(weights[0], wires=wires[0]) + qp.RX(weights[1], wires=wires[1]) + qp.CNOT(wires=wires) -dev = qml.device("default.qubit", wires=8) +dev = qp.device("default.qubit", wires=8) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(template_weights): - qml.TTN( + qp.TTN( wires=range(8), n_block_wires=2, block=block, n_params_block=2, template_weights=template_weights, ) - return qml.expval(qml.PauliZ(wires=7)) + return qp.expval(qp.PauliZ(wires=7)) weights = np.random.random(size=[7, 2]) -fig, ax = qml.draw_mpl(circuit, level="device")(weights) +fig, ax = qp.draw_mpl(circuit, level="device")(weights) fig.set_size_inches((4, 4)) ############################################################################## # Classifying the bars and stripes data set @@ -309,9 +309,9 @@ def circuit(template_weights): def block(weights, wires): - qml.RY(weights[0], wires=wires[0]) - qml.RY(weights[1], wires=wires[1]) - qml.CNOT(wires=wires) + qp.RY(weights[0], wires=wires[0]) + qp.RY(weights[1], wires=wires[1]) + qp.CNOT(wires=wires) ############################################################################## @@ -323,24 +323,24 @@ def block(weights, wires): # The circuit diagram below shows the full circuit. The :class:`~pennylane.BasisState` # encoding appears in the initial :class:`~pennylane.PauliX` gates. -dev = qml.device("default.qubit", wires=4) +dev = qp.device("default.qubit", wires=4) -@qml.qnode(dev) +@qp.qnode(dev) def circuit(image, template_weights): - qml.BasisState(image, wires=range(4)) - qml.TTN( + qp.BasisState(image, wires=range(4)) + qp.TTN( wires=range(4), n_block_wires=2, block=block, n_params_block=2, template_weights=template_weights, ) - return qml.expval(qml.PauliZ(wires=3)) + return qp.expval(qp.PauliZ(wires=3)) weights = np.random.random(size=[3, 2]) -fig, ax = qml.draw_mpl(circuit, level="device")(BAS[0], weights) +fig, ax = qp.draw_mpl(circuit, level="device")(BAS[0], weights) fig.set_size_inches((6, 3.5)) ############################################################################## @@ -368,7 +368,7 @@ def costfunc(params): # the cost function. params = np.random.random(size=[3, 2], requires_grad=True) -optimizer = qml.GradientDescentOptimizer(stepsize=0.1) +optimizer = qp.GradientDescentOptimizer(stepsize=0.1) for k in range(100): if k % 20 == 0: @@ -380,7 +380,7 @@ def costfunc(params): # we can now show the full circuits and the resulting output for each image. for image in BAS: - fig, ax = qml.draw_mpl(circuit, level="device")(image, params) + fig, ax = qp.draw_mpl(circuit, level="device")(image, params) plt.figure(figsize=[1.8, 1.8]) plt.imshow(np.reshape(image, [2, 2]), cmap="gray") plt.title( diff --git a/demonstrations_v2/tutorial_tn_circuits/metadata.json b/demonstrations_v2/tutorial_tn_circuits/metadata.json index bfb7e23fd6..9a51a681b8 100644 --- a/demonstrations_v2/tutorial_tn_circuits/metadata.json +++ b/demonstrations_v2/tutorial_tn_circuits/metadata.json @@ -17,7 +17,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-03-29T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_toric_code/demo.py b/demonstrations_v2/tutorial_toric_code/demo.py index d338c4d8d2..debb31352e 100644 --- a/demonstrations_v2/tutorial_toric_code/demo.py +++ b/demonstrations_v2/tutorial_toric_code/demo.py @@ -112,7 +112,7 @@ On to some practical coding! First, let's define the sites on a :math:`4\times 6` lattice. """ -import pennylane as qml +import pennylane as qp import matplotlib.pyplot as plt from matplotlib.patches import Polygon, Patch from itertools import product @@ -170,7 +170,7 @@ class Wire: sites = [(x0, y), (x0 + 1, y), (x0 + 1, y + 1), (x0, y + 1)] - op = qml.prod(*(qml.PauliZ(mod(s)) for s in sites)) + op = qp.prod(*(qp.PauliZ(mod(s)) for s in sites)) zgroup_sites.append(sites) zgroup_ops.append(op) @@ -196,7 +196,7 @@ class Wire: if x == 2 and y == 1: # change order for state prep later sites = sites[1:] + sites[0:1] - op = qml.prod(*(qml.PauliX(mod(s)) for s in sites)) + op = qp.prod(*(qp.PauliX(mod(s)) for s in sites)) xgroup_sites.append(sites) xgroup_ops.append(op) @@ -306,18 +306,18 @@ def misc_plot_formatting(fig, ax): # Now let’s actually put these together into a circuit! # -dev = qml.device("lightning.qubit", wires=[Wire(*s) for s in all_sites]) +dev = qp.device("lightning.qubit", wires=[Wire(*s) for s in all_sites]) def state_prep(): for op in xgroup_ops[0:-1]: - qml.Hadamard(op.wires[0]) + qp.Hadamard(op.wires[0]) for w in op.wires[1:]: - qml.CNOT(wires=[op.wires[0], w]) + qp.CNOT(wires=[op.wires[0], w]) -@qml.qnode(dev, diff_method=None) +@qp.qnode(dev, diff_method=None) def circuit(): state_prep() - return [qml.expval(op) for op in xgroup_ops + zgroup_ops] + return [qp.expval(op) for op in xgroup_ops + zgroup_ops] ###################################################################### @@ -413,17 +413,17 @@ def circuit(): # Let’s create a QNode where we can apply these perturbations: -@qml.qnode(dev, diff_method=None) +@qp.qnode(dev, diff_method=None) def excitations(x_sites, z_sites): state_prep() for s in x_sites: - qml.PauliX(Wire(*s)) + qp.PauliX(Wire(*s)) for s in z_sites: - qml.PauliZ(Wire(*s)) + qp.PauliZ(Wire(*s)) - return [qml.expval(op) for op in xgroup_ops + zgroup_ops] + return [qp.expval(op) for op in xgroup_ops + zgroup_ops] ###################################################################### @@ -686,17 +686,17 @@ def excitation_plot(x_excite, z_excite): # -@qml.qnode(dev, diff_method=None) +@qp.qnode(dev, diff_method=None) def probs(x_sites, z_sites): state_prep() for s in x_sites: - qml.PauliX(Wire(*s)) + qp.PauliX(Wire(*s)) for s in z_sites: - qml.PauliZ(Wire(*s)) + qp.PauliZ(Wire(*s)) - return qml.probs(wires=[Wire(*s) for s in all_sites]) + return qp.probs(wires=[Wire(*s) for s in all_sites]) null_probs = probs([], []) @@ -772,7 +772,7 @@ def probs(x_sites, z_sites): # if the probability distributions are different: # -print("Are the probabilities equal? ", qml.math.allclose(null_probs, horizontal_probs)) +print("Are the probabilities equal? ", qp.math.allclose(null_probs, horizontal_probs)) print("Is this significant?") print("Maximum difference in probabilities: ", max(abs(null_probs - horizontal_probs))) print("Maximum probability: ", max(null_probs)) @@ -918,28 +918,28 @@ def probs(x_sites, z_sites): # Below we implement this algorithm in PennyLane and measure the mutual exchange statistics # of an X Group excitation and a Z Group excitation. -dev_aux = qml.device("lightning.qubit", wires=[Wire(*s) for s in all_sites] + ["aux"]) +dev_aux = qp.device("lightning.qubit", wires=[Wire(*s) for s in all_sites] + ["aux"]) def loop(x_loop, z_loop): for s in x_loop: - qml.PauliX(Wire(*s)) + qp.PauliX(Wire(*s)) for s in z_loop: - qml.PauliZ(Wire(*s)) + qp.PauliZ(Wire(*s)) -@qml.qnode(dev_aux, diff_method=None) +@qp.qnode(dev_aux, diff_method=None) def hadamard_test(x_prep, z_prep, x_loop, z_loop): state_prep() for s in x_prep: - qml.PauliX(Wire(*s)) + qp.PauliX(Wire(*s)) for s in z_prep: - qml.PauliZ(Wire(*s)) + qp.PauliZ(Wire(*s)) - qml.Hadamard("aux") - qml.ctrl(loop, control="aux")(x_loop, z_loop) - qml.Hadamard("aux") - return qml.expval(qml.PauliZ("aux")) + qp.Hadamard("aux") + qp.ctrl(loop, control="aux")(x_loop, z_loop) + qp.Hadamard("aux") + return qp.expval(qp.PauliZ("aux")) x_around_z = hadamard_test(prep1, prep2, [], loop1) print("Move x excitation around z excitation: ", x_around_z) diff --git a/demonstrations_v2/tutorial_toric_code/metadata.json b/demonstrations_v2/tutorial_toric_code/metadata.json index 96780d5ac6..37c0ff4eb4 100644 --- a/demonstrations_v2/tutorial_toric_code/metadata.json +++ b/demonstrations_v2/tutorial_toric_code/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2022-08-08T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Algorithms", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_trapped_ions/demo.py b/demonstrations_v2/tutorial_trapped_ions/demo.py index 33b7cff188..0cc31b3739 100644 --- a/demonstrations_v2/tutorial_trapped_ions/demo.py +++ b/demonstrations_v2/tutorial_trapped_ions/demo.py @@ -397,7 +397,7 @@ # :math:`\exp(-i \hat{H} t/\hbar)` as a function of :math:`\varphi` and the # duration :math:`t` of the pulse, with :math:`\Omega` set to 100 kHz. -import pennylane as qml +import pennylane as qp import numpy as np from scipy.linalg import expm @@ -416,36 +416,36 @@ def evolution(phi, t): # produce common gates. For example, there is a combination of pulses # with different phases and durations that yield the Hadamard gate: -dev = qml.device("default.qubit", wires=1) +dev = qp.device("default.qubit", wires=1) -@qml.qnode(dev) +@qp.qnode(dev) def ion_hadamard(state): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) """We use a series of seemingly arbitrary pulses that will give the Hadamard gate. Why this is the case will become clear later""" - qml.QubitUnitary(evolution(0, -np.pi / 2 / Omega), wires=0) - qml.QubitUnitary(evolution(np.pi / 2, np.pi / 2 / Omega), wires=0) - qml.QubitUnitary(evolution(0, np.pi / 2 / Omega), wires=0) - qml.QubitUnitary(evolution(np.pi / 2, np.pi / 2 / Omega), wires=0) - qml.QubitUnitary(evolution(0, np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(0, -np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(np.pi / 2, np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(0, np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(np.pi / 2, np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(0, np.pi / 2 / Omega), wires=0) - return qml.state() + return qp.state() #For comparison, we use the Hadamard built into PennyLane -@qml.qnode(dev) +@qp.qnode(dev) def hadamard(state): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) - qml.Hadamard(wires=0) + qp.Hadamard(wires=0) - return qml.state() + return qp.state() #We confirm that the values given by both functions are the same up to numerical error print(np.isclose(1j * ion_hadamard(0), hadamard(0))) @@ -456,28 +456,28 @@ def hadamard(state): # A similar exercise can be done for the :math:`T` gate: -@qml.qnode(dev) +@qp.qnode(dev) def ion_Tgate(state): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) - qml.QubitUnitary(evolution(0, -np.pi / 2 / Omega), wires=0) - qml.QubitUnitary(evolution(np.pi / 2, np.pi / 4 / Omega), wires=0) - qml.QubitUnitary(evolution(0, np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(0, -np.pi / 2 / Omega), wires=0) + qp.QubitUnitary(evolution(np.pi / 2, np.pi / 4 / Omega), wires=0) + qp.QubitUnitary(evolution(0, np.pi / 2 / Omega), wires=0) - return qml.state() + return qp.state() -@qml.qnode(dev) +@qp.qnode(dev) def tgate(state): if state == 1: - qml.PauliX(wires=0) + qp.PauliX(wires=0) - qml.T(wires=0) + qp.T(wires=0) - return qml.state() + return qp.state() print(np.isclose(np.exp(1j * np.pi / 8) * ion_Tgate(0), tgate(0))) @@ -501,12 +501,12 @@ def tgate(state): import matplotlib.pyplot as plt -@qml.qnode(dev) +@qp.qnode(dev) def evolution_prob(t): - qml.QubitUnitary(evolution(0, t / Omega), wires=0) + qp.QubitUnitary(evolution(0, t / Omega), wires=0) - return qml.probs(wires=0) + return qp.probs(wires=0) t = np.linspace(0, 4 * np.pi, 101) @@ -806,32 +806,32 @@ def Molmer_Sorensen(t): # time :math:`t/\Omega_{MS}.` Let us verify that this is indeed the case # by building the circuit in PennyLane: -dev2 = qml.device("default.qubit",wires=2) +dev2 = qp.device("default.qubit",wires=2) -@qml.qnode(dev2) +@qp.qnode(dev2) def ion_cnot(basis_state): #Prepare the two-qubit basis states from the input - qml.BasisState(basis_state, wires=range(2)) + qp.BasisState(basis_state, wires=range(2)) #Implements the circuit shown above - qml.RY(np.pi/2, wires=0) - qml.QubitUnitary(Molmer_Sorensen(np.pi/2/Omega),wires=[0,1]) - qml.RX(-np.pi/2, wires=0) - qml.RX(-np.pi/2, wires=1) - qml.RY(-np.pi/2, wires=0) + qp.RY(np.pi/2, wires=0) + qp.QubitUnitary(Molmer_Sorensen(np.pi/2/Omega),wires=[0,1]) + qp.RX(-np.pi/2, wires=0) + qp.RX(-np.pi/2, wires=1) + qp.RY(-np.pi/2, wires=0) - return qml.state() + return qp.state() #Compare with built-in CNOT -@qml.qnode(dev2) +@qp.qnode(dev2) def cnot_gate(basis_state): - qml.BasisState(basis_state, wires=range(2)) + qp.BasisState(basis_state, wires=range(2)) - qml.CNOT(wires=[0,1]) + qp.CNOT(wires=[0,1]) - return qml.state() + return qp.state() #Check that they are the same up to numerical error and global phase print(np.isclose(np.exp(-1j*np.pi/4)*ion_cnot([0,0]),cnot_gate([0,0]))) diff --git a/demonstrations_v2/tutorial_trapped_ions/metadata.json b/demonstrations_v2/tutorial_trapped_ions/metadata.json index 14c4a77a2b..d9d5fe61f6 100644 --- a/demonstrations_v2/tutorial_trapped_ions/metadata.json +++ b/demonstrations_v2/tutorial_trapped_ions/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-11-10T00:00:00+00:00", - "dateOfLastModification": "2025-12-19T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Hardware", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_unitary_designs/demo.py b/demonstrations_v2/tutorial_unitary_designs/demo.py index 83180842e4..30ffe0c9da 100644 --- a/demonstrations_v2/tutorial_unitary_designs/demo.py +++ b/demonstrations_v2/tutorial_unitary_designs/demo.py @@ -431,7 +431,7 @@ def f(x, y, z): # operation first with experiments using a large but finite amount of Haar-random # unitaries, and then again with only the Clifford group. -import pennylane as qml +import pennylane as qp # Scipy allows us to sample Haar-random unitaries directly from scipy.stats import unitary_group @@ -440,7 +440,7 @@ def f(x, y, z): np.random.seed(42) # Use the mixed state simulator -dev = qml.device("default.mixed", wires=1) +dev = qp.device("default.mixed", wires=1) ###################################################################### # Let's set up a noisy quantum channel. To keep things simple, assume it @@ -449,8 +449,8 @@ def f(x, y, z): # quantum function for our ideal experiment: def ideal_experiment(): - qml.SX(wires=0) - return qml.state() + qp.SX(wires=0) + return qp.state() ###################################################################### # Next, we apply some noise. We do so by making use of a relatively new feature @@ -459,9 +459,9 @@ def ideal_experiment(): # operations. Suppose the noisy channel is composed of the following: def noisy_operations(damp_factor, depo_factor, flip_prob): - qml.AmplitudeDamping(damp_factor, wires=0) - qml.DepolarizingChannel(depo_factor, wires=0) - qml.BitFlip(flip_prob, wires=0) + qp.AmplitudeDamping(damp_factor, wires=0) + qp.DepolarizingChannel(depo_factor, wires=0) + qp.BitFlip(flip_prob, wires=0) ###################################################################### @@ -469,10 +469,10 @@ def noisy_operations(damp_factor, depo_factor, flip_prob): # *after* the original operations, but before the measurements. We use the # convenient :func:`~.pennylane.transform` decorator: -@qml.transform +@qp.transform def apply_noise(tape, damp_factor, depo_factor, flip_prob): # Capture the operations from the noisy sequence - noisy_tape = qml.tape.make_qscript(noisy_operations)(damp_factor, depo_factor, flip_prob) + noisy_tape = qp.tape.make_qscript(noisy_operations)(damp_factor, depo_factor, flip_prob) # Apply the original operations, then the noisy ones noisy_ops = tape.operations + noisy_tape.operations @@ -499,12 +499,12 @@ def null_postprocessing_fn(results): # before all the operations, and its inverse right before the measurements. We # can write another transform here to streamline this process: -@qml.transform +@qp.transform def conjugate_with_unitary(tape, matrix): new_ops = [ - qml.QubitUnitary(matrix, wires=0), + qp.QubitUnitary(matrix, wires=0), *tape.operations, - qml.QubitUnitary(matrix.conj().T, wires=0), + qp.QubitUnitary(matrix.conj().T, wires=0), ] def null_postprocessing_fn(results): @@ -541,8 +541,8 @@ def fidelity(rho, sigma): conjugated_noisy_experiment = conjugate_with_unitary(noisy_experiment, U) # Use the functions to create QNodes - ideal_qnode = qml.QNode(conjugated_ideal_experiment, dev) - noisy_qnode = qml.QNode(conjugated_noisy_experiment, dev) + ideal_qnode = qp.QNode(conjugated_ideal_experiment, dev) + noisy_qnode = qp.QNode(conjugated_noisy_experiment, dev) # Execute the QNodes ideal_state = ideal_qnode() @@ -562,19 +562,19 @@ def fidelity(rho, sigma): def apply_single_clifford(clifford_string, inverse=False): for gate in clifford_string: if gate == 'H': - qml.Hadamard(wires=0) + qp.Hadamard(wires=0) else: sign = -1 if inverse else 1 - qml.PhaseShift(sign * np.pi/2, wires=0) + qp.PhaseShift(sign * np.pi/2, wires=0) ###################################################################### # Next, we write a transform that applies a Clifford in the context of the full # experiment, i.e., apply the Clifford, then the operations, followed by the # inverse of the Clifford. -@qml.transform +@qp.transform def conjugate_with_clifford(tape, clifford_string): - make_single_clifford = qml.tape.make_qscript(apply_single_clifford) + make_single_clifford = qp.tape.make_qscript(apply_single_clifford) non_inv_tape = make_single_clifford(clifford_string, inverse=False) inv_tape = make_single_clifford(clifford_string, inverse=True) @@ -598,8 +598,8 @@ def null_postprocessing_fn(results): conjugated_ideal_experiment = conjugate_with_clifford(ideal_experiment, C) conjugated_noisy_experiment = conjugate_with_clifford(noisy_experiment, C) - ideal_qnode = qml.QNode(conjugated_ideal_experiment, dev) - noisy_qnode = qml.QNode(conjugated_noisy_experiment, dev) + ideal_qnode = qp.QNode(conjugated_ideal_experiment, dev) + noisy_qnode = qp.QNode(conjugated_noisy_experiment, dev) ideal_state = ideal_qnode() noisy_state = noisy_qnode() diff --git a/demonstrations_v2/tutorial_unitary_designs/metadata.json b/demonstrations_v2/tutorial_unitary_designs/metadata.json index f0e508788b..34c4e2b8ef 100644 --- a/demonstrations_v2/tutorial_unitary_designs/metadata.json +++ b/demonstrations_v2/tutorial_unitary_designs/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2021-09-07T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_unitary_synthesis_kak/demo.py b/demonstrations_v2/tutorial_unitary_synthesis_kak/demo.py index 2b7feefec6..5f24a52c0b 100644 --- a/demonstrations_v2/tutorial_unitary_synthesis_kak/demo.py +++ b/demonstrations_v2/tutorial_unitary_synthesis_kak/demo.py @@ -193,10 +193,10 @@ We may check that this works with the following code. We apply ``cossin`` to some input ``U``, from which we create the block matrices :math:`K_1` and :math:`K_2` with ``numpy`` and the Cartan subgroup matrix :math:`A` via a Select-applied, -or multiplexed, ``qml.RY`` rotation. Then we check that those matrices multiplied together +or multiplexed, ``qp.RY`` rotation. Then we check that those matrices multiplied together yield the input ``U`` again. """ -import pennylane as qml +import pennylane as qp import numpy as np import matplotlib.pyplot as plt from scipy.linalg import cossin, eig, qr @@ -220,8 +220,8 @@ def aiii_decomposition(U): # Check that the decomposition is valid zero = np.zeros_like(u_1) K_1 = np.block([[u_1, zero], [zero, u_2]]) -ry_ops = [qml.RY(2 * th, 0) for th in theta] -A = qml.matrix(qml.Select(ry_ops, control=range(1, n)), wire_order=range(n)) +ry_ops = [qp.RY(2 * th, 0) for th in theta] +A = qp.matrix(qp.Select(ry_ops, control=range(1, n)), wire_order=range(n)) K_2 = np.block([[v_1, zero], [zero, v_2]]) reconstructed_U = K_1 @ A @ K_2 @@ -249,8 +249,8 @@ def aiii_decomposition_rotated(U): zero = np.zeros_like(u_1) K_1 = np.block([[u_1, zero], [zero, u_2]]) K_2 = np.block([[v_1, zero], [zero, v_2]]) - rotation = (qml.X(0) + qml.Y(0)) / np.sqrt(2) - rotation_mat = qml.matrix(rotation, wire_order=range(n)) + rotation = (qp.X(0) + qp.Y(0)) / np.sqrt(2) + rotation_mat = qp.matrix(rotation, wire_order=range(n)) # Transform K_1 and K_2. No need to transform theta, just re-interpret as RX angles K_1 = K_1 @ rotation_mat K_2 = rotation_mat @ K_2 @@ -273,8 +273,8 @@ def aiii_decomposition_rotated(U): # The decomposition is still valid: -rx_ops = [qml.RX(2 * th, 0) for th in theta] -new_A = qml.matrix(qml.Select(rx_ops, control=range(1, n)), wire_order=range(n)) +rx_ops = [qp.RX(2 * th, 0) for th in theta] +new_A = qp.matrix(qp.Select(rx_ops, control=range(1, n)), wire_order=range(n)) reconstructed_U = new_K_1 @ new_A @ new_K_2 print(np.allclose(reconstructed_U, U)) @@ -379,8 +379,8 @@ def demultiplex(U, V): # The demultiplexed matrices make up :math:`K_1=u_1\oplus u_2` from above: # -rz_ops = [qml.RZ(-2 * p, 0) for p in phi] -demultiplex_A = qml.matrix(qml.Select(rz_ops, control=range(1, n)), wire_order=range(n)) +rz_ops = [qp.RZ(-2 * p, 0) for p in phi] +demultiplex_A = qp.matrix(qp.Select(rz_ops, control=range(1, n)), wire_order=range(n)) demultiplex_K_1 = np.block([[U_1, zero], [zero, U_1]]) demultiplex_K_2 = np.block([[U_2, zero], [zero, U_2]]) reconstructed_K_1 = demultiplex_K_1 @ demultiplex_A @ demultiplex_K_2 diff --git a/demonstrations_v2/tutorial_unitary_synthesis_kak/metadata.json b/demonstrations_v2/tutorial_unitary_synthesis_kak/metadata.json index 577c5dc4e5..eb95f5e2e0 100644 --- a/demonstrations_v2/tutorial_unitary_synthesis_kak/metadata.json +++ b/demonstrations_v2/tutorial_unitary_synthesis_kak/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2025-05-30T09:00:00+00:00", - "dateOfLastModification": "2025-12-10T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Compilation", "Quantum Computing" diff --git a/demonstrations_v2/tutorial_univariate_qvr/demo.py b/demonstrations_v2/tutorial_univariate_qvr/demo.py index cb4a682061..a794d4e11c 100644 --- a/demonstrations_v2/tutorial_univariate_qvr/demo.py +++ b/demonstrations_v2/tutorial_univariate_qvr/demo.py @@ -434,7 +434,7 @@ def get_training_cycler(Xtr: torch.Tensor, batch_size: int, seed: int = GLOBAL_S # appendix of [#Cîrstoiu2020]_), we create the electron: # -import pennylane as qml +import pennylane as qp from itertools import combinations @@ -451,18 +451,18 @@ def D(gamma: torch.Tensor, n_qubits: int, k: int = None, get_probs: bool = False for i in range(1, k + 1): for comb in combinations(range(n_qubits), i): if len(comb) == 1: - qml.RZ(gamma[cnt], wires=[comb[0]]) + qp.RZ(gamma[cnt], wires=[comb[0]]) cnt += 1 elif len(comb) > 1: cnots = [comb[i : i + 2] for i in range(len(comb) - 1)] for j in cnots: - qml.CNOT(wires=j) - qml.RZ(gamma[cnt], wires=[comb[-1]]) + qp.CNOT(wires=j) + qp.RZ(gamma[cnt], wires=[comb[-1]]) cnt += 1 for j in cnots[::-1]: - qml.CNOT(wires=j) + qp.CNOT(wires=j) if get_probs: - return qml.probs(wires=range(n_qubits)) + return qp.probs(wires=range(n_qubits)) ###################################################################### @@ -470,9 +470,9 @@ def D(gamma: torch.Tensor, n_qubits: int, k: int = None, get_probs: bool = False # qubit in this tutorial, the resulting circuit is merely a single :math:`R_z(\theta)` gate. n_qubits = 1 -dev = qml.device("default.qubit", wires=n_qubits) -D_one_qubit = qml.qnode(dev)(D) -_ = qml.draw_mpl(D_one_qubit, decimals=2)(torch.tensor([1, 0]), 1, 1, True) +dev = qp.device("default.qubit", wires=n_qubits) +D_one_qubit = qp.qnode(dev)(D) +_ = qp.draw_mpl(D_one_qubit, decimals=2)(torch.tensor([1, 0]), 1, 1, True) ###################################################################### # You may find the general function for :math:`D`` useful in case you want to experiment @@ -486,7 +486,7 @@ def D(gamma: torch.Tensor, n_qubits: int, k: int = None, get_probs: bool = False @ct.electron -@qml.qnode(dev, interface="torch", diff_method="backprop") +@qp.qnode(dev, interface="torch", diff_method="backprop") def get_probs( xt: torch.Tensor, t: float, @@ -505,8 +505,8 @@ def get_probs( U(xt, wires=range(n_qubits)) W(alpha, wires=range(n_qubits)) D(gamma * t, n_qubits, k) - qml.adjoint(W)(alpha, wires=range(n_qubits)) - return qml.probs(range(n_qubits)) + qp.adjoint(W)(alpha, wires=range(n_qubits)) + return qp.probs(range(n_qubits)) ###################################################################### @@ -776,8 +776,8 @@ def training_workflow( # general_options = { - "U": qml.AngleEmbedding, - "W": qml.StronglyEntanglingLayers, + "U": qp.AngleEmbedding, + "W": qp.StronglyEntanglingLayers, "D": D, "n_qubits": 1, "probs_func": get_probs, diff --git a/demonstrations_v2/tutorial_univariate_qvr/metadata.json b/demonstrations_v2/tutorial_univariate_qvr/metadata.json index c35abd766a..0abe4181ee 100644 --- a/demonstrations_v2/tutorial_univariate_qvr/metadata.json +++ b/demonstrations_v2/tutorial_univariate_qvr/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2023-02-07T00:00:00+00:00", - "dateOfLastModification": "2025-11-28T00:00:00+00:00", + "dateOfLastModification": "2026-04-17T00:00:00+00:00", "categories": [ "Quantum Machine Learning" ], diff --git a/demonstrations_v2/tutorial_variational_classifier/demo.py b/demonstrations_v2/tutorial_variational_classifier/demo.py index 4e1198574f..53aa324da5 100644 --- a/demonstrations_v2/tutorial_variational_classifier/demo.py +++ b/demonstrations_v2/tutorial_variational_classifier/demo.py @@ -53,7 +53,7 @@ # We start by importing PennyLane, the PennyLane-provided version of NumPy, # and an optimizer. -import pennylane as qml +import pennylane as qp from pennylane import numpy as np from pennylane.optimize import NesterovMomentumOptimizer @@ -63,7 +63,7 @@ # # We then create a quantum device that will run our circuits. -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") ############################################################################## # Variational classifiers usually define a “layer” or “block”, which is an @@ -78,10 +78,10 @@ def layer(layer_weights): for wire in range(4): - qml.Rot(*layer_weights[wire], wires=wire) + qp.Rot(*layer_weights[wire], wires=wire) for wires in ([0, 1], [1, 2], [2, 3], [3, 0]): - qml.CNOT(wires) + qp.CNOT(wires) ############################################################################## @@ -99,7 +99,7 @@ def layer(layer_weights): def state_preparation(x): - qml.BasisState(x, wires=[0, 1, 2, 3]) + qp.BasisState(x, wires=[0, 1, 2, 3]) ############################################################################## @@ -107,14 +107,14 @@ def state_preparation(x): # by a repetition of the layer structure. -@qml.qnode(dev) +@qp.qnode(dev) def circuit(weights, x): state_preparation(x) for layer_weights in weights: layer(layer_weights) - return qml.expval(qml.PauliZ(0)) + return qp.expval(qp.PauliZ(0)) ############################################################################## @@ -136,8 +136,8 @@ def variational_classifier(weights, bias, x): def square_loss(labels, predictions): - # We use a call to qml.math.stack to allow subtracting the arrays directly - return np.mean((labels - qml.math.stack(predictions)) ** 2) + # We use a call to qp.math.stack to allow subtracting the arrays directly + return np.mean((labels - qp.math.stack(predictions)) ** 2) ############################################################################## @@ -301,19 +301,19 @@ def get_angles(x): def state_preparation(a): - qml.RY(a[0], wires=0) + qp.RY(a[0], wires=0) - qml.CNOT(wires=[0, 1]) - qml.RY(a[1], wires=1) - qml.CNOT(wires=[0, 1]) - qml.RY(a[2], wires=1) + qp.CNOT(wires=[0, 1]) + qp.RY(a[1], wires=1) + qp.CNOT(wires=[0, 1]) + qp.RY(a[2], wires=1) - qml.PauliX(wires=0) - qml.CNOT(wires=[0, 1]) - qml.RY(a[3], wires=1) - qml.CNOT(wires=[0, 1]) - qml.RY(a[4], wires=1) - qml.PauliX(wires=0) + qp.PauliX(wires=0) + qp.CNOT(wires=[0, 1]) + qp.RY(a[3], wires=1) + qp.CNOT(wires=[0, 1]) + qp.RY(a[4], wires=1) + qp.PauliX(wires=0) ############################################################################## @@ -323,11 +323,11 @@ def state_preparation(a): ang = get_angles(x) -@qml.qnode(dev) +@qp.qnode(dev) def test(angles): state_preparation(angles) - return qml.state() + return qp.state() state = test(ang) @@ -344,7 +344,7 @@ def test(angles): # # The ``default.qubit`` simulator provides a shortcut to # ``state_preparation`` with the command -# ``qml.StatePrep(x, wires=[0, 1])``. On state simulators, this just +# ``qp.StatePrep(x, wires=[0, 1])``. On state simulators, this just # replaces the quantum state with our (normalized) input. On hardware, the operation implements # more sophisticated versions of the routine used above. @@ -358,8 +358,8 @@ def test(angles): def layer(layer_weights): for wire in range(2): - qml.Rot(*layer_weights[wire], wires=wire) - qml.CNOT(wires=[0, 1]) + qp.Rot(*layer_weights[wire], wires=wire) + qp.CNOT(wires=[0, 1]) def cost(weights, bias, X, Y): diff --git a/demonstrations_v2/tutorial_variational_classifier/metadata.json b/demonstrations_v2/tutorial_variational_classifier/metadata.json index 94296eb863..bb5d75ea99 100644 --- a/demonstrations_v2/tutorial_variational_classifier/metadata.json +++ b/demonstrations_v2/tutorial_variational_classifier/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2019-10-11T00:00:00+00:00", - "dateOfLastModification": "2025-10-03T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Machine Learning", "Getting Started" diff --git a/demonstrations_v2/tutorial_vqe/demo.py b/demonstrations_v2/tutorial_vqe/demo.py index 65785f0561..98ebe87707 100644 --- a/demonstrations_v2/tutorial_vqe/demo.py +++ b/demonstrations_v2/tutorial_vqe/demo.py @@ -52,9 +52,9 @@ jax.config.update("jax_platform_name", "cpu") jax.config.update('jax_enable_x64', True) -import pennylane as qml +import pennylane as qp -dataset = qml.data.load('qchem', molname="H2")[0] +dataset = qp.data.load('qchem', molname="H2")[0] H, qubits = dataset.hamiltonian, len(dataset.hamiltonian.wires) print("Number of qubits = ", qubits) print("The Hamiltonian is ", H) @@ -85,8 +85,8 @@ # # symbols = ["H", "H"] # coordinates = np.array([[-0.70108983, 0.0, 0.0], [0.70108983, 0.0, 0.0]]) -# molecule = qml.qchem.Molecule(symbols, coordinates) -# H, qubits = qml.qchem.molecular_hamiltonian(molecule) +# molecule = qp.qchem.Molecule(symbols, coordinates) +# H, qubits = qp.qchem.molecular_hamiltonian(molecule) # # Implementing the VQE algorithm # ------------------------------ @@ -94,7 +94,7 @@ # algorithms and optimizers. We begin by defining the device, in this case PennyLane’s # standard qubit simulator: -dev = qml.device("lightning.qubit", wires=qubits) +dev = qp.device("lightning.qubit", wires=qubits) ############################################################################## # Next, we need to define the quantum circuit that prepares the trial state of the @@ -134,7 +134,7 @@ # :func:`~.pennylane.qchem.hf_state` function to generate the vector representing the Hartree-Fock state. electrons = 2 -hf = qml.qchem.hf_state(electrons, qubits) +hf = qp.qchem.hf_state(electrons, qubits) print(hf) ############################################################################## @@ -145,11 +145,11 @@ # We do this using the :func:`~.pennylane.expval` function. The decorator syntax allows us to # run the cost function as an executable QNode with the gate parameter :math:`\theta:` -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def circuit(param, wires): - qml.BasisState(hf, wires=wires) - qml.DoubleExcitation(param, wires=[0, 1, 2, 3]) - return qml.expval(H) + qp.BasisState(hf, wires=wires) + qp.DoubleExcitation(param, wires=[0, 1, 2, 3]) + return qp.expval(H) ############################################################################## diff --git a/demonstrations_v2/tutorial_vqe/metadata.json b/demonstrations_v2/tutorial_vqe/metadata.json index 72bbf9d642..4f7c18dc79 100644 --- a/demonstrations_v2/tutorial_vqe/metadata.json +++ b/demonstrations_v2/tutorial_vqe/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-02-08T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry", "Getting Started" diff --git a/demonstrations_v2/tutorial_vqe_qng/demo.py b/demonstrations_v2/tutorial_vqe_qng/demo.py index d235c5fbc9..03301d663d 100644 --- a/demonstrations_v2/tutorial_vqe_qng/demo.py +++ b/demonstrations_v2/tutorial_vqe_qng/demo.py @@ -32,14 +32,14 @@ import matplotlib.pyplot as plt from pennylane import numpy as np -import pennylane as qml +import pennylane as qp ############################################################################## # For this simple example, we consider the following single-qubit Hamiltonian: :math:`\sigma_x + \sigma_z.` # # We define the device: -dev = qml.device("default.qubit", wires=1) +dev = qp.device("default.qubit", wires=1) ############################################################################## @@ -48,8 +48,8 @@ def circuit(params, wires=0): - qml.RX(params[0], wires=wires) - qml.RY(params[1], wires=wires) + qp.RX(params[0], wires=wires) + qp.RY(params[1], wires=wires) ############################################################################## @@ -58,14 +58,14 @@ def circuit(params, wires=0): # crucial component for optimizing with quantum natural gradients. coeffs = [1, 1] -obs = [qml.PauliX(0), qml.PauliZ(0)] +obs = [qp.PauliX(0), qp.PauliZ(0)] -H = qml.Hamiltonian(coeffs, obs) +H = qp.Hamiltonian(coeffs, obs) -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def cost_fn(params): circuit(params) - return qml.expval(H) + return qp.expval(H) ############################################################################## # To analyze the performance of quantum natural gradient on VQE calculations, @@ -90,7 +90,7 @@ def cost_fn(params): ############################################################################## # First, we carry out the VQE optimization using the standard gradient descent method. -opt = qml.GradientDescentOptimizer(stepsize=step_size) +opt = qp.GradientDescentOptimizer(stepsize=step_size) params = init_params @@ -125,7 +125,7 @@ def cost_fn(params): ############################################################################## # We then repeat the process for the optimizer employing quantum natural gradients: -opt = qml.QNGOptimizer(stepsize=step_size, approx="block-diag") +opt = qp.QNGOptimizer(stepsize=step_size, approx="block-diag") params = init_params @@ -259,7 +259,7 @@ def cost_fn(params): # # To construct our system Hamiltonian, we can use `PennyLane Datasets `__ to obtain the dataset for a :math:`\text{H}_2` molecule. -dataset = qml.data.load('qchem',molname="H2", bondlength=0.7)[0] +dataset = qp.data.load('qchem',molname="H2", bondlength=0.7)[0] hamiltonian, qubits = dataset.hamiltonian, len(dataset.hamiltonian.wires) hamiltonian_coeffs, hamiltonian_ops = hamiltonian.terms() @@ -272,18 +272,18 @@ def cost_fn(params): # but expand out the arbitrary single-qubit rotations to elementary # gates (RZ-RY-RZ). -dev = qml.device("default.qubit", wires=qubits) +dev = qp.device("default.qubit", wires=qubits) hf_state = np.array([1, 1, 0, 0], requires_grad=False) def ansatz(params, wires=[0, 1, 2, 3]): - qml.BasisState(hf_state, wires=wires) + qp.BasisState(hf_state, wires=wires) for i in wires: - qml.RZ(params[3 * i], wires=i) - qml.RY(params[3 * i + 1], wires=i) - qml.RZ(params[3 * i + 2], wires=i) - qml.CNOT(wires=[2, 3]) - qml.CNOT(wires=[2, 0]) - qml.CNOT(wires=[3, 1]) + qp.RZ(params[3 * i], wires=i) + qp.RY(params[3 * i + 1], wires=i) + qp.RZ(params[3 * i + 2], wires=i) + qp.CNOT(wires=[2, 3]) + qp.CNOT(wires=[2, 0]) + qp.CNOT(wires=[3, 1]) ############################################################################## @@ -291,10 +291,10 @@ def ansatz(params, wires=[0, 1, 2, 3]): # the Hartree-Fock state of the hydrogen molecule described in the minimal basis. # Again, we define the cost function to be the following QNode that measures ``expval(H)``: -@qml.qnode(dev, interface="autograd") +@qp.qnode(dev, interface="autograd") def cost(params): ansatz(params) - return qml.expval(hamiltonian) + return qp.expval(hamiltonian) ############################################################################## # For this problem, we can compute the exact value of the @@ -316,7 +316,7 @@ def cost(params): # As was done with our previous VQE example, we run the standard gradient descent # optimizer. -opt = qml.GradientDescentOptimizer(step_size) +opt = qp.GradientDescentOptimizer(step_size) params = init_params @@ -355,9 +355,9 @@ def cost(params): # Next, we run the optimizer employing quantum natural gradients. We also need to make the # Hamiltonian coefficients non-differentiable by setting ``requires_grad=False``. -hamiltonian = qml.Hamiltonian(np.array(hamiltonian_coeffs, requires_grad=False), hamiltonian_ops) +hamiltonian = qp.Hamiltonian(np.array(hamiltonian_coeffs, requires_grad=False), hamiltonian_ops) -opt = qml.QNGOptimizer(step_size, lam=0.001, approx="block-diag") +opt = qp.QNGOptimizer(step_size, lam=0.001, approx="block-diag") params = init_params prev_energy = cost(params) diff --git a/demonstrations_v2/tutorial_vqe_qng/metadata.json b/demonstrations_v2/tutorial_vqe_qng/metadata.json index 5a27a98566..a941085608 100644 --- a/demonstrations_v2/tutorial_vqe_qng/metadata.json +++ b/demonstrations_v2/tutorial_vqe_qng/metadata.json @@ -14,7 +14,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-11-06T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Optimization" ], diff --git a/demonstrations_v2/tutorial_vqe_spin_sectors/demo.py b/demonstrations_v2/tutorial_vqe_spin_sectors/demo.py index 0e24022bb4..2ace64f88f 100644 --- a/demonstrations_v2/tutorial_vqe_spin_sectors/demo.py +++ b/demonstrations_v2/tutorial_vqe_spin_sectors/demo.py @@ -62,9 +62,9 @@ # the qubit Hamiltonian of the molecule is built using the # :func:`~.pennylane.qchem.molecular_hamiltonian` function. -import pennylane as qml +import pennylane as qp -H, qubits = qml.qchem.molecular_hamiltonian(symbols, coordinates) +H, qubits = qp.qchem.molecular_hamiltonian(symbols, coordinates) print("Number of qubits = ", qubits) print("The Hamiltonian is ", H) @@ -99,7 +99,7 @@ # :math:`\hat{S}^2` observable. electrons = 2 -S2 = qml.qchem.spin2(electrons, qubits) +S2 = qp.qchem.spin2(electrons, qubits) print(S2) ############################################################################## @@ -118,7 +118,7 @@ # function to generate the vector representing the Hartree-Fock state # :math:`\vert 1100 \rangle` of the :math:`\mathrm{H}_2` molecule. -hf = qml.qchem.hf_state(electrons, qubits) +hf = qp.qchem.hf_state(electrons, qubits) print(hf) ############################################################################## @@ -139,7 +139,7 @@ # Therefore, for the ground state of the :math:`\mathrm{H}_2` molecule we choose # ``delta_sz = 0``. -singles, doubles = qml.qchem.excitations(electrons, qubits, delta_sz=0) +singles, doubles = qp.qchem.excitations(electrons, qubits, delta_sz=0) print(singles) print(doubles) @@ -154,7 +154,7 @@ def circuit(params, wires): - qml.AllSinglesDoubles(params, wires, hf, singles, doubles) + qp.AllSinglesDoubles(params, wires, hf, singles, doubles) ############################################################################## @@ -180,7 +180,7 @@ def circuit(params, wires): # Now we proceed to optimize the variational parameters. First, we define the device, # in this case a qubit simulator: -dev = qml.device("lightning.qubit", wires=qubits) +dev = qp.device("lightning.qubit", wires=qubits) ############################################################################## # Next, we define the cost function as the following QNode, where we make use of @@ -189,20 +189,20 @@ def circuit(params, wires): # a cost function that can be evaluated with the circuit parameters: -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def cost_fn(params): circuit(params, wires=range(qubits)) - return qml.expval(H) + return qp.expval(H) ############################################################################## # As a reminder, we also built the total spin operator :math:`\hat{S}^2` for which # we can now define a function to compute its expectation value: -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def S2_exp_value(params): circuit(params, wires=range(qubits)) - return qml.expval(S2) + return qp.expval(S2) ############################################################################## @@ -239,10 +239,10 @@ def total_spin(params): max_iterations = 100 prev_energy = 0.0 -@qml.qjit +@qp.qjit def update_step(i, params, opt_state): """Perform a single gradient update step""" - grads = qml.grad(cost_fn)(params) + grads = qp.grad(cost_fn)(params) updates, opt_state = opt.update(grads, opt_state) params = optax.apply_updates(params, updates) return (params, opt_state) @@ -271,7 +271,7 @@ def update_step(i, params, opt_state): # excitations whose total-spin projection differs by the quantity ``delta_sz=1`` # with respect to the Hartree-Fock state. -singles, doubles = qml.qchem.excitations(electrons, qubits, delta_sz=1) +singles, doubles = qp.qchem.excitations(electrons, qubits, delta_sz=1) print(singles) print(doubles) @@ -284,7 +284,7 @@ def update_step(i, params, opt_state): def circuit(params, wires): - qml.AllSinglesDoubles(params, wires, np.flip(hf), singles, doubles) + qp.AllSinglesDoubles(params, wires, np.flip(hf), singles, doubles) ############################################################################## @@ -306,16 +306,16 @@ def circuit(params, wires): # and the total spin operator for the new circuit. -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def cost_fn(params): circuit(params, wires=range(qubits)) - return qml.expval(H) + return qp.expval(H) -@qml.qnode(dev, interface="jax") +@qp.qnode(dev, interface="jax") def S2_exp_value(params): circuit(params, wires=range(qubits)) - return qml.expval(S2) + return qp.expval(S2) ############################################################################## @@ -328,10 +328,10 @@ def S2_exp_value(params): max_iterations = 100 -@qml.qjit +@qp.qjit def update_step(i, params, opt_state): """Perform a single gradient update step""" - grads = qml.grad(cost_fn)(params) + grads = qp.grad(cost_fn)(params) updates, opt_state = opt.update(grads, opt_state) params = optax.apply_updates(params, updates) return (params, opt_state) diff --git a/demonstrations_v2/tutorial_vqe_spin_sectors/metadata.json b/demonstrations_v2/tutorial_vqe_spin_sectors/metadata.json index c7c38851ea..de3f434cee 100644 --- a/demonstrations_v2/tutorial_vqe_spin_sectors/metadata.json +++ b/demonstrations_v2/tutorial_vqe_spin_sectors/metadata.json @@ -8,7 +8,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2020-10-13T00:00:00+00:00", - "dateOfLastModification": "2025-09-22T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry" ], diff --git a/demonstrations_v2/tutorial_vqe_vqd/demo.py b/demonstrations_v2/tutorial_vqe_vqd/demo.py index a899af0c90..d26dcc9096 100644 --- a/demonstrations_v2/tutorial_vqe_vqd/demo.py +++ b/demonstrations_v2/tutorial_vqe_vqd/demo.py @@ -51,14 +51,14 @@ # The warnings do not impact the correctness of the results, but make it harder to view outputs. # -import pennylane as qml +import pennylane as qp import numpy as np import warnings warnings.filterwarnings(action="ignore", category=np.exceptions.ComplexWarning) # Load the dataset -h2 = qml.data.load("qchem", molname="H2", bondlength=0.742, basis="STO-3G")[0] +h2 = qp.data.load("qchem", molname="H2", bondlength=0.742, basis="STO-3G")[0] # Extract the Hamiltonian H, n_qubits = h2.hamiltonian, len(h2.hamiltonian.wires) @@ -66,23 +66,23 @@ # Obtain the ground state from the operations given by the dataset def generate_ground_state(wires): - qml.BasisState(np.array(h2.hf_state), wires=wires) + qp.BasisState(np.array(h2.hf_state), wires=wires) for op in h2.vqe_gates: # use the gates data from the dataset - op = qml.map_wires(op, {op.wires[i]: wires[i] for i in range(len(wires))}) - qml.apply(op) + op = qp.map_wires(op, {op.wires[i]: wires[i] for i in range(len(wires))}) + qp.apply(op) ###################################################################### # The ``generate_ground_state`` function prepares the ground state of the molecule using the data obtained from the dataset. # Let's use it to check the energy of that state: # -dev = qml.device("default.qubit") +dev = qp.device("default.qubit") -@qml.qnode(dev) +@qp.qnode(dev) def circuit(): generate_ground_state(range(n_qubits)) - return qml.expval(H) + return qp.expval(H) print(f"Ground state energy: {circuit()}") @@ -100,16 +100,16 @@ def circuit(): from functools import partial # This line is added to better visualise the circuit -@partial(qml.transforms.decompose, max_expansion=1) +@partial(qp.transforms.decompose, max_expansion=1) def ansatz(theta, wires): - singles, doubles = qml.qchem.excitations(2, n_qubits) + singles, doubles = qp.qchem.excitations(2, n_qubits) singles = [[wires[i] for i in single] for single in singles] doubles = [[wires[i] for i in double] for double in doubles] - qml.AllSinglesDoubles(theta, wires, np.array([1,1,0,0]), singles, doubles) + qp.AllSinglesDoubles(theta, wires, np.array([1,1,0,0]), singles, doubles) theta = np.random.rand(3) # 3 parameters for the ansatz -print(qml.draw(ansatz, decimals = 2)(theta, range(4))) +print(qp.draw(ansatz, decimals = 2)(theta, range(4))) ###################################################################### # The ``ansatz`` function is the one that generates the state :math:`|\Psi(\theta)\rangle.` @@ -117,19 +117,19 @@ def ansatz(theta, wires): # known as `swap test `__. -@qml.qnode(dev) +@qp.qnode(dev) def swap_test(params): generate_ground_state(range(1, n_qubits + 1)) ansatz(params, range(n_qubits + 1, 2 * n_qubits + 1)) - qml.Barrier() # added to better visualise the circuit - qml.Hadamard(wires=0) + qp.Barrier() # added to better visualise the circuit + qp.Hadamard(wires=0) for i in range(n_qubits): - qml.CSWAP(wires=[0, 1 + i + n_qubits, 1 + i]) - qml.Hadamard(wires=0) - return qml.expval(qml.Z(0)) + qp.CSWAP(wires=[0, 1 + i + n_qubits, 1 + i]) + qp.Hadamard(wires=0) + return qp.expval(qp.Z(0)) -print(qml.draw(swap_test)(theta)) +print(qp.draw(swap_test)(theta)) print(f"\nOverlap between the ground state and the ansatz: {swap_test(theta)}") ###################################################################### @@ -138,10 +138,10 @@ def swap_test(params): # With this we have all the ingredients to define the loss function that we want to minimize: # -@qml.qnode(dev) +@qp.qnode(dev) def expected_value(theta): ansatz(theta, range(n_qubits)) - return qml.expval(H) + return qp.expval(H) def loss_f(theta, beta): return expected_value(theta) + beta * swap_test(theta) diff --git a/demonstrations_v2/tutorial_vqe_vqd/metadata.json b/demonstrations_v2/tutorial_vqe_vqd/metadata.json index 4b1bd2ad70..3ead91be51 100644 --- a/demonstrations_v2/tutorial_vqe_vqd/metadata.json +++ b/demonstrations_v2/tutorial_vqe_vqd/metadata.json @@ -11,7 +11,7 @@ "executable_stable": true, "executable_latest": true, "dateOfPublication": "2024-08-26T00:00:00+00:00", - "dateOfLastModification": "2026-01-14T15:48:14+00:00", + "dateOfLastModification": "2026-04-17T15:48:14+00:00", "categories": [ "Quantum Chemistry", "How-to"