### Install Documentation Dependencies with uv (Bash) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Installs the specific dependencies required for building the project documentation using `uv sync` with the `--group doc` option. ```bash uv sync --group doc ``` -------------------------------- ### Run Full Test Suite with Make (Bash) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Executes the complete Mr Mustard test suite using the `make test` command. This is the standard way to verify correct installation and functionality. ```bash make test ``` -------------------------------- ### Install Mr Mustard for Development (Bash) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Clones the Mr Mustard repository from GitHub, navigates into the directory, and installs the package in editable mode using pip. The `-e` flag ensures local code changes are reflected without reinstallation. ```bash git clone https://github.com/XanaduAI/MrMustard cd MrMustard pip install -e . ``` -------------------------------- ### Build HTML Documentation with Make (Bash) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Builds the project's HTML documentation using the `make docs` command. The output is placed in the `doc/_build/html/` directory. ```bash make docs ``` -------------------------------- ### Run Formatting and Linting with Make (Bash) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Executes both code formatting and linting checks using a single `make` command. ```bash make format lint ``` -------------------------------- ### Format Code with Make (Bash) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Applies the configured code formatting (using black) to the project files via the `make format` command. ```bash make format ``` -------------------------------- ### Chaining Gates with Right Shift Operator (Mr Mustard/Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md This example illustrates how to apply multiple gates sequentially to a quantum state using the right-shift operator (`>>`). It starts with a single-mode vacuum state, applies a Squeeze gate, and then a Displacement gate to create a displaced squeezed vacuum state. ```python displaced_squeezed = Vacuum(1) >> Sgate(r=0.5) >> Dgate(x=1.0) ``` -------------------------------- ### Creating and Applying Circuits (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Illustrates how to define quantum circuits by chaining multiple gates using the right-shift operator >>. Includes examples of applying a circuit to a state and constructing a circuit with noise/loss. ```python X8 = Sgate(r=[1.0] * 4) >> Interferometer(4) output = Vacuum(4) >> X8 # lossy X8 noise = lambda: np.random.uniform(size=4) X8_noisy = (Sgate(r=0.9 + 0.1*noise(), phi=0.1*noise()) >> Attenuator(0.89 + 0.01*noise()) >> Interferometer(4) >> Attenuator(0.95 + 0.01*noise()) ) # 2-mode Bloch Messiah decomposition bloch_messiah = Sgate(r=[0.1,0.2]) >> BSgate(theta=-0.1, phi=2.1) >> Dgate(x=[0.1, -0.4]) my_state = Vacuum(2) >> bloch_messiah ``` -------------------------------- ### Sync Development Dependencies with uv (Bash) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Uses the `uv` tool to synchronize development dependencies, including testing and formatting tools like pytest and black. This command also creates a virtual environment. ```bash uv sync ``` -------------------------------- ### Run Code Linting with Make (Bash) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Executes code linting checks on the project files using the `make lint` command. ```bash make lint ``` -------------------------------- ### Getting State/Gate Representations in MrMustard Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Demonstrates how to obtain Fock representations (ket, density matrix) for a state and matrix representations (unitary, Choi) for a gate by specifying cutoffs. ```python Coherent(0.5).ket(cutoffs=[5]) # ket Coherent(0.5).dm(cutoffs=[5]) # density matrix Dgate(x=1.0).U(cutoffs=[15]) # truncated unitary matrix Dgate(x=1.0).choi(cutoffs=[15]) # truncated choi tensor ``` -------------------------------- ### Format Code Directly with Black (Bash) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Directly invokes the `black` formatter on the `mrmustard` directory with a line length limit of 100 characters. Alternative to using `make format`. ```bash black -l 100 mrmustard ``` -------------------------------- ### Linting Python Code with Pylint (Bash) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Describes how to use Pylint to check Python code for errors and adherence to coding standards. This command requires Pylint to be installed and should be run from the source code directory on the specific modified file. ```bash pylint mrmustard/path/to/modified/file.py ``` -------------------------------- ### Using MrMustard Math Module with Numpy Backend Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Illustrates the use of the mrmustard.math module, which provides a plug-and-play interface to different backends. This example shows a simple trigonometric function call using the default numpy backend. ```python import mrmustard.math as math math.cos(0.1) # numpy ``` -------------------------------- ### Creating and Applying Quantum Circuits (Mr Mustard/Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md This code illustrates how to define quantum circuits by chaining gates using the `>>` operator. It shows examples of a simple 4-mode circuit (`X8`), a more realistic circuit with noise and loss, and a 2-mode circuit representing a Bloch-Messiah decomposition. These circuits can then be applied to states. ```python X8 = Sgate(r=[1.0] * 4) >> Interferometer(4) output = Vacuum(4) >> X8 # lossy X8 noise = lambda: np.random.uniform(size=4) X8_realistic = (Sgate(r=0.9 + 0.1*noise(), phi=0.1*noise()) >> Attenuator(0.89 + 0.01*noise()) >> Interferometer(4) >> Attenuator(0.95 + 0.01*noise()) ) # 2-mode Bloch Messiah decomposition bloch_messiah = Sgate(r=[0.1,0.2]) >> BSgate(-0.1, 2.1) >> Dgate(x=[0.1, -0.4]) my_state = Vacuum(2) >> bloch_messiah ``` -------------------------------- ### Comparing Transformations (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Illustrates the use of the equality operator == to compare quantum transformations (gates or circuits), showing an example of checking the equivalence of applying a displacement and an attenuator in different orders. ```python >>> Dgate(np.sqrt(2)) >> Attenuator(0.5) == Attenuator(0.5) >> Dgate(1.0) True ``` -------------------------------- ### Check Test Coverage with Make (Bash) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Generates a test coverage report for the Mr Mustard project using the `make coverage` command. Requires the `pytest-cov` plugin. ```bash make coverage ``` -------------------------------- ### Optimizing Parameters using MrMustard Optimizer Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Provides an example of using the mrmustard.training.Optimizer to minimize a cost function by optimizing trainable parameters of gates. It shows how to define cost functions and use the optimizer for both Euclidean (Adam) and Symplectic parameters. ```python from mrmustard import math from mrmustard.lab import Dgate, Ggate, Attenuator, Vacuum, Coherent, DisplacedSqueezed from mrmustard.physics import fidelity from mrmustard.training import Optimizer math.change_backend("tensorflow") D = Dgate(x = 0.1, y = -0.5, x_trainable=True, y_trainable=True) L = Attenuator(transmissivity=0.5) # we write a function that takes no arguments and returns the cost def cost_fn_eucl(): state_out = Vacuum(1) >> D >> L return 1 - fidelity(state_out, Coherent(0.1, 0.5)) G = Ggate(num_modes=1, symplectic_trainable=True) def cost_fn_sympl(): state_out = Vacuum(1) >> G >> D >> L return 1 - fidelity(state_out, DisplacedSqueezed(r=0.3, phi=1.1, x=0.4, y=-0.2)) # For illustration, here the Euclidean optimization doesn't include squeezing opt = Optimizer(symplectic_lr=0.1, euclidean_lr=0.01) opt.minimize(cost_fn_eucl, by_optimizing=[D]) # using Adam for D # But the symplectic optimization always does opt = Optimizer(symplectic_lr=0.1, euclidean_lr=0.01) opt.minimize(cost_fn_sympl, by_optimizing=[G,D]) # uses Adam for D and the symplectic opt for G ``` -------------------------------- ### Run Specific Test Module with Pytest (Bash) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Runs tests contained within a single specified test file using the `pytest` command directly. This allows for focused testing of individual components. ```bash pytest tests/test_fidelity.py ``` -------------------------------- ### Stop Pytest on First Failure (Console) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Runs the pytest suite but stops execution immediately upon encountering the first test failure. Useful for debugging specific issues. ```console pytest -x ``` -------------------------------- ### Applying Transformations in Dual Sense with Left Shift (Mr Mustard/Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md This example illustrates the duality between applying a channel to a state (`>>`) and applying the adjoint channel to a detector/measurement (`<<`). It shows that applying an Attenuator to a Coherent state using `<<` is equivalent to applying an Amplifier (the adjoint channel) to the same Coherent state using `>>`. ```python Attenuator(0.5) << Coherent(0.1, 0.2) == Coherent(0.1, 0.2) >> Amplifier(2.0) ``` -------------------------------- ### Generate Filtered Coverage Report (Console) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Generates a coverage report for a specific file while excluding tests matching a pattern using the `-k` option. Combines coverage reporting with test filtering. ```console pytest tests/test_fidelity.py --cov --cov-report=term-missing -k 'not test_fidelity_coherent_state' ``` -------------------------------- ### Generate Coverage Report for Specific Module (Console) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Generates a detailed test coverage report for a specified module path using pytest with the `--cov` and `--cov-report=term-missing` options. Shows missing lines. ```console pytest tests/test_fidelity.py --cov=mrmustard/location/to/module --cov-report=term-missing ``` -------------------------------- ### Autoformatting Python Code with Black (Bash) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/development/development_guide.rst Explains how to use the Black autoformatter to format Python code according to PEP8 standards with a maximum line length of 100 characters. This command should be run from the source code directory on the specific modified file. ```bash black -l 100 mrmustard/path/to/modified/file.py ``` -------------------------------- ### Getting Fock Representation of States and Transformations in MrMustard Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Explains how to obtain the truncated Fock representation (ket, density matrix, unitary, Choi matrix) for states, gates, and circuits using methods like `.ket`, `.dm`, `.U`, and `.choi` with specified cutoffs. ```python # Fock representation of a coherent state Coherent(0.5).ket(cutoffs=[5]) # ket Coherent(0.5).dm(cutoffs=[5]) # density matrix Dgate(x=1.0).U(cutoffs=[15]) # truncated unitary op Dgate(x=1.0).choi(cutoffs=[15]) # truncated choi op ``` -------------------------------- ### Setting up Optimization with Trainable Parameters in MrMustard Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Demonstrates the initial steps for setting up an optimization problem in MrMustard by importing necessary modules and defining gates with trainable parameters. ```python from mrmustard import math from mrmustard.lab import Dgate, Ggate, Attenuator, Vacuum, Coherent, DisplacedSqueezed from mrmustard.physics import fidelity from mrmustard.training import Optimizer math.change_backend("tensorflow") D = Dgate(x = 0.1, y = -0.5, x_trainable=True, y_trainable=True) L = Attenuator(transmissivity=0.5) ``` -------------------------------- ### Creating Quantum States and Gates in MrMustard (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Demonstrates how to instantiate various single-mode and multi-mode quantum states and gates available in the `mrmustard.lab` module, including vacuum, coherent, squeezed vacuum, Gaussian, Fock states, and displacement, squeezing, rotation, amplifier, attenuator, noise, beam splitter, two-mode squeezing, Mach-Zehnder, and interferometer gates. ```python import numpy as np from mrmustard.lab import * vac = Vacuum(num_modes=2) # 2-mode vacuum state coh = Coherent(x=0.1, y=-0.4) # coh state |alpha> with alpha = 0.1 - 0.4j sq = SqueezedVacuum(r=0.5) # squeezed vacuum state g = Gaussian(num_modes=2) # 2-mode Gaussian state with zero means fock4 = Fock(4) # fock state |4> D = Dgate(x=1.0, y=-0.4) # Displacement by 1.0 along x and -0.4 along y S = Sgate(r=0.5) # Squeezer with r=0.5 R = Rgate(angle=0.3) # Phase rotation by 0.3 A = Amplifier(gain=2.0) # noisy amplifier with 200% gain L = Attenuator(0.5) # pure loss channel with 50% transmissivity N = AdditiveNoise(noise=0.1) # additive noise with noise level 0.1 BS = BSgate(theta=np.pi/4) # 50/50 beam splitter S2 = S2gate(r=0.5) # two-mode squeezer MZ = MZgate(phi_a=0.3, phi_b=0.1) # Mach-Zehnder interferometer I = Interferometer(8) # 8-mode interferometer L = Attenuator(0.5) # pure lossy channel with 50% transmissivity A = Amplifier(gain=2.0, nbar=1.0) # noisy amplifier with 200% gain ``` -------------------------------- ### Creating Quantum States and Gates in Mr Mustard (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md This snippet shows how to instantiate common quantum states like Vacuum, Coherent, SqueezedVacuum, Gaussian, and Fock states, as well as various gates such as Displacement, Squeezer, Beam Splitter, Two-Mode Squeezer, Mach-Zehnder, Interferometer, Attenuator, and Amplifier using the Mr Mustard library. It imports necessary components from `mrmustard.lab` and `numpy`. ```python import numpy as np from mrmustard.lab import * vac = Vacuum(num_modes=2) # 2-mode vacuum state coh = Coherent(x=0.1, y=-0.4) # coh state |alpha> with alpha = 0.1 - 0.4j sq = SqueezedVacuum(r=0.5) # squeezed vacuum state g = Gaussian(num_modes=2) # 2-mode Gaussian state with zero means fock4 = Fock(4) # fock state |4> D = Dgate(x=1.0, y=-0.4) # Displacement by 1.0 along x and -0.4 along y S = Sgate(r=0.5) # Squeezer with r=0.5 BS = BSgate(theta=np.pi/4) # 50/50 beam splitter S2 = S2gate(r=0.5) # two-mode squeezer MZ = MZgate(phi_a=0.3, phi_b=0.1) # Mach-Zehnder interferometer I = Interferometer(8) # 8-mode interferometer L = Attenuator(0.5) # pure lossy channel with 50% transmissivity A = Amplifier(gain=2.0, nbar=1.0) # noisy amplifier with 200% gain ``` -------------------------------- ### Initializing State from Fock Amplitudes with Buffer in MrMustard Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Demonstrates creating a quantum state directly from a NumPy array of Fock amplitudes, including a buffer of zeros to implicitly set the cutoff, and applying a gate to it. ```python my_amplitudes = np.array([0.5, 0.25, -0.5, 0.25, 0.25, 0.5, -0.25] + [0.0]*23) # notice the buffer my_state = State(ket=my_amplitudes) my_state >> Sgate(r=0.5) # just works ``` -------------------------------- ### Applying Gates to Specific Modes using Item Access (Mr Mustard/Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md This snippet shows how to apply gates to selected modes in a multi-mode system using Python's item access syntax (`[]`). It demonstrates applying a Displacement gate to mode 1, a Squeeze gate to mode 0, a Beam Splitter to modes 0 and 2, and a Squeeze gate in parallel to modes 0, 1, and 2. ```python D = Dgate(y=-0.4) S = Sgate(r=0.1, phi=0.5) state = Vacuum(2) >> D[1] >> S[0] # displacement on mode 1 and squeezing on mode 0 BS = BSgate(theta=1.1) state = Vacuum(3) >> BS[0,2] # applying a beamsplitter to modes 0 and 2 state = Vacuum(4) >> S[0,1,2] # applying the same Sgate in parallel to modes 0, 1 and 2 but not to mode 3 ``` -------------------------------- ### Using MrMustard Math Module with NumPy Backend Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Illustrates how to import and use the `mrmustard.math` module, which defaults to the NumPy backend, for mathematical operations. ```python import mrmustard.math as math math.cos(0.1) # numpy ``` -------------------------------- ### Changing MrMustard Math Backend to Tensorflow Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Demonstrates how to switch the backend used by the mrmustard.math module to tensorflow using the change_backend function. Subsequent math operations will utilize the specified backend. ```python import mrmustard.math as math math.change_backend("tensorflow") math.cos(0.1) # tensorflow ``` -------------------------------- ### Initializing State from Fock Amplitudes and Forcing Cutoff in MrMustard Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Shows an alternative method for creating a quantum state from Fock amplitudes by explicitly setting the internal cutoff after initialization, allowing subsequent gate operations. ```python my_amplitudes = np.array([0.5, 0.25, -0.5, 0.25, 0.25, 0.5, -0.25]) # no buffer my_state = State(ket=my_amplitudes) my_state._cutoffs = [42] # force the cutoff my_state >> Sgate(r=0.5) # works too ``` -------------------------------- ### Joining States using & in MrMustard Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Demonstrates how to combine multiple quantum states into a joint state using the bitwise AND operator (`&`), creating separable multi-mode states. ```python Coherent(x=1.0, y=1.0) & Coherent(x=2.0, y=2.0) # A separable two-mode coherent state s = SqueezedVacuum(r=1.0) s4 = s & s & s & s # four squeezed states ``` -------------------------------- ### Constructing a Cat State in MrMustard (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Shows how to create a cat state by superposing two coherent states using the `Coherent` state class and the `ket` method, normalizing the resulting state vector, and wrapping it in a `State` object for use within MrMustard. ```python cat_amps = Coherent(2.0).ket([20]) + Coherent(-2.0).ket([20]) cat_amps = cat_amps / np.linalg.norm(cat_amps) cat = State(ket=cat_amps) cat ``` -------------------------------- ### Joining States with And Operator (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Demonstrates how to combine multiple quantum states into a joint state using the bitwise AND operator &, creating separable multi-mode states. ```python Coherent(x=1.0, y=1.0) & Coherent(x=2.0, y=2.0) # A separable two-mode coherent state s = SqueezedVacuum(r=1.0) s4 = s & s & s & s # four squeezed states ``` -------------------------------- ### Applying Gates with Right Shift Operator (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Demonstrates applying a sequence of gates (Sgate, Dgate) to a Vacuum state using the right-shift operator >> in Mr Mustard. ```python displaced_squeezed = Vacuum(1) >> Sgate(r=0.5) >> Dgate(x=1.0) ``` -------------------------------- ### Applying a Squeezing Gate to a Cat State in MrMustard (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Illustrates the composition of states and gates in MrMustard by applying a single-mode squeezing gate (`Sgate`) to a previously constructed cat state using the `>>` operator, demonstrating the compatibility between different state representations and gate types. ```python cat >> Sgate(0.5) # squeezed cat ``` -------------------------------- ### Changing MrMustard Math Backend to TensorFlow Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Shows how to dynamically change the backend of the `mrmustard.math` module to TensorFlow using `math.change_backend`, affecting subsequent mathematical operations. ```python import mrmustard.math as math math.change_backend("tensorflow") math.cos(0.1) # tensorflow ``` -------------------------------- ### Accessing Subsystems with get_modes in MrMustard Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Shows how to extract specific modes or reorder modes from a multi-mode quantum state using the `get_modes` method. ```python joint = Coherent(x=1.0, y=1.0) & Coherent(x=2.0, y=2.0) joint.get_modes(0) # first mode joint.get_modes(1) # second mode swapped = joint.get_modes([1,0]) ``` -------------------------------- ### Optimize Symplectic and Euclidean Parameters - Mr Mustard - Python Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Initializes a new `Optimizer` instance. It then minimizes the `cost_fn_sympl` by optimizing both the Symplectic gate `G` (using the symplectic optimizer) and the Euclidean gate `D` (using Adam). ```python opt = Optimizer(symplectic_lr=0.1, euclidean_lr=0.01) opt.minimize(cost_fn_sympl, by_optimizing=[G,D]) # using Adam for D and the symplectic opt for G ``` -------------------------------- ### Comparing Transformations using == in MrMustard Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Illustrates the use of the equality operator (`==`) to compare quantum transformations (gates and circuits), showing that the order of applying an Attenuator and a Dgate can be commuted if parameters are adjusted. ```python >>> Dgate(np.sqrt(2)) >> Attenuator(0.5) == Attenuator(0.5) >> Dgate(1.0) True ``` -------------------------------- ### Using PNRDetector and Accessing Results in MrMustard Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Demonstrates applying a PNRDetector to a Gaussian state and accessing the unnormalized density matrix for specific measurement outcomes using indexing based on the measured photon counts. ```python results = Gaussian(3) << PNRDetector(efficiency = [0.9, 0.8], modes = [0,1]) results[2,3] # unnormalized dm of mode 2 conditioned on measuring 2 in mode 0 and 3 in mode 1 ``` -------------------------------- ### Applying Gates to Specific Modes (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Shows how to apply gates to individual or multiple specified modes using the getitem syntax ([]) after the gate object, combined with the right-shift operator >>. ```python D = Dgate(y=-0.4) S = Sgate(r=0.1, phi=0.5) state = Vacuum(2) >> D[1] >> S[0] # displacement on mode 1 and squeezing on mode 0 BS = BSgate(theta=1.1) state = Vacuum(3) >> BS[0,2] # applying a beamsplitter to modes 0 and 2 state = Vacuum(4) >> S[0,1,2] # applying the same Sgate in parallel to modes 0, 1 and 2 but not to mode 3 ``` -------------------------------- ### Optimize Euclidean Parameters - Mr Mustard - Python Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Initializes an `Optimizer` instance with specified learning rates for symplectic and euclidean parameters. It then minimizes the `cost_fn_eucl` by optimizing only the Euclidean gate `D` using the Adam optimizer. ```python opt = Optimizer(symplectic_lr=0.1, euclidean_lr=0.01) opt.minimize(cost_fn_eucl, by_optimizing=[D]) # using Adam for D ``` -------------------------------- ### Accessing Subsystems with get_modes (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Shows how to extract individual modes or reorder modes from a multi-mode quantum state object using the .get_modes() method. ```python joint = Coherent(x=1.0, y=1.0) & Coherent(x=2.0, y=2.0) joint.get_modes(0) # first mode joint.get_modes(1) # second mode swapped = joint.get_modes([1,0]) ``` -------------------------------- ### Include Reference File (Jinja2) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/module.rst Conditionally includes a reference file if the 'referencefile' variable is defined. This is typically used to include introductory text or additional documentation. ```Jinja2 {% if referencefile %} .. include:: {{ referencefile }} {% endif %} ``` -------------------------------- ### Initializing Fock State from Amplitudes (with buffer) in MrMustard Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Shows how to create a State object in Fock representation from a numpy array of amplitudes, including padding with zeros to implicitly define the cutoff. The resulting state can be used with gates. ```python my_amplitudes = np.array([0.5, 0.25, -0.5, 0.25, 0.25, 0.5, -0.25] + [0.0]*23) # notice the buffer my_state = State(ket=my_amplitudes) my_state >> Sgate(r=0.5) # just works ``` -------------------------------- ### Individual Method Documentation (Jinja2/reST) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/class.rst Iterates through the list of methods and generates an `automethod` directive for each one, pulling detailed documentation from the source code. ```Jinja2/reST {% for item in methods %} .. automethod:: {{ item }} {%- endfor %} ``` -------------------------------- ### Initialize Trainable Symplectic Gate - Mr Mustard - Python Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Initializes a `Ggate` with one mode, setting its symplectic parameters to be trainable. This gate will be included in the optimization process for the symplectic cost function. ```python G = Ggate(num_modes=1, symplectic_trainable=True) ``` -------------------------------- ### Initializing Fock State from Amplitudes (force cutoff) in MrMustard Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Presents an alternative method to initialize a State from amplitudes without padding, by explicitly setting the cutoff using the internal _cutoffs attribute. This state is also compatible with gates. ```python my_amplitudes = np.array([0.5, 0.25, -0.5, 0.25, 0.25, 0.5, -0.25]) # no buffer my_state = State(ket=my_amplitudes) my_state._cutoffs = [42] # force the cutoff my_state >> Sgate(r=0.5) # works too ``` -------------------------------- ### Methods Section Header & Summary (Jinja2/reST/HTML) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/class.rst Generates the HTML collapsible header for the Methods section and includes an `autosummary` directive for methods if they exist, providing a quick overview. ```Jinja2/reST/HTML {% block methods_documentation %} {% if methods %} .. raw:: html
{% block methods_summary %} {% if methods %} .. autosummary:: {% for item in methods %} ~{{ name }}.{{ item }} {%- endfor %} {% endif %} {% endblock %} ``` -------------------------------- ### HTML for Collapsible Methods Section Header Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary/class.rst Defines the HTML structure for the header of the collapsible methods section. Similar to the attributes header, it uses an anchor tag to trigger the collapse and includes an H2 heading with a rotatable icon. ```HTML
``` -------------------------------- ### Comparing States (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Shows how the equality operator == can be used to compare quantum states in Mr Mustard, demonstrating the comparison of a subsystem of a state resulting from a beamsplitter operation. ```python >>> bunched = (Coherent(1.0) & Coherent(1.0)) >> BSgate(np.pi/4) >>> bunched.get_modes(1) == Coherent(np.sqrt(2.0)) True ``` -------------------------------- ### Include Reference File and Set Module Name (Jinja2) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/class.rst Includes a reference file if specified and calculates the module path for documentation, defaulting to 'mm' if the module is top-level. ```Jinja2 {% if referencefile %} .. include:: {{ referencefile }} {% endif %} {% if module.split(".")[1:] | length >= 1 %} {% set mod = module.split(".")[1:] | join(".") %} {% set mod = "mm." + mod %} {% else %} {% set mod = "mm" %} {% endif %} ``` -------------------------------- ### Creating a Cat State in Fock Representation (Mr Mustard/Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md This code constructs a Cat state by superposing two coherent states with opposite amplitudes in the Fock basis up to a cutoff of 20. It normalizes the resulting state vector and creates a `State` object from it. Requires `numpy` and `mrmustard.lab`. ```python cat_amps = Coherent(2.0).ket([20]) + Coherent(-2.0).ket([20]) cat_amps = cat_amps / np.linalg.norm(cat_amps) cat = State(ket=cat_amps) cat ``` -------------------------------- ### Using PNR Detector (Single Mode Measurement) (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Shows how to use the PNRDetector with the left-shift operator << to measure a single mode of a Gaussian state. The result is an array of unnormalized density matrices for the remaining modes, conditioned on the measurement outcome. ```python results = Gaussian(2) << PNRDetector(efficiency = 0.9, modes = [0]) results[0] # unnormalized dm of mode 1 conditioned on measuring 0 in mode 0 results[1] # unnormalized dm of mode 1 conditioned on measuring 1 in mode 0 results[2] # unnormalized dm of mode 1 conditioned on measuring 2 in mode 0 # etc... ``` -------------------------------- ### Applying Transformations in Dual Sense (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Shows how the left-shift operator << can be used to apply transformations in a dual sense, demonstrating an equivalence between applying an attenuator left-shifted to a state and applying an amplifier right-shifted. ```python Attenuator(0.5) << Coherent(0.1, 0.2) == Coherent(0.1, 0.2) >> Amplifier(2.0) ``` -------------------------------- ### Applying a Sgate to a State using Right Shift (Mr Mustard/Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md This snippet shows how to apply a Squeeze gate (`Sgate`) with a squeezing parameter of 0.5 to a previously defined quantum state (`cat`) using the right-shift operator (`>>`). This operator is overloaded in Mr Mustard to represent gate application. ```python cat >> Sgate(0.5) ``` -------------------------------- ### Using PNR Detector (Multiple Mode Measurement) (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Demonstrates using the PNRDetector to measure multiple modes simultaneously. The result is a multi-dimensional array of unnormalized density matrices for the remaining modes, indexed by the measurement outcomes for each measured mode. ```python results = Gaussian(3) << PNRDetector(efficiency = [0.9, 0.8], modes = [0,1]) results[2,3] # unnormalized dm of mode 2 conditioned on measuring 2 in mode 0 and 3 in mode 1 # etc... ``` -------------------------------- ### Comparing States using == in MrMustard Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Shows how to use the equality operator (`==`) to compare two quantum states in MrMustard, illustrating that a bunched state created from two coherent states is equivalent to a single coherent state with a different amplitude. ```python >>> bunched = (Coherent(1.0) & Coherent(1.0)) >> BSgate(np.pi/4) >>> bunched.get_modes(1) == Coherent(np.sqrt(2.0)) True ``` -------------------------------- ### HTML for Collapsible Attributes Section Header Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary/class.rst Defines the HTML structure for the header of the collapsible attributes section. It includes an anchor tag that acts as the collapse trigger and contains an H2 heading with an icon that indicates the section's state. ```HTML
``` -------------------------------- ### Individual Attribute Documentation (Jinja2/reST) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/class.rst Iterates through the list of attributes and generates an `autoattribute` directive for each one, pulling detailed documentation from the source code. ```Jinja2/reST {% for item in attributes %} .. autoattribute:: {{ item }} {%- endfor %} ``` -------------------------------- ### Attributes Section Header & Summary (Jinja2/reST/HTML) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/class.rst Generates the HTML collapsible header for the Attributes section and includes an `autosummary` directive for attributes if they exist, providing a quick overview. ```Jinja2/reST/HTML {% block attributes_documentation %} {% if attributes %} .. raw:: html
{% block attributes_summary %} {% if attributes %} .. autosummary:: :nosignatures: {% for item in attributes %} ~{{ name }}.{{ item }} {%- endfor %} {% endif %} {% endblock %} ``` -------------------------------- ### Sphinx Automodule Directive (RST) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/module.rst Includes the Sphinx 'automodule' directive, which automatically documents the specified Python module ('fullname'). This directive is the primary way to pull in module-level documentation. ```Jinja2 .. automodule:: {{ fullname }} ``` -------------------------------- ### Performing a Measurement using Left Shift (Mr Mustard/Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md This snippet shows how to perform a measurement on a quantum state using the left-shift operator (`<<`). It applies a circuit (`X8`) to a 4-mode vacuum state and then performs a homodyne-like measurement on mode 2 by left-shifting a highly squeezed vacuum state onto it. The result (`leftover`) represents the remaining state conditioned on the measurement outcome. ```python leftover = Vacuum(4) >> X8 << SqueezedVacuum(r=10.0, phi=np.pi)[2] # a homodyne measurement of p=0.0 on mode 2 ``` -------------------------------- ### Collapse Header Script (HTML/JavaScript) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/class.rst Includes a JavaScript snippet that adds click functionality to elements with the 'collapse-header' class to toggle an 'up' class on their child icon, providing visual feedback for collapsing sections. ```HTML/JavaScript .. raw:: html ``` -------------------------------- ### Performing Measurements with Left Shift Operator (Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/README.md Demonstrates performing a measurement on a specific mode of a state after applying a circuit, using the left-shift operator << to represent "closing" the circuit with a detector/measurement. ```python leftover = Vacuum(4) >> X8 << SqueezedVacuum(r=10.0, phi=np.pi)[2] # a homodyne measurement of p=0.0 on mode 2 ``` -------------------------------- ### Jinja2 Template for Python Module Documentation Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary/module.rst This template generates a reStructuredText file for a Python module. It includes directives for Sphinx's automodule, and uses autosummary to list classes, functions, and exceptions found within the module, organized under appropriate rubrics. ```Jinja2 {{ fullname | replace("mrmustard", "mm") | escape | underline}} .. automodule:: {{ fullname }} {% block classes %} {% if classes %} .. rubric:: Classes .. autosummary:: :toctree: {% for item in classes %} {{ item }} {%- endfor %} {% endif %} {% endblock %} {% block functions %} {% if functions %} .. rubric:: Functions .. autosummary:: :toctree: {% for item in functions %} {{ item }} {%- endfor %} {% endif %} {% endblock %} {% block exceptions %} {% if exceptions %} .. rubric:: Exceptions .. autosummary:: {% for item in exceptions %} {{ item }} {%- endfor %} {% endif %} {% endblock %} ``` -------------------------------- ### Document Exceptions Block (Jinja2/RST) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/module.rst A Jinja2 block that conditionally generates documentation for exceptions. If the 'exceptions' list is not empty, it adds an RST rubric 'Exceptions' and an 'autosummary' directive listing each exception item. ```Jinja2 {% block exceptions %} {% if exceptions %} .. rubric:: Exceptions .. autosummary:: {% for item in exceptions %} {{ item }} {%- endfor %} {% endif %} {% endblock %} ``` -------------------------------- ### Document Classes Block (Jinja2/RST) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/module.rst A Jinja2 block that conditionally generates documentation for classes. If the 'classes' list is not empty, it adds an RST rubric 'Classes' and an 'autosummary' directive listing each class item. ```Jinja2 {% block classes %} {% if classes %} .. rubric:: Classes .. autosummary:: {% for item in classes %} {{ item }} {%- endfor %} {% endif %} {% endblock %} ``` -------------------------------- ### Class Header and Autoclass Directive (reST) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/class.rst Generates the reStructuredText header for the class documentation and includes the main `autoclass` directive with inheritance display. ```reStructuredText {{ mod }}.{{ objname }} ={% for i in range(mod|length) %}={% endfor %}{{ underline }} .. currentmodule:: {{ module }} .. autoclass:: {{ objname }} :show-inheritance: ``` -------------------------------- ### Document Functions Block (Jinja2/RST) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/module.rst A Jinja2 block that conditionally generates documentation for functions. If the 'functions' list is not empty, it adds an RST rubric 'Functions' and an 'autosummary' directive listing each function item. ```Jinja2 {% block functions %} {% if functions %} .. rubric:: Functions .. autosummary:: {% for item in functions %} {{ item }} {%- endfor %} {% endif %} {% endblock %} ``` -------------------------------- ### Close Methods Section Div (HTML) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/class.rst Closes the HTML div element that wraps the method documentation details, completing the collapsible section. ```HTML .. raw:: html
``` -------------------------------- ### Generate Sphinx Autodoc Directives (Jinja2) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/base.rst This template snippet generates reStructuredText directives for Sphinx autodoc. It conditionally includes a reference file, calculates the appropriate module prefix ('mm' or 'mm.submodule') based on the 'module' variable, prints the object name with an underline, sets the current module, and finally generates the 'auto' directive (e.g., 'automodule', 'autoclass', 'autofunction') for the specified object. ```Jinja2 {% if referencefile %} .. include:: {{ referencefile }} {% endif %} {% if module.split(".")[1:] | length >= 1 %} {% set mod = module.split(".")[1:] | join(".") %} {% set mod = "mm." + mod %} {% else %} {% set mod = "mm" %} {% endif %} {{ mod }}.{{ objname }} ={% for i in range(mod|length) %}={% endfor %}{{ underline }} .. currentmodule:: {{ module }} .. auto{{ objtype }}:: {{ objname }} ``` -------------------------------- ### Filter __init__ Method (Jinja2) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/class.rst Removes the `__init__` method from the list of methods to be documented if it exists, preventing it from being included in the generated documentation sections. ```Jinja2 {% if '__init__' in methods %} {% set caught_result = methods.remove('__init__') %} {% endif %} ``` -------------------------------- ### Using PNRDetector for Measurement (Mr Mustard/Python) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md This snippet shows how to perform a photon number resolving (PNR) measurement on a Gaussian state using the `PNRDetector`. The detector is applied to mode 0 with a specified efficiency. The result is an array where each element is the unnormalized density matrix of the remaining modes (mode 1 in this case), conditioned on a specific measurement outcome (0, 1, 2, etc.) on the measured mode. ```python results = Gaussian(2) << PNRDetector(efficiency = 0.9, modes = [0]) results[0] # unnormalized dm of mode 1 conditioned on measuring 0 in mode 0 results[1] # unnormalized dm of mode 1 conditioned on measuring 1 in mode 0 results[2] # unnormalized dm of mode 1 conditioned on measuring 2 in mode 0 ``` -------------------------------- ### Close Attributes Section Div (HTML) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/class.rst Closes the HTML div element that wraps the attribute documentation details, completing the collapsible section. ```HTML .. raw:: html
``` -------------------------------- ### Generate Section Title (Jinja2/RST) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/module.rst Generates a section title using the determined module name ('mod') and object name ('objname'). It also creates an underline of '=' characters based on the length of the module name, followed by a variable 'underline'. This formats the title according to RST conventions. ```Jinja2 {{ mod }}.{{ objname }} ={% for i in range(mod|length) %}={% endfor %}{{ underline }} ``` -------------------------------- ### JavaScript for Toggling Collapse Icon Rotation Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary/class.rst Attaches a click event listener to all elements with the class 'collapse-header'. When clicked, it finds the icon ( tag) within the header's H2 element and toggles the 'up' class, typically used to rotate the icon. ```JavaScript $(".collapse-header").click(function () { $(this).children('h2').eq(0).children('i').eq(0).toggleClass("up"); }) ``` -------------------------------- ### Define Symplectic Cost Function - Mr Mustard - Python Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/introduction/basic_reference.md Defines a cost function `cost_fn_sympl` that calculates the infidelity between a state transformed by a trainable Symplectic gate (`Ggate`) and Euclidean gates (Displacement `D` and Loss `L`) and a target Displaced Squeezed state. This function takes no arguments and returns a scalar cost value (1 - fidelity). ```python def cost_fn_sympl(): state_out = Vacuum(1) >> G >> D >> L return 1 - fidelity(state_out, DisplacedSqueezed(r=0.3, phi=1.1, x=0.4, y=-0.2)) ``` -------------------------------- ### Set Module Name Variable (Jinja2) Source: https://github.com/xanaduai/mrmustard/blob/develop/doc/_templates/autosummary_core/module.rst Sets the 'mod' variable based on the 'module' variable. If 'module' contains submodules, it extracts them and prepends 'mm.'; otherwise, it sets 'mod' to 'mm'. This prepares the module name for display and use in directives. ```Jinja2 {% if module.split(".")[1:] | length >= 1 %} {% set mod = module.split(".")[1:] | join(".") %} {% set mod = "mm." + mod %} {% else %} {% set mod = "mm" %} {% endif %} ```