### Install Perceval from GitHub Source: https://github.com/quandela/perceval/blob/main/README.md Clone the Perceval repository from GitHub and install it locally. Use `pip install -e .` for development. ```bash git clone https://github.com/quandela/Perceval pip install . # Or for developers: pip install -e . ``` -------------------------------- ### Clifford2017Backend Usage Example Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/backends/clifford2017.rst This example demonstrates how to instantiate and use the Clifford2017Backend to generate samples from a circuit. ```APIDOC ## Clifford2017Backend Usage Example ### Description This example demonstrates how to instantiate and use the Clifford2017Backend to generate samples from a circuit. ### Code ```python import perceval as pcvl c = pcvl.BS() backend = pcvl.Clifford2017Backend() backend.set_circuit(c) backend.set_input_state(pcvl.BasicState([1, 0])) print(backend.samples(10)) # Results may vary ``` ### Output Example ``` [ |1,0>, |0,1>, |0,1>, |0,1>, |1,0>, |0,1>, |1,0>, |0,1>, |0,1>, |0,1> ] ``` ``` -------------------------------- ### SLAPBackend Usage Example Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/backends/slap.rst This example demonstrates how to initialize and use the SLAPBackend to compute all output probabilities for a given unitary circuit and input state. ```APIDOC ## SLAPBackend Usage Example ### Description This example demonstrates how to initialize and use the SLAPBackend to compute all output probabilities for a given unitary circuit and input state. ### Method This is a usage example, not a direct API call. ### Endpoint N/A ### Parameters N/A ### Request Example ```python import perceval as pcvl c = pcvl.Unitary(pcvl.Matrix.random_unitary(4)) backend = pcvl.SLAPBackend() backend.set_circuit(c) backend.set_input_state(pcvl.BasicState([1, 0, 1, 0])) print(backend.all_prob()) # Results are random due to random unitary ``` ### Response #### Success Response (Output) ``` [0.22615963112684112, 0.059932460984674245, 0.11409780074515555, 0.05869159993147518, 0.06610964358209905, 0.1384083292588432, 0.1266841040718083, 0.08819140959446393, 0.05777776134512867, 0.0639472593595116] ``` #### Response Example (See Success Response above, values are random) ``` -------------------------------- ### Example Usage Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/utils/stategenerator.rst Illustrates how to instantiate and use the StateGenerator class to create different quantum states. ```APIDOC >>> from perceval import StateGenerator, Encoding >>> sg = StateGenerator(Encoding.DUAL_RAIL) >>> sg.bell_state("phi+") 0.707*|1,0,1,0>+0.707*|0,1,0,1> >>> sg.dicke_state(2) 0.408*|1,0,0,1,0,1,1,0>+0.408*|0,1,1,0,1,0,0,1>+0.408*|0,1,1,0,0,1,1,0>+0.408*|0,1,0,1,1,0,1,0>+0.408*|1,0,0,1,1,0,0,1>+0.408*|1,0,1,0,0,1,0,1> ``` -------------------------------- ### SLOSBackend Usage Example Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/backends/slos.rst This example demonstrates how to use the SLOSBackend to compute the probability distribution of a given circuit and input state. ```APIDOC ## SLOSBackend Usage Example ### Description This example demonstrates how to use the SLOSBackend to compute the probability distribution of a given circuit and input state. ### Method ```python import perceval as pcvl # Define a circuit c = pcvl.Circuit(4) // pcvl.BS() // (2, pcvl.BS()) # Instantiate the SLOSBackend backend = pcvl.SLOSBackend() # Set the circuit and input state backend.set_circuit(c) backend.set_input_state(pcvl.BasicState([1, 0, 1, 0])) # Compute and print the probability distribution print(backend.prob_distribution()) ``` ### Response Example ```json { "|1,0,1,0>": 0.2500000000000001, "|1,0,0,1>": 0.2500000000000001, "|0,1,1,0>": 0.2500000000000001, "|0,1,0,1>": 0.2500000000000001 } ``` ``` -------------------------------- ### Create and Configure an Experiment Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/components/experiment.rst Demonstrates how to create an experiment with a specified number of modes, a noise model, and add components to it. This is useful for defining a simulation setup. ```python import perceval as pcvl e = pcvl.Experiment(2, noise=pcvl.NoiseModel(0.8), name="my experiment").add(0, pcvl.BS()) e.add_herald(0, 1) p = pcvl.Processor("SLOS", e) rp = pcvl.RemoteProcessor("sim:slos").add(e) ``` -------------------------------- ### Example QUBO Hamiltonian Generation Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/QUBO.ipynb This example demonstrates how to use the `graph_to_hamiltonian` function to generate a QUBO Hamiltonian for a specific 5-edge graph. It prints the resulting Hamiltonian matrix. ```python """example: our 5-edge graph""" # start,a,b,finish -> 0,1,2,3 G1 = np.array([[0,2,1,0], [0,0,3,2], [0,3,0,4], [0,0,0,0]]) # weights associated to all possible paths G1_s = 0 # start index G1_f = 3 # finish index H_example = graph_to_hamiltonian(G1, G1_s, G1_f) print(H_example) ``` -------------------------------- ### FFCircuitProvider Example Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/components/feed_forward_configurator.rst Demonstrates how to use FFCircuitProvider to link measurements to circuits or processors. This configurator can use any circuit or processor matching the default circuit size if all parameters are numerical. ```python import perceval as pcvl p = pcvl.Processor("SLOS", 4) c = pcvl.FFCircuitProvider(1, offset=1, default_circuit=pcvl.Circuit(2), name="FFCircuitProvider Example") c.add_configuration([1], pcvl.BS()) p.add(0, pcvl.Detector.threshold()) p.add(0, c) ``` -------------------------------- ### Instantiate Scaleway Session Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/providers.rst Import the library and Scaleway, provide credentials, and choose a platform. Sessions can be started and stopped manually or managed with a 'with' block. ```python import perceval as pcvl import perceval.providers.scaleway as scw PROJECT_ID = "your-scaleway-project-id" TOKEN = "your-scaleway-api-key" PLATFORM_NAME = "EMU-SAMPLING-L4" # For emulated QPU # PLATFORM_NAME = "QPU-BELENOS-12PQ" # For real QPU session = scw.Session(platform_name=PLATFORM_NAME, project_id=PROJECT_ID, token=TOKEN) session.start() /* * Session scope */ session.stop() ``` ```python with scw.Session(platform_name=PLATFORM_NAME, project_id=PROJECT_ID, token=TOKEN) as session: # # Session scope # ``` -------------------------------- ### Logger Configuration Example Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/utils/logging.rst Configure logger by enabling file logging and setting specific levels for channels like 'resources' and 'general'. ```python from perceval.utils.logging import get_logger, channel, level logger = get_logger() logger.enable_file() logger.set_level(level.info, channel.resources) logger.set_level(level.err, channel.general) ``` -------------------------------- ### Import Perceval and Utilities Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Graph_States_Tutorial.ipynb Imports necessary libraries for quantum circuit simulation and graph state generation. Ensure these are installed before running. ```python import math import perceval as pcvl import networkx as nx from perceval.utils import StateGenerator, Encoding ``` -------------------------------- ### GenericInterferometer Initialization Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/components/generic_interferometer.rst Example of how to define a generic interferometer with a specified number of modes, a component layout function, and a shape. ```APIDOC ## GenericInterferometer ### Description Initializes a generic interferometer. ### Parameters #### Path Parameters - **nmodes** (int) - Required - The number of modes in the interferometer. - **component_layout** (function) - Required - A function that takes an integer `i` and returns a component layout. - **shape** (InterferometerShape, optional) - The shape of the interferometer. Defaults to `InterferometerShape.DEFAULT`. ### Example ```python import perceval as pcvl from perceval.components import BS, PS c = pcvl.GenericInterferometer(8, lambda i: BS() // PS(pcvl.P("φ%d" % i)), shape=pcvl.InterferometerShape.TRIANGLE) pcvl.pdisplay(c) ``` ``` -------------------------------- ### Simplify Circuit Example Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/utils_algorithms/simplify.rst Demonstrates how to use the simplify function to reduce the number of components in a circuit. Imports necessary classes from perceval.utils.algorithms.simplification and perceval. ```python from perceval.utils.algorithms.simplification import simplify from perceval import Circuit, PERM, PS circuit = Circuit(6) // PERM([3,2,1,0]) // (1, PERM([4,1,3,2,0])) // PS(phi=0.6) // PS(phi=0.2) print(circuit.ncomponents()) simplified_circuit = simplify(circuit, display = False) print(simplified_circuit.ncomponents()) ``` -------------------------------- ### Setting up a Processor for CNOT Gate Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Quantum_teleportation_feed_forward.ipynb Initializes a Perceval Experiment with 6 modes and adds a postprocessed CNOT gate and a Hadamard gate. This setup is for circuits involving feed-forward operations. ```python experiment = Experiment(6) experiment.add(0, catalog["postprocessed cnot"].build_processor()) experiment.add(0, pcvl.BS.H()); ``` -------------------------------- ### Batch Job Setup with Sampler Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/algorithm/sampler.rst Configure a batch job by defining a circuit with variable parameters. Add individual iterations or a list of iterations, specifying circuit parameters, input state, and photon detection filters for each. This optimizes job management and reduces overhead, especially for cloud-based computations. ```python >>> c = BS() // PS(phi=pcvl.P("my_phase")) // BS() # Define a circuit containing "my_phase" variable >>> processor = pcvl.RemoteProcessor("qpu:altair", token_qcloud) >>> processor.set_circuit(c) >>> sampler = Sampler(processor) >>> sampler.add_iteration(circuit_params={"my_phase": 0.1}, >>> input_state=BasicState([1, 1]), >>> min_detected_photons=1) # You can add a single iteration >>> sampler.add_iteration_list([ >>> {"circuit_params": {"my_phase": i/2}, >>> "input_state": BasicState([1, 1]), >>> "min_detected_photons": 1 >>> } for i in range(1, 6) >>> ]) # Or you can add multiple iterations at once >>> sample_count = sampler.sample_count(10000) ``` -------------------------------- ### PersistentData Usage Example Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/utils/persistent_data.rst Demonstrates how to initialize PersistentData, write a file, read it back, and then delete it. The default storage location is within the user's home directory. ```python >>> import perceval as pcvl >>> pdata = pcvl.PersistentData() >>> pdata.write_file("my_file.txt", "my_data", pcvl.FileFormat.TEXT) >>> print(pdata.read_file("my_file.txt", pcvl.FileFormat.TEXT)) my_data >>> pdata.delete_file("my_file.txt") ``` -------------------------------- ### Building a Circuit with Symbolic Components Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Circuit_Tutorial.ipynb Constructs a circuit with multiple components, including phase shifters with symbolic parameters. This demonstrates how to define complex optical setups programmatically. ```python bs_rx_circuit=pcvl.Circuit(2) // (0, PS(phi=pcvl.P("phi_tl"))) // (1, PS(phi=pcvl.P("phi_bl"))) // BS(theta=pcvl.P('theta')) // (0, PS(phi=pcvl.P("phi_tr"))) // (1, PS(phi=pcvl.P("phi_br"))) pcvl.pdisplay(bs_rx_circuit.U) pcvl.pdisplay(bs_rx_circuit) ``` -------------------------------- ### Accessing a component from the catalog Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/components/catalog.rst Use the catalog as a dictionary to retrieve a component by its key. This example shows how to get the 'heralded cz' gate. ```Python from perceval import catalog catalog['heralded cz'] ``` -------------------------------- ### Initialize and Use NaiveApproxBackend Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/backends/naive_approx.rst Demonstrates initializing the NaiveApproxBackend with a specified number of iterations, setting a circuit, input state, and calculating the probability with a confidence interval. Use this backend when only a few output probabilities are needed with many photons. ```python import perceval as pcvl circuit_size = 60 n_photons = 30 backend = pcvl.NaiveApproxBackend(100_000_000) # Number of iterations; higher values reduce the error bound backend.set_circuit(pcvl.Unitary(pcvl.Matrix.random_unitary(circuit_size))) input_state = pcvl.BasicState([1]*n_photons + [0]*(circuit_size-n_photons)) backend.set_input_state(input_state) interval = backend.probability_confidence_interval(BasicState([1]*n_photons + [0]*(circuit_size-n_photons))) print(f"Probability in {interval}") ``` -------------------------------- ### Initialize and Use Simulator Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/simulators/simulator.rst Demonstrates initializing a Simulator with a backend, setting a circuit, configuring selection and precision, and performing probability calculations. ```python import perceval as pcvl sim = pcvl.Simulator(pcvl.SLOSBackend()) sim.set_circuit(pcvl.BS()) # Now, sim holds a 2 modes circuit # Physical and logical selection sim.set_selection(min_detected_photons_filter = 2) # Other fields: heralds (accounting only the output), postselect sim.set_precision(1e-6) # Relative precision; only input states having more than this times the highest input prob will be computed # Computation state by state print(sim.prob_amplitude(pcvl.BasicState("|{_:0}, {_:1}>"), pcvl.BasicState("|{_:0}, {_:1}>"))) # No selection # (0.5000000000000001+0j) # Compute everything print(sim.probs(pcvl.BasicState([2, 1]))) # Computes the BSD with selection; no performance and no automatic usage of masks # { # |1,2>: 0.12500000000000003 # |3,0>: 0.375 # |2,1>: 0.12500000000000003 # |0,3>: 0.375 # } # Compute everything from anything svd = pcvl.SVDistribution({pcvl.StateVector([1, 1]) + 0.5j * pcvl.StateVector([0, 2]): 0.7, pcvl.StateVector([1, 0]): 0.3}) print(sim.probs_svd(svd, [pcvl.Detector.threshold()] * 2)) # Can also simulate detectors # {'results': BSDistribution(, {|1,1>: 1.0}), 'physical_perf': 0.06999999999999998, 'logical_perf': 1.0000000000000004} ``` -------------------------------- ### Initialize and Sample with Clifford2017Backend Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/backends/clifford2017.rst Demonstrates how to initialize the Clifford2017Backend, set a circuit and input state, and then generate samples. Results may vary due to the probabilistic nature of sampling. ```python import perceval as pcvl c = pcvl.BS() backend = pcvl.Clifford2017Backend() backend.set_circuit(c) backend.set_input_state(pcvl.BasicState([1, 0])) print(backend.samples(10)) # Results may vary ``` -------------------------------- ### Install Perceval Source: https://github.com/quandela/perceval/blob/main/docs/source/getting_started.rst Install Perceval and its dependencies using pip. Ensure you are using a supported Python version. ```bash pip install perceval-quandela ``` -------------------------------- ### Initialize and Configure Simulator Backend Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Graph_States_Tutorial.ipynb Sets up the 'SLOS' backend for simulating the quantum circuit and assigns the previously defined circuit to it. ```python # Simulator backend = pcvl.BackendFactory.get_backend("SLOS") backend.set_circuit(c_graph_lin) ``` -------------------------------- ### Install Perceval using PIP Source: https://github.com/quandela/perceval/blob/main/README.md Install or upgrade Perceval using pip. Ensure your Python version is between 3.10 and 3.14. ```bash pip install --upgrade pip pip install perceval-quandela ``` -------------------------------- ### Listing and Using Backends Source: https://context7.com/quandela/perceval/llms.txt Demonstrates how to list available backends and use them for circuit simulation, including exact probability distributions and fast boson sampling. ```APIDOC ## Listing Available Backends ### Description Lists the names of all available simulation backends. ### Method ```python print(BACKEND_LIST.keys()) ``` ### Response Example ``` dict_keys(['CliffordClifford2017', 'MPS', 'Naive', 'NaiveApprox', 'SLAP', 'SLOS']) ``` ## Using Specific Backends ### Description Shows how to instantiate and use different backends like SLOS for exact probabilities and CliffordClifford2017 for boson sampling. ### SLOS Backend Example ```python import perceval as pcvl # Use SLOS for exact probability distributions (up to ~20 photons/modes) p_slos = pcvl.Processor("SLOS", pcvl.BS()) p_slos.with_input(pcvl.BasicState([1, 1])) print(p_slos.probs()["results"]) ``` ### CliffordClifford2017 Backend Example ```python import perceval as pcvl # Use CliffordClifford2017 for fast boson sampling (up to ~30 photons) p_cc = pcvl.Processor("CliffordClifford2017", pcvl.BS()) p_cc.with_input(pcvl.BasicState([1, 1])) print(p_cc.available_commands) # ['samples'] ``` ### MPS Backend Example ```python import perceval as pcvl # Use MPS (tensor network, approximate, good for large circuits) p_mps = pcvl.Processor("MPS", pcvl.BS()) p_mps.with_input(pcvl.BasicState([1, 1])) print(p_mps.probs()["results"]) ``` ### NaiveApprox Backend Example ```python import perceval as pcvl # Use NaiveApprox for single-output probability with error bounds on large photon counts p_na = pcvl.Processor("NaiveApprox", pcvl.BS()) p_na.with_input(pcvl.BasicState([1, 1])) print(p_na.probs()["results"]) ``` ## Direct Backend Instantiation ### Description Instantiates a backend directly and queries probability amplitudes. ### Method ```python from perceval import BackendFactory backend = BackendFactory.get_backend("Naive") c = pcvl.BS() backend.set_circuit(c) amp = backend.prob_amplitude(pcvl.BasicState([1, 1]), pcvl.BasicState([2, 0])) print(amp) # complex probability amplitude ``` ``` -------------------------------- ### Configure and Initialize Perceval Backend Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Differential_equation_resolution.ipynb Sets up the Perceval backend, defines a random unitary for the circuit, and preprocesses the input state. ```python backend = pcvl.BackendFactory().get_backend("SLOS") backend.set_circuit(pcvl.Unitary(pcvl.Matrix.random_unitary(m))) backend.preprocess([input_state]) pcvl.pdisplay(c) ``` -------------------------------- ### MPSBackend Initialization and Usage Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/backends/mps.rst Demonstrates how to initialize the MPSBackend with a cutoff, set a circuit, set an input state, and compute the probability distribution. ```APIDOC ## MPSBackend Initialization and Usage ### Description This example shows how to instantiate the `MPSBackend`, configure it with a circuit and input state, and then retrieve the probability distribution of the output. ### Method ```python backend = pcvl.MPSBackend(cutoff=3) backend.set_circuit(c) backend.set_input_state(pcvl.BasicState([1, 0, 1, 0])) print(backend.prob_distribution()) ``` ### Parameters - `cutoff` (int): The cutoff number for matrix dimensions, influencing accuracy and computation cost. - `c` (pcvl.Circuit): The quantum circuit to simulate. - `input_state` (pcvl.BasicState): The initial state of the system. ### Response Example ```json { "|1,1,0,0>": 0.12500000000000003, "|1,0,1,0>": 0.07775105849101832, "|1,0,0,1>": 0.29017090063073997, "|0,2,0,0>": 0.12500000000000003, "|0,1,1,0>": 0.020833333333333356, "|0,1,0,1>": 0.07775105849101838, "|0,0,2,0>": 0.12500000000000006, "|0,0,1,1>": 0.12500000000000003 } ``` ``` -------------------------------- ### Initialize Boson Sampling Simulator Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Boson_Bunching.ipynb Sets up the boson sampling simulator with a specified backend. Requires `SLOSBackend` and `Simulator` to be defined. ```python # simulating boson sampling simulator = Simulator(SLOSBackend()) simulator.set_circuit(circuit) ``` -------------------------------- ### Get Logger Instance Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/utils/logging.rst Import and retrieve the logger instance. A logger is created upon the first import of Perceval. ```python from perceval.utils import get_logger ``` -------------------------------- ### Compute All Output Probabilities with SLAPBackend Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/backends/slap.rst Demonstrates how to set up a circuit and input state with the SLAPBackend and compute all output probabilities. Results are random due to the random unitary used. ```python import perceval as pcvl c = pcvl.Unitary(pcvl.Matrix.random_unitary(4)) backend = pcvl.SLAPBackend() backend.set_circuit(c) backend.set_input_state(pcvl.BasicState([1, 0, 1, 0])) print(backend.all_prob()) # Results are random due to random unitary ``` -------------------------------- ### Import Necessary Packages Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/QUBO.ipynb Imports required libraries for Perceval, numerical operations, optimization, and plotting. Ensure these are installed before running. ```python import math import perceval as pcvl from perceval.components import PS, BS, GenericInterferometer import numpy as np from scipy.optimize import minimize import matplotlib.pyplot as plt plt.rcdefaults() ``` -------------------------------- ### LOv Rewriting Rule Output Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/LOv_rewriting_rules.ipynb Example output from matching LOv patterns during the rewriting process. This indicates which patterns are being matched. ```text matching pattern pattern3 matching pattern pattern4 matching pattern pattern1 matching pattern pattern3 matching pattern pattern4 ``` -------------------------------- ### Heralding and Logical Performance Computation Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Computation_Tutorial.ipynb Example of setting up heralding and computing logical performance. Heralded modes are excluded from the `min_detected_photons_filter`. ```python circuit = Circuit(3) // BS() // (1, BS()) // BS() p = Processor("SLOS", circuit) p.add_herald(2, 0) # Third mode is heralded (0 photon in, 0 photon expected out) p.min_detected_photons_filter(1) # Only non-heralded modes must be taken into account in this filter # Enable the computation of logical performance p.compute_physical_logical_perf(True) # After a mode is heralded, you must not take it into account when setting an input to the processor p.with_input(pcvl.BasicState([1, 0])) sampler = Sampler(p) probs = sampler.probs() print("With herald only") print("Logical perf =", probs['logical_perf']) print(probs['results']) ``` -------------------------------- ### Direct Backend Instantiation and Probability Amplitude Query Source: https://context7.com/quandela/perceval/llms.txt Shows how to directly instantiate a backend using `BackendFactory`, set a circuit, and then query the probability amplitude for a specific input and output state. This method provides fine-grained control over simulation parameters. ```python # Direct backend instantiation and probability amplitude query backend = BackendFactory.get_backend("Naive") c = pcvl.BS() backend.set_circuit(c) amp = backend.prob_amplitude(pcvl.BasicState([1, 1]), pcvl.BasicState([2, 0])) print(amp) # complex probability amplitude ``` -------------------------------- ### Use NaiveApprox Backend for Single-Output Probabilities Source: https://context7.com/quandela/perceval/llms.txt Demonstrates the 'NaiveApprox' backend for calculating single-output probabilities with error bounds, particularly useful for scenarios involving a large number of photons. The Processor is set up with the backend and circuit, and the input state is defined. ```python # Use NaiveApprox for single-output probability with error bounds on large photon counts p_na = pcvl.Processor("NaiveApprox", pcvl.BS()) p_na.with_input(pcvl.BasicState([1, 1])) print(p_na.probs()["results"]) ``` -------------------------------- ### Set and Get Post-Selection Function Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/components/processor.rst Applies a post-selection filter to a Processor using a string representation of the condition. The post-selection function is then retrieved. ```python >>> p.set_postselection(pcvl.PostSelect("[0, 1] == 2")) >>> p.post_select_fn [0, 1] == 2 ``` -------------------------------- ### RemoteProcessor Initialization Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/runtime/remote_processor.rst Demonstrates how to initialize a RemoteProcessor with a platform name and an access token. It also shows how to query the available commands for a given remote platform. ```APIDOC ## RemoteProcessor Initialization ### Description Initialize a RemoteProcessor to interact with a remote platform, such as a simulator or a QPU. You can specify the platform name and provide an access token for authentication. After initialization, you can inspect the `available_commands` property to understand what operations the remote platform supports. ### Usage ```python # Example with a specific platform and token remote_simulator = RemoteProcessor("platform:name", "YOUR_TOKEN") # Example querying available commands remote_simulator = RemoteProcessor("qpu:belenos") print(remote_simulator.available_commands) # Expected output: ['sample_count', 'samples'] ``` ### Parameters - **platform** (str): The identifier for the remote platform (e.g., "sim:slos", "qpu:belenos"). - **token** (str, optional): The access token for authentication. If not provided, it might be inferred from the environment or configuration. - **m** (int, optional): Number of modes for the processor. If not specified, it is inferred from the first added component. - **noise** (NoiseModel, optional): A noise model to apply to the remote computation. ### Methods - **RemoteProcessor(platform, token=None, m=None, noise=None, ...)**: Constructor for the RemoteProcessor. - **RemoteProcessor.from_local_processor(local_processor, platform, token=None, ...)**: Creates a RemoteProcessor by converting a local Processor. ### Properties - **available_commands** (list[str]): A list of commands that the remote platform natively supports. - **specs** (dict): Platform-specific specifications that must be fulfilled for a job to be completed. - **constraints** (dict): Similar to specs, detailing platform constraints. - **performance** (dict): Information about the performance characteristics of the remote source. ``` -------------------------------- ### Prepare Local Sampler Job Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/algorithm/index.rst Prepares a sampling job to run locally on a specified processor. The computation is not started until the job is executed. ```python from perceval import Processor, BasicState from perceval.algorithm import Sampler local_p = Processor("CliffordClifford2017", pcvl.BS()) local_p.with_input(BasicState('|1,1>')) sampler = Sampler(local_p) local_sample_job = sampler.sample_count ``` -------------------------------- ### Set up VQA parameters and circuit Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/VQA_Tutorial.ipynb Initializes VQA parameters, defines the input and output states, and creates a generic interferometer circuit with parameterized components. ```python # Data n = 4 input_state = BasicState([1]*n) output_to_max = BasicState([n]+[0]*(n-1)) backend = SLOSBackend() # We create a generic interferometer (variable parameters make it universal - i.e. it can implement any unitary transformation) circuit = GenericInterferometer(n, lambda i: BS(theta=Parameter(f"theta{i}"), phi_tr=Parameter(f"phi_tr{i}")), phase_shifter_fun_gen=lambda i: PS(phi=Parameter(f"phi{i}"))) param_circuit = circuit.get_parameters() params_init = [random()*np.pi for _ in param_circuit] pdisplay(circuit) ``` -------------------------------- ### NaiveBackend Methods Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/backends/naive.rst This section details the methods available for the NaiveBackend, including setting the circuit, input state, and computing probability amplitudes. ```APIDOC ## NaiveBackend Methods ### `set_circuit(circuit)` Sets the quantum circuit to be simulated by the backend. ### `set_input_state(state)` Sets the initial input state for the simulation. ### `prob_amplitude(state)` Computes and returns the probability amplitude for a given output state. #### Parameters - **state** (pcvl.BasicState): The desired output state for which to compute the probability amplitude. #### Returns - **complex**: The probability amplitude of the specified output state. ``` -------------------------------- ### ProcessTomography Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/algorithm/tomography.rst Represents a process tomography experiment. This class likely handles the setup, execution, and data processing for reconstructing a quantum process. ```APIDOC ## ProcessTomography This class is used for performing process tomography. ### Methods (Members are documented in the source code.) ``` -------------------------------- ### StateTomography Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/algorithm/tomography.rst Represents a state tomography experiment. This class likely handles the setup, execution, and data processing for reconstructing a quantum state. ```APIDOC ## StateTomography This class is used for performing state tomography. ### Methods (Members are documented in the source code.) ``` -------------------------------- ### Create and Inspect BasicState Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/utils/states.rst Demonstrates creating a FockState using BasicState factory and accessing its properties like number of photons and modes. Also shows basic tensor product operation. ```python import perceval as pcvl # Create a two-mode FockState with no photon in the 1st mode, and 1 photon in the 2nd mode. bs = pcvl.BasicState("|0,1>") print(bs) # Prints out the created Fock state bs.n # Displays the number of photons of the created Fock state bs.m # Displays the number of modes of the created Fock state bs[0] # Displays the number of photons in the first mode of the created Fock state ( note that the counter of the number of modes starts at 0 and ends at m-1 for an m-mode Fock state) print(pcvl.BasicState([0,1])*pcvl.BasicState([2,3])) # Tensors the |0,1> and |2,3> Fock states, and prints out the result (the Fock state |0,1,2,3>) ``` -------------------------------- ### Processor Simulation with Noise and Filters Source: https://context7.com/quandela/perceval/llms.txt Sets up a Processor with a circuit, noise model, and input state, then performs exact probability calculations and applies filters. Also shows how to add heralds and post-selection. ```python import perceval as pcvl from perceval.algorithm import Sampler # Hong-Ou-Mandel effect with noisy source input_state = pcvl.BasicState("|1,1>") circuit = pcvl.BS() noise_model = pcvl.NoiseModel(transmittance=0.05, indistinguishability=0.85) p = pcvl.Processor("SLOS", circuit, noise=noise_model) p.min_detected_photons_filter(1) # Accept outputs with at least 1 photon p.with_input(input_state) # Exact probabilities via strong simulation (SLOS) result = p.probs() print(result["results"]) # BSDistribution: {|2,0>: 0.012, |0,2>: 0.012, |1,0>: 0.487, |0,1>: 0.487, |1,1>: 0.002} print(result["global_perf"]) # Probability of passing the photon filter # Heralded CNOT gate from catalog from perceval import catalog p2 = pcvl.Processor("SLOS", 4) cnot = catalog["heralded cnot"].build_processor() p2.add(0, cnot) p2.add(2, cnot) # Add post-selection condition p.set_postselection(pcvl.PostSelect("[0,1] == 1")) # Add ports for logical state encoding p3 = pcvl.Processor("SLOS", 4) p3.add_port(0, pcvl.Port(pcvl.Encoding.DUAL_RAIL, "q0")) p3.add_port(2, pcvl.Port(pcvl.Encoding.DUAL_RAIL, "q1")) p3.with_input(pcvl.LogicalState([0, 1])) # |01> logical input ``` -------------------------------- ### Retrieving All Circuit Parameters Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/components/circuit.rst The get_parameters() method provides all parameters defined by the arguments (variable or all, with or without expressions). This is the preferred method for getting all parameters. ```python c = BS(theta=pcvl.P("alpha1")) // PS(pcvl.P("phi")) // BS(theta=pcvl.P("alpha2")) for params in c.get_parameters(): print(param) ``` -------------------------------- ### Create and Use a Basic Parameter Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/utils/parameter.rst Demonstrates how to create a basic symbolic parameter and set its value. Use this when you need a placeholder for a value that will be defined later. ```python import perceval as pcvl p = pcvl.Parameter("phi") # Or equivalently pcvl.P("phi") p.spv p.defined p.set_value(3.14) float(p) p.defined ``` -------------------------------- ### Retrieve and Display Unitary Circuit Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Circuit_Tutorial.ipynb Get the unitary circuit from an experiment and display it using pcvl.pdisplay. This is useful for visualizing the circuit's structure. ```python circ = experiment.unitary_circuit() print(circ.compute_unitary()) pcvl.pdisplay(circ) ``` -------------------------------- ### Import necessary libraries for Perceval Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Two-particle_bosonic-fermionic_quantum_walk.ipynb Imports required modules from Perceval, Matplotlib, and NumPy for quantum walk simulation and visualization. Ensure Perceval is installed. ```python # imports import matplotlib.pyplot as plt import numpy as np import perceval as pcvl from perceval.components.unitary_components import BS from perceval.backends import SLOSBackend from perceval.simulators import Simulator from perceval.components import Source ## Use the symbolic skin for display from perceval.rendering import DisplayConfig, SymbSkin DisplayConfig.select_skin(SymbSkin) ``` -------------------------------- ### Scaleway Session Initialization Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/providers.rst Demonstrates how to initialize and manage a Scaleway session for accessing QPUs. It shows both manual start/stop and context manager usage. ```APIDOC ## Scaleway Session Initialization ### Description Instantiate and manage a Scaleway session to interact with Quantum Processing Units (QPUs) provided by Scaleway. ### Method `scw.Session(platform_name: str, project_id: str, token: str, deduplication_id: Optional[str] = None)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import perceval as pcvl import perceval.providers.scaleway as scw PROJECT_ID = "your-scaleway-project-id" TOKEN = "your-scaleway-api-key" PLATFORM_NAME = "EMU-SAMPLING-L4" # Or a real QPU name # Manual start/stop session = scw.Session(platform_name=PLATFORM_NAME, project_id=PROJECT_ID, token=TOKEN) session.start() # ... use session ... session.stop() # Using a with block (automatic start/stop) with scw.Session(platform_name=PLATFORM_NAME, project_id=PROJECT_ID, token=TOKEN) as session: # ... use session ... # Using an existing session with deduplication_id DEDUPLICATION_ID = "my-quantum-workshop-identifier" session = scw.Session(platform=PLATFORM_NAME, project_id=PROJECT_ID, token=TOKEN, deduplication_id=DEDUPLICATION_ID) ``` ### Response #### Success Response (200) `session`: An initialized Scaleway session object. #### Response Example ```json // No direct JSON response for session creation, returns a session object. ``` ``` -------------------------------- ### Initialize and Use NoiseModel with Processor Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/utils/noise_model.rst Demonstrates how to create a NoiseModel instance with specified parameters and then associate it with a Processor for simulation. This is useful for setting up experiments with realistic noise characteristics. ```python >>> import perceval as pcvl >>> noise_model = pcvl.NoiseModel(brightness=0.3, g2=0.05) >>> proc = pcvl.Processor("SLOS", 4, noise_model) ``` -------------------------------- ### Add Barrier to Circuit Source: https://context7.com/quandela/perceval/llms.txt Inserts a barrier into a circuit, serving as a visual separator between circuit sections. This example demonstrates adding a barrier after a BS component. ```python c2 = pcvl.Circuit(2) // pcvl.BS() c2.barrier() c2 //= pcvl.PS(0.5) ``` -------------------------------- ### Parameter Initialization and Usage Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/utils/parameter.rst Demonstrates how to initialize a Parameter object, set its value, and access its properties. ```APIDOC ## Parameter Initialization and Usage ### Description This section shows how to create a `Parameter` object, assign it a symbolic name, and then set and retrieve its numerical value. It also illustrates how to check if a parameter has been defined and how to cast it to a float. ### Method ```python import perceval as pcvl # Initialize a parameter with a symbolic name p = pcvl.Parameter("phi") # Or equivalently pcvl.P("phi") # Access the symbolic value print(p.spv) # Check if the parameter is defined (has a numerical value) print(p.defined) # Set a numerical value for the parameter p.set_value(3.14) # Cast the parameter to a float to get its numerical value print(float(p)) # Check again if the parameter is defined print(p.defined) ``` ### Response Example ``` phi False 3.14 True ``` ``` -------------------------------- ### Define and Configure an Experiment Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Circuit_Tutorial.ipynb Sets up an optical experiment including the circuit, noise model, input state, and post-selection criteria. This allows for simulating realistic experimental conditions. ```python # Define your experiment experiment = pcvl.Experiment(4, pcvl.NoiseModel(brightness= 0.8, indistinguishability=0.9)) experiment.add(0, chip) # Those two lines could also be replaced by experiment = pcvl.Experiment(chip, NoiseModel(...)) # Define your input experiment.with_input(pcvl.BasicState([1, 0, 1, 0])) # Define conditions on the output experiment.min_detected_photons_filter(2) # Postselection on the number of photons of the output experiment.set_postselection(pcvl.PostSelect("[0, 1] == 1 & [2, 3] == 1")) # Postselection using logical conditions pcvl.pdisplay(experiment) # chip is now a black box for the experiment ``` -------------------------------- ### Initialize Perceval Processor with CliffordClifford2017 backend Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Boson_sampling.ipynb Sets up the simulation processor using the 'CliffordClifford2017' backend, suitable for Boson Sampling simulations, and applies the defined unitary circuit. ```python QPU = pcvl.Processor("CliffordClifford2017", unitary_circuit_60) ``` -------------------------------- ### Compose Experiments Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Circuit_Tutorial.ipynb Combines multiple experiments or circuits into a larger experimental setup. This allows for building complex experimental workflows by composing simpler parts. ```python # Experiments can be composed more freely than circuits expe = pcvl.Experiment(6) expe.add({0: 1, 1: 3, 2: 2, 4: 0}, experiment) # Only the inner components are added pcvl.pdisplay(expe) ``` -------------------------------- ### Generate Generic Interferometer Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/LOv_rewriting_rules.ipynb Creates a random generic interferometer with a specified number of modes, depth, and shape. This serves as an example circuit to apply rewriting rules. ```python a=pcvl.GenericInterferometer(4, lambda idx:pcvl.Circuit(2)//pcvl.PS(phi=random.random())//pcvl.BS(theta=random.random()), depth=8, shape=pcvl.InterferometerShape.RECTANGLE) pcrl.pdisplay(a, recursive=True, render_size=0.7) ``` -------------------------------- ### Source Initialization and Probability Distribution Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/components/source.rst Demonstrates how to initialize a Source object with specific emission probabilities and multiphoton components, and how to display its probability distribution. ```APIDOC ## Source Initialization and Probability Distribution ### Description This example shows how to create a `Source` object in Perceval, specifying parameters like `emission_probability` and `multiphoton_component`. It then demonstrates how to retrieve and display the probability distribution of the source. ### Method Instantiate `perceval.components.source.Source` and call `probability_distribution()`. ### Parameters #### Source Initialization Parameters - **emission_probability** (float) - The probability of emitting a photon. - **multiphoton_component** (float) - The probability of emitting multiple photons. ### Request Example ```python import perceval as pcvl source = pcvl.Source(emission_probability=0.3, multiphoton_component=0.05) print(pcvl.pdisplay(source.probability_distribution())) ``` ### Response #### Success Response The output displays a table of states and their corresponding probabilities. #### Response Example ``` +-----------------+-----------------+ | state | probability | +-----------------+-----------------+ | \|0> | 7/10 | +-----------------+-----------------+ | \|{_:0}> | 0.297716 | +-----------------+-----------------+ | \|{_:0}{_:2}> | 0.002284 | +-----------------+-----------------+ ``` ``` -------------------------------- ### Display Optical Circuit for Shor's Algorithm Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Shor_Implementation.ipynb Prints and displays the optical circuit designed for Shor's algorithm. This helps visualize the experimental setup. ```python print("Optical circuit for Shor's algorithm") pcvl.pdisplay(experiment, recursive=True) ``` -------------------------------- ### Run Perceval Unit Tests Source: https://github.com/quandela/perceval/blob/main/README.md Install test requirements and run unit tests using pytest. Use the --cov flag to generate a coverage report. ```bash pip install -r tests/requirements.txt pytest pytest --cov=perceval ``` -------------------------------- ### Hamiltonian Coefficients and Elements (Example 3) Source: https://github.com/quandela/perceval/blob/main/docs/source/notebooks/Variational_Quantum_Eigensolver.ipynb Defines Hamiltonian elements and coefficients for a specific Hamiltonian (Hamiltonian n°3). This is used to construct the Hamiltonian matrix for VQE calculations. ```python Hamiltonian_elem = np.array([[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]], #00 [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], #II [[1,0,0,0],[0,1,0,0],[0,0,-1,0],[0,0,0,-1]], #ZI [[0,0,0,1],[0,0,1,0],[0,1,0,0],[1,0,0,0]], #XX [[1,0,0,0],[0,-1,0,0],[0,0,1,0],[0,0,0,-1]], #IZ [[1,0,0,0],[0,-1,0,0],[0,0,-1,0],[0,0,0,1]]]) #ZZ Hamiltonian_coef = np.matrix( ``` -------------------------------- ### NaiveApproxBackend Initialization Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/backends/naive_approx.rst Initializes the NaiveApproxBackend with a specified number of iterations for permanent estimation. Higher iteration counts lead to a reduced error bound. ```APIDOC ## NaiveApproxBackend(iterations) ### Description Initializes the NaiveApproxBackend with a specified number of iterations for permanent estimation. Higher iteration counts lead to a reduced error bound. ### Parameters #### Path Parameters - **iterations** (int) - Required - The number of iterations to use for estimating the permanent. ``` -------------------------------- ### Compute Probability Distribution with SLOSBackend Source: https://github.com/quandela/perceval/blob/main/docs/source/reference/backends/slos.rst This snippet demonstrates how to set up a circuit, configure the SLOSBackend, define an input state, and compute the probability distribution of the output states. Ensure the perceval library is imported. ```python import perceval as pcvl c = pcvl.Circuit(4) // pcvl.BS() // (2, pcvl.BS()) backend = pcvl.SLOSBackend() backend.set_circuit(c) backend.set_input_state(pcvl.BasicState([1, 0, 1, 0])) print(backend.prob_distribution()) ```