### Installation Guide Updates Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.43.0.md The installation page has been updated with currently supported Python versions and installation instructions. ```markdown installation page ``` -------------------------------- ### Installing and Using lightning.qubit Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.11.0.md Shows how to install the `pennylane-lightning` plugin and use the `lightning.qubit` device for state-vector simulation. ```console $ pip install pennylane-lightning ``` ```pycon >>> dev = qml.device("lightning.qubit", wires=2) ``` -------------------------------- ### Quantum Tape Recording Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.15.0.md Demonstrates how to get the currently active quantum tape and temporarily stop its recording using a context manager. Operations recorded outside `stop_recording` are included in the final tape. ```python with qml.tape.QuantumTape(): qml.RX(0, wires=0) current_tape = qml.tape.get_active_tape() with current_tape.stop_recording(): qml.RY(1.0, wires=1) qml.RZ(2, wires=1) current_tape.operations ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/guide/documentation.rst Install the required packages for building the documentation using pip. ```console pip install --group docs ``` -------------------------------- ### Add code example to ApproxTimeEvolution.compute_decomposition Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.32.0.md A code example has been added to `qml.ApproxTimeEvolution.compute_decomposition()`. ```python qml.ApproxTimeEvolution.compute_decomposition() ``` -------------------------------- ### Device Initialization with Wires Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/plugins.rst Example of initializing a default qubit device with a specified number of wires. ```python >>> dev = qp.device('default.qubit', wires=1) ``` -------------------------------- ### Install JAX and JAXlib Source: https://github.com/pennylaneai/pennylane/blob/main/doc/introduction/interfaces/jax.rst Install the necessary JAX libraries for PennyLane integration. Ensure you use the specified versions. ```bash pip install jax==0.7.1 jaxlib==0.7.1 ``` -------------------------------- ### Install Catalyst Compiler Source: https://github.com/pennylaneai/pennylane/blob/main/doc/introduction/compiling_workflows.rst Install the Catalyst hybrid compiler using pip. This is required for using the `@qjit` decorator with Catalyst. ```console pip install pennylane-catalyst ``` -------------------------------- ### Qutrit Circuit Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.26.0.md Demonstrates the initialization of a `default.qutrit` device and the definition of a custom unitary operation for a qutrit circuit. ```python dev = qml.device("default.qutrit", wires=1) U = np.array([ [1, 1, 1], [1, 1, 1], [1, 1, 1] ] ``` -------------------------------- ### Example TOML Configuration File Source: https://github.com/pennylaneai/pennylane/blob/main/doc/introduction/configuration.rst An example of a TOML configuration file demonstrating how to set global PennyLane options, plugin-specific global options, and device-specific options. This file structure allows for granular control over various settings. ```toml [main] # Global PennyLane options. # Affects every loaded plugin if applicable. shots = 1000 [strawberryfields.global] # Options for the Strawberry Fields plugin # For more details, see the PennyLane-SF documentation: # https://pennylane-sf.readthedocs.io hbar = 2 shots = 100 [strawberryfields.fock] # Options for the strawberryfields.fock device cutoff_dim = 10 hbar = 2 [strawberryfields.gaussian] # Indentation doesn't matter in TOML files, # but helps provide clarity. [qiskit.global] # Global options for the Qiskit plugin. # For more details, see the PennyLane-Qiskit documentation: # https://pennylaneqiskit.readthedocs.io/en/latest/index.html backend = "qasm_simulator" [qiskit.aer] # Default options for Qiskit Aer # set the default backend options for the Qiskit Aer device # Note that, in TOML, dictionary key-value pairs are defined # using '=' rather than ':'. backend_options = {"validation_threshold" = 1e-6} [qiskit.ibmq] # Default options for IBMQ # IBM Quantum Experience authentication token ibmqx_token = "XXX" # hardware backend device backend = "ibmq_rome" # pass (optional) provider information hub = "MYHUB" group = "MYGROUP" project = "MYPROJECT" ``` -------------------------------- ### Updated qml.prod Docstring Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.41.0.md The docstring for `qml.prod` has been updated to explain that the order of the output may seem reversed, but it is correct. This example demonstrates the expected output. ```python import pennylane as qml from pennylane import numpy as np # Example demonstrating the output order of qml.prod @qml.qnode(qml.device('default.qubit')) def circuit(): qml.PauliX(wires=0) qml.PauliY(wires=1) return qml.expval(qml.prod(qml.PauliZ(0), qml.PauliZ(1))) print(circuit()) # The output is the expectation value of PauliZ(0) @ PauliZ(1). # The order in the qml.prod function does not affect the resulting operator. # The docstring clarifies that the internal representation might appear reversed # but the mathematical operation is correct. ``` -------------------------------- ### Install OpenFermion-PySCF Source: https://github.com/pennylaneai/pennylane/blob/main/doc/code/qp_qchem.rst Installs the OpenFermion-PySCF package, which is required for using the OpenFermion-PySCF backend with PennyLane's quantum chemistry module. ```bash pip install openfermionpyscf ``` -------------------------------- ### Custom Device Initialization Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/legacy_plugins.rst Example of a custom QubitDevice subclass overriding __init__ to set fixed wires, a default shot number, and accept custom hardware options. This is useful for devices with specific hardware constraints or configurations. ```python class CustomDevice(QubitDevice): name = 'My custom device' short_name = 'example.mydevice' pennylane_requires = '0.1.0' version = '0.0.1' author = 'Ada Lovelace' operations = {"PauliX", "RX", "CNOT"} observables = {"PauliZ", "PauliX", "PauliY"} def __init__(self, shots=1024, hardware_options=None): super().__init__(wires=24, shots=shots) self.hardware_options = hardware_options or hardware_defaults ``` -------------------------------- ### Install Catalyst and CUDA Quantum Source: https://github.com/pennylaneai/pennylane/blob/main/doc/introduction/compiling_workflows.rst Install both the Catalyst and CUDA Quantum compilers. This is a prerequisite for using the `@qjit` decorator with the `compiler="cuda_quantum"` option. ```bash pip install pennylane-catalyst cuda_quantum ``` -------------------------------- ### Example Package Autosummary in __init__.py Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/guide/documentation.rst An example of an autosummary table to be included at the bottom of a package's __init__.py docstring. It lists all modules within the package. ```rest .. ~pennylane.package_name.module_name1 ~pennylane.package_name.module_name2 ``` -------------------------------- ### Print GQSP Circuit Matrix (Example Output) Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.40.0.md Example output showing the first 2x2 submatrix of the calculated matrix for the GQSP circuit. The output is rounded to 3 decimal places. ```python print(np.round(matrix,3)[:2, :2]) ``` -------------------------------- ### Run PennyLane Device Integration Tests Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.11.0.md Example of invoking the PennyLane device test suite from the command line. ```console $ pl-device-test --device=default.qubit --shots=1234 --analytic=False ``` -------------------------------- ### Basic Preprocessing Pipeline Setup Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/plugins.rst Demonstrates the initial steps of setting up an execution configuration and a compile pipeline for processing quantum scripts. ```python execution_config = dev.setup_execution_config(initial_config) compile_pipeline = dev.preprocess_transforms(execution_config) batch, fn = compile_pipeline(initial_batch) fn(dev.execute(batch, execution_config)) ``` -------------------------------- ### Build HTML Documentation Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/guide/documentation.rst Navigate to the top-level directory and run the make command to build the HTML documentation. ```bash make docs ``` -------------------------------- ### Get All Possible Measurement Counts Source: https://github.com/pennylaneai/pennylane/blob/main/doc/introduction/measurements.rst This example demonstrates how to retrieve all possible measurement outcomes, including those with zero counts, by setting `all_outcomes=True` in the `qp.counts()` function. ```python dev = qp.device("default.qubit", wires=2) @qp.set_shots(shots=1000) @qp.qnode(dev) def circuit(): qp.Hadamard(wires=0) qp.CNOT(wires=[0, 1]) return qp.counts(all_outcomes=True) ``` -------------------------------- ### Using the QNSPSA Optimizer Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.26.0.md Illustrates the basic usage pattern for the QNSPSAOptimizer, showing how to initialize it and perform optimization steps. ```python max_iterations = 50 opt = qml.QNSPSAOptimizer() for _ in range(max_iterations): params, cost = opt.step_and_cost(cost, params) ``` -------------------------------- ### BBQRAM Resource Estimation Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.44.0.md Example of using the lightweight `qml.estimator.BBQRAM` for fast resource estimation within a circuit definition. The `estimate` function is then called to get the resource breakdown. ```python import pennylane.estimator as qre def circuit(): qre.CNOT() qre.QFT(num_wires=4) qre.BBQRAM(num_bitstrings=30, size_bitstring=8, num_wires=100) qre.Hadamard() ``` -------------------------------- ### Quantum Chemistry Operations with Broadcasting Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.25.0.md Quantum chemistry operations now support parameter broadcasting. This example shows how to get the matrix shape for a `SingleExcitation` operation with broadcasted parameters. ```python op = qml.SingleExcitation(np.array([0.3, 1.2, -0.7]), wires=[0, 1]) op.matrix().shape ``` -------------------------------- ### Applying operator transforms to circuits Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.22.0.md Operator transforms can act on multiple operations by passing quantum functions or tapes. This example shows how to get the matrix representation of a circuit. ```python def circuit(theta): qml.RX(theta, wires=1) qml.PauliZ(wires=0) qml.matrix(circuit)(np.pi / 4) ``` -------------------------------- ### Mottonen State Preparation Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.15.0.md Demonstrates the usage of MottonenStatePreparation for preparing a quantum state. Previously returned a different drawing of the circuit. ```python inputstate = [np.sqrt(0.2), np.sqrt(0.3), np.sqrt(0.4), np.sqrt(0.1)] @qml.qnode(dev) def circuit(): mottonen.MottonenStatePreparation(inputstate,wires=[0, 1]) return qml.expval(qml.PauliZ(0)) ``` ```python print(qml.draw(circuit)()) ``` ```python print(qml.draw(circuit)()) ``` -------------------------------- ### Initialize lightning.qubit device and circuit Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.18.0.md Demonstrates how to initialize the lightning.qubit device and define a QNode using the adjoint differentiation method. Ensure the lightning-qubit plugin is installed. ```python import pennylane as qml wires = 3 layers = 2 dev = qml.device("lightning.qubit", wires=wires) @qml.qnode(dev, diff_method="adjoint") def circuit(weights): qml.templates.StronglyEntanglingLayers(weights, wires=range(wires)) return qml.expval(qml.PauliZ(0)) weights = qml.init.strong_ent_layers_normal(layers, wires, seed=1967) ``` -------------------------------- ### Install Required Packages for .data Module Source: https://github.com/pennylaneai/pennylane/blob/main/doc/introduction/data.rst Installs the necessary packages for using the pennylane.data module. Ensure these are installed before proceeding. ```console pip install aiohttp fsspec h5py ``` -------------------------------- ### Updated qml.qchem.VibrationalPES Docstring Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.41.0.md The docstrings for `qml.qchem.localize_normal_modes` and `qml.qchem.VibrationalPES` have been updated to include examples that can be copied. This example shows `VibrationalPES`. ```python import pennylane as qml from pennylane import numpy as np # Example for qml.qchem.VibrationalPES # Define a potential energy surface (PES) function def pes_function(coords): x, y = coords return x**2 + y**2 # Create a VibrationalPES object vibrational_pes = qml.VibrationalPES(pes_function) # Evaluate the PES at a specific coordinate coords = np.array([0.5, -0.2]) energy = vibrational_pes.evaluate(coords) print(f"Coordinates: {coords}") print(f"Potential Energy: {energy}") # This class provides a convenient way to handle and evaluate potential energy surfaces for vibrational analysis. ``` -------------------------------- ### Creating and Using a QNode with JAX Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/guide/architecture.rst Illustrates the creation of a QNode using a quantum function and a device, with the JAX interface, and its subsequent execution and drawing. ```python import jax from jax import numpy as jnp params = jnp.array([0.5, 0.2]) ``` ```python qnode = qp.QNode(qfunc, device, interface='jax') qnode(params) ``` ```python qnode_drawer = qp.draw(qnode) print(qnode_drawer(params)) ``` -------------------------------- ### Updated qml.qchem.localize_normal_modes Docstring Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.41.0.md The docstrings for `qml.qchem.localize_normal_modes` and `qml.qchem.VibrationalPES` have been updated to include examples that can be copied. This example shows `localize_normal_modes`. ```python import pennylane as qml from pennylane import numpy as np # Example for qml.qchem.localize_normal_modes # Define a Hessian matrix (example for a 2-mode system) Hessian = np.array([ [1.0, 0.1], [0.1, 1.5] ]) # Localize the normal modes localized_modes = qml.localize_normal_modes(Hessian) print("Original Hessian:\n", Hessian) print("Localized modes:\n", localized_modes) # This function helps in transforming normal modes to localized ones, useful in quantum chemistry simulations. ``` -------------------------------- ### Executing a Tape on a Device Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/guide/architecture.rst Shows how to instantiate a device and execute a quantum tape using the batch_execute method. ```python device = qp.device("default.qubit", wires=['a', 'b'], shots=None) device.batch_execute([tape]) ``` -------------------------------- ### Install Pre-commit Hook Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/guide/pullrequests.rst Install the 'pre-commit' package, which automates running 'black', 'isort', and 'pylint' as a git pre-commit hook. This command should be run in the top-level folder of the PennyLane repository after installing the package. ```bash pre-commit install ``` -------------------------------- ### Import OpenQASM 3.0 Circuit Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.42.0.md Demonstrates importing an OpenQASM 3.0 program into a PennyLane QNode. Ensure 'openqasm3' and 'openqasm3[parser]' are installed. ```python import pennylane as qml dev = qml.device("default.qubit", wires=[0, 1, 2]) @qml.qnode(dev) def my_circuit(): qml.from_qasm3( """ qubit q0; qubit q1; qubit q2; float theta = 0.2; int power = 2; ry(theta / 2) q0; rx(theta) q1; pow(power) @ x q0; def random(qubit q) -> bit { bit b = "0"; h q; measure q -> b; return b; } bit m = random(q2); if (m) { int i = 0; while (i < 5) { i = i + 1; rz(i) q1; break; } } ", {'q0': 0, 'q1': 1, 'q2': 2}, )() return qml.expval(qml.Z(0)) ``` -------------------------------- ### SemiAdder Template Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.42.0.md Demonstrates the usage of the SemiAdder template for performing addition on a quantum computer. It shows how to initialize registers and apply the SemiAdder to add two integers. ```python from functools import partial x = 3 y = 4 wires = qml.registers({"x": 3, "y": 6, "work": 5}) dev = qml.device("default.qubit") @partial(qml.set_shots, shots=1) @qml.qnode(dev) def circuit(): qml.BasisEmbedding(x, wires=wires["x"]) qml.BasisEmbedding(y, wires=wires["y"]) qml.SemiAdder(wires["x"], wires["y"], wires["work"]) return qml.sample(wires=wires["y"]) ``` -------------------------------- ### Corrected Lie Closure Dense Code Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.41.0.md A typo has been fixed in the code example for `qml.labs.dla.lie_closure_dense`. ```python import pennylane as qml from pennylane import numpy as np # Example of lie_closure_dense # Define a list of matrices matrices = [ np.array([[0, 1], [1, 0]]), np.array([[0, -1j], [1j, 0]]) ] # Compute the Lie closure closure = qml.lie_closure_dense(matrices) print(closure) ``` -------------------------------- ### Optimizing QNode with Optax Adam Source: https://github.com/pennylaneai/pennylane/blob/main/doc/introduction/interfaces/jax.rst This example shows how to optimize a QNode using `jax.jit` and the `adam` optimizer from the Optax library. PennyLane's optimizers are not compatible with the JAX interface. ```python import pennylane as qp from jax import numpy as jnp import jax import optax learning_rate = 0.15 dev = qp.device("default.qubit", wires=1) @jax.jit @qp.set_shots(shots=None) @qp.qnode(dev, interface="jax") def energy(a): qp.RX(a, wires=0) return qp.expval(qp.PauliZ(0)) optimizer = optax.adam(learning_rate) params = jnp.array(0.5) opt_state = optimizer.init(params) for _ in range(200): grads = jax.grad(energy)(params) updates, opt_state = optimizer.update(grads, opt_state) params = optax.apply_updates(params, updates) >>> params Array(3.14159111, dtype=float64) ``` -------------------------------- ### Initialize Device by Short Name Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/legacy_plugins.rst Shows how to initialize a PennyLane device using its unique `short_name` string, which is discovered via setuptools entry points. ```python import pennylane as qp dev1 = qp.device(short_name, wires=2) ``` -------------------------------- ### Install PennyLane with Pip Source: https://github.com/pennylaneai/pennylane/blob/main/doc/index.rst Install PennyLane and its dependencies using pip. Ensure you have Python version 3.11 or above. ```bash python -m pip install pennylane ``` -------------------------------- ### Corrected BasisRotation Code Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.41.0.md The code example for `qml.BasisRotation` has been corrected to include `wire_order` in the call to `qml.matrix`. ```python import pennylane as qml from pennylane import numpy as np # Example with wire_order matrix = np.array([[1, 0], [0, 1]]) @qml.qnode(qml.device('default.qubit')) def circuit(): qml.BasisRotation(matrix, wires=[0, 1], wire_order=[0, 1]) return qml.expval(qml.PauliZ(0)) print(circuit()) # Example without wire_order (original issue) # @qml.qnode(qml.device('default.qubit')) # def circuit_no_wire_order(): # qml.BasisRotation(matrix, wires=[0, 1]) # return qml.expval(qml.PauliZ(0)) # print(circuit_no_wire_order()) ``` -------------------------------- ### Basic QNode Execution with Auto Interface Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.29.0.md Example of defining and executing a QNode with automatic interface detection. Imports `jax` and `jax.numpy`. ```python import jax import jax.numpy as jnp qml.enable_return() a = jnp.array(0.1) b = jnp.array(0.2) dev = qml.device("default.qubit", wires=2) @qml.qnode(dev) def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliY(1)) ``` -------------------------------- ### Register Plugin Devices with Setuptools Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/legacy_plugins.rst Configures the `setup.py` file to register custom PennyLane devices using setuptools `entry_points`, enabling PennyLane to discover and load them. ```python devices_list = [ 'example.mydevice1 = MyModule.MySubModule:MyDevice1', 'example.mydevice2 = MyModule.MySubModule:MyDevice2' ], setup(entry_points={'pennylane.plugins': devices_list}) ``` -------------------------------- ### Prepare State in Circuit with qml.StatePrep Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.32.0.md Implement a quantum state vector in a circuit using `qml.StatePrep`. This example prepares the state obtained from `qml.qchem.import_state`. ```pycon >>> dev = qml.device('default.qubit', wires=4) >>> @qml.qnode(dev) ... def circuit(): ... qml.StatePrep(wf_cisd, wires=range(4)) ... return qml.state() >>> print(circuit()) [ 0. +0.j 0. +0.j 0. +0.j 0.1066467 +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 2. +0.j 0. +0.j 0. +0.j 0. +0.j -0.99429698+0.j 0. +0.j 0. +0.j 0. +0.j] ``` -------------------------------- ### Install PySCF Source: https://github.com/pennylaneai/pennylane/blob/main/doc/code/qp_qchem.rst Installs the PySCF package, which is required for using the PySCF backend with PennyLane's quantum chemistry module. ```bash pip install pyscf ``` -------------------------------- ### Enable and Use PennyLane Logging Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/guide/logging.rst Enables PennyLane logging and demonstrates its use within a QNode execution. This example shows how to log device creation, QNode definition, and evaluation steps. ```python import pennylane as qp import logging qp.logging.enable_logging() logger = logging.getLogger(__name__) def circuit(param): logger.info(f"Creating {dev_name} device with {num_wires} wires") dev = qp.device(dev_name, wires=num_wires) @qp.set_shots(shots=num_shots) @qp.qnode(dev, diff_method="adjoint") def my_circuit(param): qp.RX(param, wires=0) qp.CNOT(wires=[0, 1]) return qp.expval(qp.PauliZ(0)) logger.info(f"Created QNODE={my_circuit}") res = my_circuit(param) logger.info(f"Created QNODE evaluation={res}") return res par = qp.numpy.array([0.1,0.2]) logger.info(f"Running circuit with par={par[0]}") circuit(par[0]) logger.info(f"Running circuit with par={par[1]}") circuit(par[1]) logger.info(f"Calculating jacobian circuit with par={par}") logger.info(f"Jacobian={qp.jacobian(circuit)(par[0])}") ``` -------------------------------- ### Optimizing QNode with JAXopt GradientDescent Source: https://github.com/pennylaneai/pennylane/blob/main/doc/introduction/interfaces/jax.rst This example demonstrates optimizing a QNode using `jax.jit` and the `GradientDescent` optimizer from the JAXopt library. PennyLane's optimizers are not compatible with the JAX interface. ```python import pennylane as qp import jax import jaxopt jax.config.update("jax_enable_x64", True) dev = qp.device("default.qubit", wires=1) @jax.jit @qp.set_shots(shots=None) @qp.qnode(dev, interface="jax") def energy(a): qp.RX(a, wires=0) return qp.expval(qp.PauliZ(0)) gd = jaxopt.GradientDescent(energy, maxiter=5) res = gd.run(0.5) optimized_params = res.params >>> optimized_params Array(3.1415861, dtype=float64, weak_type=True) ``` -------------------------------- ### Idempotent run_autograph Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.41.0.md `qml.capture.run_autograph` is now idempotent, meaning applying it multiple times has the same effect as applying it once. This example illustrates the concept. ```python import pennylane as qml from pennylane import numpy as np # Define a simple function def my_function(x): return x * 2 # Apply run_autograph once processed_function_1 = qml.capture.run_autograph(my_function) # Apply run_autograph again to the already processed function processed_function_2 = qml.capture.run_autograph(processed_function_1) # Test both result_1 = processed_function_1(5) result_2 = processed_function_2(5) print(f"Result after one run_autograph: {result_1}") print(f"Result after two runs of run_autograph: {result_2}") # The results should be identical, demonstrating idempotency. ``` -------------------------------- ### Example Device Execution with Tracker Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/plugins.rst Demonstrates how to use a device tracker to record execution details like batches, simulations, and resources. This snippet shows the typical usage within an execute method. ```python def execute(self, circuits, execution_config: ExecutionConfig | None = None): return tuple(0.0 for _ in circuits) >>> dev = MyDevice() >>> tape = qp.tape.QuantumTape([qp.S(0)], [qp.expval(qp.X(0))]) >>> with dev.tracker: ... out = dev.execute(tape) >>> out 0.0 >>> dev.tracker.history {'batches': [1], 'simulations': [1], 'executions': [1], 'results': [0.0], 'resources': [Resources(num_wires=1, num_gates=1, gate_types=defaultdict(, {'S': 1}), gate_sizes=defaultdict(, {1: 1}), depth=1, shots=Shots(total_shots=None, shot_vector=()))]} ``` -------------------------------- ### Updated qml.PauliSentence Docstring Code Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.41.0.md The code example in the docstring for `qml.PauliSentence` has been updated to ensure it properly copy-pastes and runs. ```python import pennylane as qml from pennylane import numpy as np # Example for qml.PauliSentence # Define a PauliSentence pauli_sentence = qml.PauliSentence({ "PauliZ(0)@PauliX(1)": 2.0, "PauliX(0)@PauliY(1)": -1.5 }) print("PauliSentence:", pauli_sentence) # Convert to a list of Pauli terms pauli_terms = list(pauli_sentence.terms()) print("Pauli terms:", pauli_terms) # This demonstrates how to create and inspect a PauliSentence object. ``` -------------------------------- ### Improve Device.experimental.Device documentation Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.32.0.md Documentation for `qml.devices.experimental.Device` has been improved to clarify its use. ```python qml.devices.experimental.Device ``` -------------------------------- ### Deprecated qml.device Usage Examples Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.43.0.md Three examples of deprecated usage of 'qml.device(..., shots=...)' in the documentation have been updated. ```python qml.device(..., shots=...) ``` -------------------------------- ### Setup Entry Points in __init__.py Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/guide/documentation.rst Import and use _setup_entry_points to make Catalyst features accessible from a PennyLane module. This is typically done in the module's __init__.py file. ```python3 from .._entry_points_utils import _setup_entry_points __all__, __getattr__, __dir__ = _setup_entry_points(__name__, "pennylane.drawer") ``` -------------------------------- ### Experimental Functionality Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.13.0.md Example of using an experimental function `ones_like` which returns a tensor of ones with the same shape and dtype as the input. ```python >>> qml.proc.ones_like(y, dtype=np.complex128) ``` -------------------------------- ### JAX-JIT Gradient Support for QNodes Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.27.0.md Illustrates the use of `jax.jit` with PennyLane QNodes for computing gradients. This example demonstrates computing the Jacobian of a circuit returning multiple expectation values using JAX. ```python import jax from jax import numpy as jnp from jax.config import config config.update("jax_enable_x64", True) dev = qml.device("lightning.qubit", wires=2) @jax.jit @qml.qnode(dev, diff_method="parameter-shift", interface="jax") def circuit(x, y): qml.RY(x, wires=0) qml.RY(y, wires=1) qml.CNOT(wires=[0, 1]) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)) x = jnp.array(1.0) y = jnp.array(2.0) ``` ```python >>> jax.jacobian(circuit, argnums=[0, 1])(x, y) (Array([-0.84147098, 0.35017549], dtype=float64, weak_type=True), Array([ 4.47445479e-18, -4.91295496e-01], dtype=float64, weak_type=True)) ``` -------------------------------- ### Install Plugin in Developer Mode Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/legacy_plugins.rst Install a plugin directly from its source path for development. Replace 'pluginpath' with the actual directory of your plugin. ```bash pip install -e pluginpath ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/guide/installation.rst Install additional packages required for development processes such as linting, testing, and pre-commit checks using pip. ```bash python -m pip install --group dev ``` -------------------------------- ### Execute a circuit with custom shot scaling Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.32.0.md This example demonstrates executing a QNode decorated with a custom transform that scales shots. The output shows the result of sampling from the circuit with the scaled number of shots. ```python >>> circuit(shots=1) array([False, False]) ``` -------------------------------- ### Install Pre-commit Package Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/guide/pullrequests.rst Install the 'pre-commit' package using pip. This package is used to configure git hooks for code formatting and linting. ```bash pip install pre-commit ``` -------------------------------- ### Updated qml.unary_mapping Docstring Example Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.41.0.md The docstrings for several mapping functions, including `qml.unary_mapping`, have been updated to include better, copy-pasteable code examples. ```python import pennylane as qml from pennylane import numpy as np # Example of qml.unary_mapping def my_unary_op(x): return qml.RX(x, wires=0) # Apply the unary mapping to a circuit @qml.qnode(qml.device('default.qubit')) def circuit(param): qml.unary_mapping(param, my_unary_op) return qml.expval(qml.PauliZ(0)) print(circuit(np.pi/2)) # This demonstrates how to define and use custom unary operations within PennyLane. ``` -------------------------------- ### Update specs Function Examples Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.43.0.md Code examples in the documentation of ':func:`~.specs`' have been updated to replace keyword arguments with 'gradient_kwargs' in the QNode definition. ```python .specs ``` -------------------------------- ### PrepSelPrep Template Equivalence Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.38.0.md Demonstrates the equivalence between using the qml.PrepSelPrep template and a manual sequence of qml.StatePrep, qml.Select, and qml.adjoint(qml.StatePrep). Requires numpy for calculations. ```python import numpy as np coeffs = [0.3, 0.1] alphas = (np.sqrt(coeffs) / np.linalg.norm(np.sqrt(coeffs))) unitaries = [qml.X(2), qml.Z(2)] lcu = qml.dot(coeffs, unitaries) control = [0, 1] def prep_sel_prep(alphas, unitaries): qml.StatePrep(alphas, wires=control, pad_with=0) qml.Select(unitaries, control=control) qml.adjoint(qml.StatePrep)(alphas, wires=control, pad_with=0) @qml.qnode(qml.device("default.qubit")) def circuit(lcu, control, alphas, unitaries): qml.PrepSelPrep(lcu, control) qml.adjoint(prep_sel_prep)(alphas, unitaries) return qml.state() ``` -------------------------------- ### Get Canonical Interface Name with Enum Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.43.0.md Use the Enum directly to get the canonical interface name. This replaces the deprecated get_canonical_interface_name function. ```python from pennylane.math.interface_utils import Interface Interface("torch") ``` ```python Interface("jax-jit") ``` -------------------------------- ### Initialize PennyLane Device with Custom Wires Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.11.0.md Demonstrates initializing a PennyLane device with custom wire labels for quantum operations. ```python dev = qml.device("default.qubit", wires=['anc1', 'anc2', 0, 1, 3]) ``` -------------------------------- ### Example Package RST Content Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/guide/documentation.rst This is an example of the content for a package's .rst file in the documentation. It uses the literalinclude directive to embed content from another file. ```rest .. automodule:: pennylane.package_name :members: :undoc-members: :show-inheritance: ``` -------------------------------- ### Use JAX Interface with default.qubit Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.14.0.md Example of creating and differentiating hybrid quantum-classical models using JAX with the `default.qubit.jax` device. Requires `interface="jax"` and `diff_method="backprop"`. ```python import pennylane as qml import jax from jax import numpy as jnp dev = qml.device("default.qubit", wires=1) @qml.qnode(dev, interface="jax", diff_method="backprop") def circuit(x): qml.RX(x[1], wires=0) qml.Rot(x[0], x[1], x[2], wires=0) return qml.expval(qml.PauliZ(0)) weights = jnp.array([0.2, 0.5, 0.1]) grad_fn = jax.grad(circuit) print(grad_fn(weights)) ``` -------------------------------- ### Workflow Inspection with qjit specs Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.45.0.md Example of using qp.specs with qp.qjit and level="all" to display circuit resource evolution through compilation stages. Shows how transformations like cancel_inverses and merge_rotations affect gate counts and wire usage. ```python @qp.qjit @qp.transforms.merge_rotations @qp.transforms.cancel_inverses @qp.qnode(qp.device("lightning.qubit", wires=2)) def circuit(): qp.RX(1.23,0) qp.RX(1.23,0) qp.X(0) qp.H(0) qp.H(0) return qp.probs() ``` ```python print(qp.specs(circuit, level="all")()) ``` -------------------------------- ### Example Module RST Content Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/guide/documentation.rst This is an example of the content for a module's .rst file in the documentation. It uses the literalinclude directive to embed content from another file. ```rest .. automodule:: pennylane.module_name :members: :undoc-members: :show-inheritance: ``` -------------------------------- ### Enable JAX-JIT First-Order Gradients Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.28.0.md Demonstrates enabling first-order gradient computation with JAX-JIT after calling `qml.enable_return()`. Requires JAX and PennyLane. ```python import jax from jax import numpy as jnp jax.config.update("jax_enable_x64", True) qml.enable_return() dev = qml.device("lightning.qubit", wires=2) @jax.jit @qml.qnode(dev, interface="jax-jit", diff_method="parameter-shift") def circuit(a, b): qml.RY(a, wires=0) qml.RX(b, wires=0) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)) a, b = jnp.array(1.0), jnp.array(2.0) ``` ```pycon >>> jax.jacobian(circuit, argnums=[0, 1])(a, b) ((Array(0.35017549, dtype=float64, weak_type=True), Array(-0.4912955, dtype=float64, weak_type=True)), (Array(5.55111512e-17, dtype=float64, weak_type=True), Array(0., dtype=float64, weak_type=True))) ``` -------------------------------- ### Install PennyLane in Development Mode Source: https://github.com/pennylaneai/pennylane/blob/main/doc/development/guide/installation.rst Clone the PennyLane repository and install it in editable mode. This ensures that changes to the source code are immediately reflected when importing PennyLane in Python. ```bash git clone https://github.com/PennyLaneAI/pennylane cd pennylane python -m pip install -e . ``` -------------------------------- ### Draw Trotterized Circuit (Example) Source: https://github.com/pennylaneai/pennylane/blob/main/doc/releases/changelog-0.40.0.md Draw the quantum circuit generated by the TrotterizedQfunc or trotterize function. This example shows the circuit for one Trotter step with specific parameters. ```python time = 0.1 theta, phi = (0.12, -3.45) print(qml.draw(my_circuit, level="device")(time, theta, phi, num_trotter_steps=1)) ```