### Install qoqo with Pip Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/installation.md Use this command to install the qoqo Python package if a pre-built wheel is available for your system. ```bash pip install qoqo ``` -------------------------------- ### Install qoqo from Source on macOS Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/installation.md When installing from source on macOS, specific linker arguments may be required. Ensure you have a Rust toolchain and maturin installed. ```shell # can be necessary on macOS RUSTFLAGS="-C link-arg=-undefined -C link-arg=dynamic_lookup" pip install qoqo ``` -------------------------------- ### Install qoqo from source on macOS Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/qoqo/README_qoqo.md Install qoqo from source on macOS, which may require specific linker arguments. This is useful if a pre-built wheel is not available for your architecture. ```shell # can be necessary on mscOS RUSTFLAGS="-C link-arg=-undefined -C link-arg=dynamic_lookup" pip install qoqo ``` -------------------------------- ### Create and Run a Quantum Circuit in qoqo Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/README.md Demonstrates how to create a quantum circuit with operations like PauliX, CNOT, and measurements, and then run it on a backend. Ensure the 'qoqo' and 'qoqo_quest' libraries are installed. ```python from qoqo import Circuit from qoqo import operations as ops from qoqo_quest import Backend circuit = Circuit() circuit += ops.DefinitionBit(name="classical_reg", length=2, is_output=True) circuit += ops.PauliX(qubit=0) circuit += ops.CNOT(0,1) circuit += ops.PragmaDamping(qubit=0, gate_time=0.1, rate=0.1) circuit += ops.PragmaDamping(qubit=1, gate_time=0.1, rate=0.1) circuit += ops.MeasureQubit(qubit=0, readout="classical_reg", readout_index=0) circuit += ops.MeasureQubit(qubit=1, readout="classical_reg", readout_index=1) circuit += ops.PragmaSetNumberOfMeasurements(number_measurements=1000, readout="classical_reg") backend = Backend(number_qubits=2) bit_registers, float_registers, complex_registers = backend.run_circuit(circuit) ``` -------------------------------- ### Install qollage for Circuit Visualization in Python Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/circuits/intro.md Install the qollage package using pip to enable circuit visualization in Python environments. ```bash pip install qollage ``` -------------------------------- ### Install qoqo (Python) and roqoqo (Rust) Source: https://context7.com/hqsquantumsimulations/qoqo/llms.txt Instructions for installing the qoqo Python package via pip and adding the roqoqo Rust crate as a Cargo dependency. ```bash # Python pip install qoqo # macOS Apple Silicon (if needed) RUSTFLAGS="-C link-arg=-undefined -C link-arg=dynamic_lookup" pip install qoqo ``` ```toml # Rust – Cargo.toml [dependencies] roqoqo = "1.21" ``` -------------------------------- ### Rust: Run Circuit, Measurement, and Quantum Program with Backend Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/backends.md Illustrates running a single circuit, a measurement with parameter substitution, and a quantum program with a symbolic parameter in Rust. Includes setup for circuits, measurements, and backend initialization. ```rust use std::collections::HashMap; use roqoqo::Circuit; use roqoqo::operations as ops; use roqoqo::measurements::{PauliZProduct, PauliZProductInput}; use roqoqo::QuantumProgram; use roqoqo::prelude::EvaluatingBackend; use roqoqo::prelude::Measure; use roqoqo_quest::Backend; // initialize |psi> let mut init_circuit = Circuit::new(); // Apply a RotateY gate with a symbolic angle // To execute the circuit this symbolic parameter needs to be replaced // with a real number with the help of a QuantumProgram init_circuit += ops::RotateX::new(0, "angle".into()); // Z-basis measurement circuit with 1000 shots let mut z_circuit = Circuit::new(); z_circuit += ops::DefinitionBit::new("ro_z".to_string(), 1, true); z_circuit += ops::PragmaRepeatedMeasurement::new("ro_z".to_string(), 1000, None); // X-basis measurement circuit with 1000 shots let mut x_circuit = Circuit::new(); x_circuit += ops::DefinitionBit::new("ro_x".to_string(), 1, true); // Changing to the X basis with a Hadamard gate x_circuit += ops::Hadamard::new(0); x_circuit += ops::PragmaRepeatedMeasurement::new("ro_x".to_string(), 1000, None); // Preparing the measurement input for one qubit let mut measurement_input = PauliZProductInput::new(1, false); // Read out product of Z on site 0 for register ro_z (no basis change) let z_basis_index = measurement_input.add_pauliz_product("ro_z".to_string(), vec![0,]).unwrap(); // Read out product of Z on site 0 for register ro_x // (after basis change effectively a measurement) let x_basis_index = measurement_input.add_pauliz_product("ro_x".to_string(), vec![0,]).unwrap(); //Add a result (the expectation value of H) that is a combination of the PauliProduct // expectation values let mut linear: HashMap = HashMap::new(); linear.insert(x_basis_index, 0.1); linear.insert(z_basis_index, 0.2); measurement_input.add_linear_exp_val("".to_string(), linear).unwrap(); let measurement = PauliZProduct{ constant_circuit: Some(init_circuit), circuits: vec![z_circuit.clone(), x_circuit], input: measurement_input, }; // Here we show three alternative options that can be ran: // a single circuit, a measurement, and a quantum program. // Create a backend simulating one qubit let backend = Backend::new(1); // a) Run a single circuit let (_bit_registers, _float_registers, _complex_registers) = backend.run_circuit(&z_circuit).unwrap(); // b) To run a measurement we need to replace the free parameter by hand let executable_measurement = measurement.substitute_parameters(HashMap::from([("angle".to_string(), 0.2)])).unwrap(); let expectation_values = backend.run_measurement(&executable_measurement).unwrap(); println!("{expectation_values:?}"); // c) Run a quantum program // The QuantumProgram now has one free parameter that must be set when executing it. // The symbolic value "angle" in the circuits will be replaced by that free parameter // during execution. let program = QuantumProgram::PauliZProduct{ measurement, input_parameter_names: vec!["angle".to_string()]}; // Run the program with 0.1 substituting `angle` let expectation_values = program.run(backend, &[0.1]).unwrap(); println!("{expectation_values:?}"); ``` -------------------------------- ### Build and Install qoqo Locally Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/installation.md Steps to build a local Python package for qoqo from its source code using maturin and then install it via pip. ```shell maturin build -m qoqo/Cargo.toml --release ``` ```shell pip install target/wheels/ ``` -------------------------------- ### Circuit Visualization with qollage (Python) Source: https://context7.com/hqsquantumsimulations/qoqo/llms.txt Render quantum circuits as inline images in Jupyter notebooks using the qollage package. Requires installation via pip. ```python # Install: pip install qollage from qoqo import Circuit from qoqo import operations as ops from qollage import draw_circuit circuit = Circuit() circuit += ops.Hadamard(0) circuit += ops.CNOT(0, 1) circuit += ops.RotateZ(1, 1.57) # Renders inline image in Jupyter notebooks draw_circuit(circuit) ``` -------------------------------- ### Setup Readout Measurements in Python Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/circuits/readout.md Configure a Bit register for qubit readout and add MeasureQubit operations to store measurement results. This is essential for obtaining classical outcomes from quantum computations on hardware. ```python from qoqo import Circuit from qoqo import operations as ops circuit = Circuit() # Add a Bit register to the circuit for the qubit readout circuit += ops.DefinitionBit("bit_register", 2, is_output = True) # Add measurement instructions for each qubit, when using hardware circuit += ops.MeasureQubit(qubit=0, readout="bit_register", readout_index=0) circuit += ops.MeasureQubit(qubit=1, readout="bit_register", readout_index=1) # Alternatively, define a Complex register to readout the state vector circuit += ops.DefinitionComplex("complex_register", 3, is_output = False) ``` -------------------------------- ### QOQO #[wrap] Attribute Example Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/add_new_gate.md Illustrates the `#[wrap]` attribute in QOQO, which functions similarly to `#[derive]` and specifies traits to be implemented for the gate. ```rust #[wrap( Operate, OperateSingleQubit, Rotate, OperateGate, OperateSingleQubitGate, JsonSchema )] ``` -------------------------------- ### Python Example: CheatedPauliZProduct Measurement Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/high-level/pauliz_cheated.md Demonstrates setting up a circuit with CheatedPauliZProduct measurement for a single qubit observable (Hadamard gate). It includes defining readout registers, adding PragmaGetPauliProduct operations, and preparing the CheatedPauliZProductInput. ```python from qoqo import Circuit from qoqo import operations as ops from qoqo.measurements import CheatedPauliZProduct, CheatedPauliZProductInput from qoqo_quest import Backend # initialize |psi> = (|0> + |1>)/ sqrt(2) circuit = Circuit() circuit += ops.Hadamard(0) # Add definition for z-Basis readout circuit += ops.DefinitionFloat("ro_z", 1, is_output=True) # Add definition for x-Basis readout circuit += ops.DefinitionFloat("ro_x", 1, is_output=True) # The dictionary of the pauli matrix to measure for each qubit in the product in the form {qubit: pauli}. # Allowed values to be provided for 'pauli' are: 1 = PauliX, 2 = PauliY, 3 = PauliZ. pauliz_products = {0: 3} paulix_products = {0: 1} # PragmaGetPauliProduct works only on simulators and can be used several # times since no projective measurements are applied circuit += ops.PragmaGetPauliProduct(qubit_paulis=pauliz_products, readout="ro_z", circuit=Circuit()) circuit += ops.PragmaGetPauliProduct(qubit_paulis=paulix_products, readout="ro_x", circuit=Circuit()) # Preparing the measurement input for CheatedPauliZProductInput measurement_input = CheatedPauliZProductInput() # Next, pauli products are added to the CheatedPauliZProductInput z_basis_index = measurement_input.add_pauliz_product("ro_z") x_basis_index = measurement_input.add_pauliz_product("ro_x") # Add a result (the expectation value of H) that is a combination of ``` -------------------------------- ### Run Circuit, Measurement, and Quantum Program with Backend Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/backends.md Demonstrates running a single circuit, a measurement with parameter substitution, and a quantum program with a symbolic parameter. Requires initializing a backend and defining circuits. ```python backend = Backend(1) # a) Run a single circuit (bit_registers, float_registers, complex_registers) = backend.run_circuit(z_circuit) # b) To run a measurement we need to replace the free parameter by hand executable_measurement = measurement.substitute_parameters({"angle": 0.2}) expectation_values = backend.run_measurement(executable_measurement) print(expectation_values) # c) Run a quantum program # The QuantumProgram now has one free parameter that must be set when executing it. # The symbolic value "angle" in the circuits will be replaced by that free parameter # during execution. program = QuantumProgram(measurement=measurement, input_parameter_names=["angle"]) # Run the program with 0.1 substituting `angle` expectation_values = program.run(backend, [0.1]) ``` -------------------------------- ### Initialize GenericDevice (Python) Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/devices.md Shows how to initialize a `GenericDevice` with a specified number of qubits in Python. This is a fundamental step for defining custom device topologies. ```python from qoqo import devices import numpy as np # Create a two-qubit device generic_device = devices.GenericDevice(2) ``` -------------------------------- ### Create and Compare Generic and AllToAll Devices (Rust) Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/devices.md Demonstrates creating a `GenericDevice` and an `AllToAllDevice` with specific gates and times. It then asserts their equivalence after converting the `AllToAllDevice` to a `GenericDevice`. Use this to define custom device configurations or verify device implementations. ```rust use roqoqo::devices::Device; use roqoqo::devices::{GenericDevice, AllToAllDevice}; use ndarray::array; // Create a two-qubit device let mut generic_device = GenericDevice::new(2); // Create a comparison two-qubit device with `RotateZ` and `CNOT` as the only gates and 1.0 as the default gate time let all_to_all = AllToAllDevice::new(2, &["RotateZ".to_string()], &["CNOT".to_string()], 1.0); generic_device.set_single_qubit_gate_time("RotateZ", 0, 1.0).unwrap(); generic_device.set_single_qubit_gate_time("RotateZ", 1, 1.0).unwrap(); generic_device.set_two_qubit_gate_time("CNOT", 0, 1, 1.0).unwrap(); generic_device.set_two_qubit_gate_time("CNOT", 1, 0, 1.0).unwrap(); assert_eq!(generic_device, all_to_all.to_generic_device()); ``` -------------------------------- ### Create AllToAllDevice in Python Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/devices.md Initializes an AllToAllDevice with specified qubit count, gates, and default gate time. Use this for dense connectivity. ```python from qoqo import devices import numpy as np # Create a two-qubit device with `RotateZ` and `CNOT` as the only gates and 1.0 as the default gate time all_to_all = devices.AllToAllDevice(2, ["RotateZ"], ["CNOT"], 1.0) ``` -------------------------------- ### Multi-Qubit Gate Operations in qoqo Source: https://context7.com/hqsquantumsimulations/qoqo/llms.txt Illustrates multi-qubit gates acting on a vector of qubits. Requires 'qoqo' and 'numpy' imports. Examples include Toffoli and Mølmer–Sørensen gates. ```python from qoqo import Circuit from qoqo import operations as ops import numpy as np circuit = Circuit() circuit += ops.DefinitionBit("ro", 3, is_output=True) # Toffoli (CCX): two controls (0,1), target 2 circuit += ops.Toffoli(control_0=0, control_1=1, target=2) # Multi-qubit Mølmer–Sørensen XX gate on qubits [0,1,2] circuit += ops.MultiQubitMS(qubits=[0, 1, 2], theta=np.pi / 4) # Multi-qubit PauliZ-product rotation on qubits [0,1,2,3] circuit += ops.MultiQubitZZ(qubits=[0, 1, 2, 3], theta=0.5) for q in range(3): circuit += ops.MeasureQubit(q, "ro", q) ``` -------------------------------- ### Define Complex Register and Get State Vector in Rust Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/circuits/readout.md Defines a complex register and adds an operation to retrieve the state vector. This is used when running circuits on a simulator. ```rust // Alternatively, define a Complex register to readout the state vector circuit += operations::DefinitionComplex::new( "complex_register".to_string(), 3, false, ); // Measure the state vector when running the circuit on a simulator circuit += operations::PragmaGetStateVector::new( "complex_register".to_string(), None, ); ``` -------------------------------- ### Define PauliZProduct Measurement in Rust Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/high-level/pauliz.md Implement PauliZProduct measurements in Rust, mirroring the Python example by setting up circuits for Z and X bases and defining how to combine expectation values. ```rust use roqoqo::{Circuit, operations::*}; use roqoqo::measurements::{PauliZProduct, PauliZProductInput}; use std::collections::HashMap; // initialize |psi> let mut init_circuit = Circuit::new(); init_circuit.add_operation(Hadamard::new(0)); // Z-basis measurement circuit with 1000 shots let mut z_circuit = Circuit::new(); z_circuit.add_operation(DefinitionBit::new("ro_z".to_string(), 1, true)); z_circuit.add_operation( PragmaRepeatedMeasurement::new("ro_z".to_string(), 1000, None), ); // X-basis measurement circuit with 1000 shots let mut x_circuit = Circuit::new(); x_circuit.add_operation(DefinitionBit::new("ro_x".to_string(), 1, true)); // Changing to the X-basis with a Hadamard gate x_circuit.add_operation(Hadamard::new(0)); x_circuit.add_operation( PragmaRepeatedMeasurement::new("ro_x".to_string(), 1000, None), ); // Preparing the measurement input for one qubit // The PauliZProductInput starts with just the number of qubits // and if to use a flipped measurements set. let mut measurement_input = PauliZProductInput::new(1, false); // Next, pauli products are added to the PauliZProductInput // Read out product of Z on site 0 for register ro_z (no basis change) measurement_input .add_pauliz_product("ro_z".to_string(), vec![0]) .unwrap(); // Read out product of Z on site 0 for register ro_x // (after basis change effectively a measurement) measurement_input .add_pauliz_product("ro_x".to_string(), vec![0]) .unwrap(); // Last, instructions how to combine the single expectation values // into the total result are provided. // Add a result (the expectation value of H) that is a combination // of the PauliProduct expectation values. measurement_input .add_linear_exp_val( "".to_string(), HashMap::from([(0, 0.1), (1, 0.2)]), ) .unwrap(); let measurement = PauliZProduct { input: measurement_input, circuits: vec![z_circuit.clone(), x_circuit.clone()], constant_circuit: Some(init_circuit.clone()), }; println!("{measurement:?}"); ``` -------------------------------- ### Run Single Circuit, Measurement, and Quantum Program with qoqo_quest Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/backends.md Demonstrates three ways to run quantum operations using an EvaluatingBackend: directly running a single circuit, running a measurement with post-processing, and running a full QuantumProgram that handles symbolic variable replacement. ```python from qoqo import Circuit from qoqo import operations as ops from qoqo.measurements import PauliZProduct, PauliZProductInput from qoqo import QuantumProgram from qoqo_quest import Backend # initialize |psi> init_circuit = Circuit() # Apply a RotateY gate with a symbolic angle # To execute the circuit this symbolic parameter must replaced # with a real number with the help of a QuantumProgram init_circuit += ops.RotateX(0, "angle") # Z-basis measurement circuit with 1000 shots z_circuit = Circuit() z_circuit += ops.DefinitionBit("ro_z", 1, is_output=True) z_circuit += ops.PragmaRepeatedMeasurement("ro_z", 1000, None) # X-basis measurement circuit with 1000 shots x_circuit = Circuit() x_circuit += ops.DefinitionBit("ro_x", 1, is_output=True) # Changing to the X basis with a Hadamard gate x_circuit += ops.Hadamard(0) x_circuit += ops.PragmaRepeatedMeasurement("ro_x", 1000, None) # Preparing the measurement input for one qubit measurement_input = PauliZProductInput(1, False) # Read out product of Z on site 0 for register ro_z (no basis change) z_basis_index = measurement_input.add_pauliz_product("ro_z", [0,]) # Read out product of Z on site 0 for register ro_x # (after basis change effectively a measurement) x_basis_index = measurement_input.add_pauliz_product("ro_x", [0,]) # Add a result (the expectation value of H) that is a combination of the PauliProduct # expectation values measurement_input.add_linear_exp_val("", {x_basis_index: 0.1, z_basis_index: 0.2}) measurement = PauliZProduct( constant_circuit=init_circuit, circuits=[z_circuit, x_circuit], input=measurement_input, ) # Here we show three alternative options that can be ran: ``` -------------------------------- ### ClassicalRegister Measurement Example Source: https://context7.com/hqsquantumsimulations/qoqo/llms.txt Demonstrates how to use ClassicalRegister to obtain raw bit register readouts from multiple circuits. Use run_registers() for this purpose. All bit, float, and complex registers are returned as dictionaries. ```python from qoqo import Circuit from qoqo import operations as ops from qoqo.measurements import ClassicalRegister from qoqo import QuantumProgram from qoqo_quest import Backend init_circuit = Circuit() init_circuit += ops.Hadamard(0) z_circuit = Circuit() z_circuit += ops.DefinitionBit("ro_z", 1, is_output=True) z_circuit += ops.PragmaRepeatedMeasurement("ro_z", 500, None) x_circuit = Circuit() x_circuit += ops.DefinitionBit("ro_x", 1, is_output=True) x_circuit += ops.Hadamard(0) x_circuit += ops.PragmaRepeatedMeasurement("ro_x", 500, None) measurement = ClassicalRegister( constant_circuit=init_circuit, circuits=[z_circuit, x_circuit], ) program = QuantumProgram(measurement=measurement, input_parameter_names=[]) backend = Backend(1) (bit_registers, float_registers, complex_registers) = program.run_registers(backend, []) # bit_registers: {"ro_z": [[0,1,0,...]], "ro_x": [[1,0,1,...]]} print(bit_registers) ``` -------------------------------- ### AllToAllDevice Configuration Source: https://context7.com/hqsquantumsimulations/qoqo/llms.txt Configure an AllToAllDevice with specified qubits, gates, and default gate times. Use builder pattern for bulk updates of gate times. ```python all_to_all = devices.AllToAllDevice( number_qubits=4, single_qubit_gates=["RotateZ", "Hadamard"], two_qubit_gates=["CNOT"], default_gate_time=1.0 ) # Builder-pattern bulk updates all_to_all = ( all_to_all .set_all_single_qubit_gate_times("RotateZ", 0.3) .set_all_two_qubit_gate_times("CNOT", 0.8)) ``` -------------------------------- ### Build a Quantum Circuit in Rust Source: https://context7.com/hqsquantumsimulations/qoqo/llms.txt Demonstrates building a quantum circuit in Rust using roqoqo, including defining a bit register and adding single-qubit, two-qubit, and measurement operations. ```rust use roqoqo::{Circuit, operations::*}; let mut circuit = Circuit::new(); circuit += DefinitionBit::new("ro".to_string(), 2, true); circuit += Hadamard::new(0); circuit += RotateZ::new(0, 1.5707963.into()); circuit += PauliX::new(1); circuit += CNOT::new(0, 1); circuit += MeasureQubit::new(0, "ro".to_string(), 0); circuit += MeasureQubit::new(1, "ro".to_string(), 1); println!("{circuit:?}"); ``` -------------------------------- ### Rust Cheated Pauli Z Product Measurement Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/high-level/pauliz_cheated.md Implement CheatedPauliZProduct in Rust for expectation value calculations. This involves defining circuits, measurement inputs, and running on a backend. Ensure correct setup of PragmaGetPauliProduct operations. ```rust use roqoqo::backends::{EvaluatingBackend, RegisterResult}; use roqoqo::measurements::{CheatedPauliZProduct, CheatedPauliZProductInput}; use roqoqo::{operations::*, Circuit, QuantumProgram}; use std::collections::HashMap; use roqoqo_quest::Backend; // initialize |psi> let mut circuit = Circuit::new(); circuit.add_operation(Hadamard::new(0)); // Add definition for z-Basis readout circuit.add_operation(DefinitionFloat::new("ro_z".to_string(), 1, true)); // Add definition for z-Basis readout circuit.add_operation(DefinitionFloat::new("ro_x".to_string(), 1, true)); // PragmaGetPauliProduct works only on simulators and can be used several // times since no projective measurements are applied circuit.add_operation(PragmaGetPauliProduct::new( HashMap::from([(0, 3)]), "ro_z".to_string(), Circuit::new()), ); circuit.add_operation(PragmaGetPauliProduct::new( HashMap::from([(0, 1)]), "ro_x".to_string(), Circuit::new())); // Preparing the measurement input for CheatedPauliZProductInput let mut measurement_input = CheatedPauliZProductInput::new(); // Next, pauli products are added to the PauliZProductInput // Read out product of Z on site 0 for register ro_z (no basis change) let index_z = measurement_input.add_pauliz_product("ro_z".to_string()); // Read out product of X on site 0 for register ro_x let index_x = measurement_input.add_pauliz_product("ro_x".to_string()); // Last, instructions how to combine the single expectation values // into the total result are provided. // Add a result (the expectation value of H) that is a combination // of the PauliProduct expectation values. measurement_input .add_linear_exp_val("".to_string(), HashMap::from([(index_z, 0.1), (index_x, 0.2)])) .unwrap(); let measurement = CheatedPauliZProduct { input: measurement_input, circuits: vec![circuit.clone()], constant_circuit: None, }; // Now, the PauliZProduct measurement is prepared to be used // in a QuantumProgram just like: let program = QuantumProgram::CheatedPauliZProduct { measurement, input_parameter_names: vec![], }; let backend = Backend::new(3); let res = program.run(backend, &[]); println!("{res:?}"); ``` -------------------------------- ### Build a Quantum Circuit in Python Source: https://context7.com/hqsquantumsimulations/qoqo/llms.txt Demonstrates building a quantum circuit in Python using qoqo, including defining a bit register and adding single-qubit, two-qubit, and measurement operations. ```python from qoqo import Circuit from qoqo import operations as ops circuit = Circuit() # Declare a bit register of length 2 as output circuit += ops.DefinitionBit(name="ro", length=2, is_output=True) # Single-qubit gates circuit += ops.Hadamard(qubit=0) circuit += ops.RotateZ(qubit=0, theta=1.5707963) # pi/2 circuit += ops.PauliX(qubit=1) # Two-qubit entangling gate circuit += ops.CNOT(control=0, target=1) # Projective measurements into the "ro" register circuit += ops.MeasureQubit(qubit=0, readout="ro", readout_index=0) circuit += ops.MeasureQubit(qubit=1, readout="ro", readout_index=1) print(circuit) # Circuit { ... 6 operations } ``` -------------------------------- ### Create AllToAllDevice in Rust Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/devices.md Initializes an AllToAllDevice with specified qubit count, gates, and default gate time. Use this for dense connectivity. ```rust use roqoqo::devices::Device; use roqoqo::devices::{GenericDevice, AllToAllDevice}; use ndarray::array; // Create a two-qubit device with `RotateZ` and `CNOT` as the only gates and 1.0 as the default gate time let mut all_to_all = AllToAllDevice::new(2, &["RotateZ".to_string()], &["CNOT".to_string()], 1.0); ``` -------------------------------- ### Rust Cheated Measurement with State Vector Readout Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/high-level/cheated.md This Rust snippet illustrates a cheated measurement using the roqoqo library. It mirrors the Python example by setting up a circuit to obtain the state vector, defining an operator, and then executing the `Cheated` measurement on a `roqoqo_quest` backend. The results are printed to the console. ```rust use num_complex::Complex64; use roqoqo::measurements::{Cheated, CheatedInput}; use roqoqo::operations as ops; use roqoqo::prelude::EvaluatingBackend; use roqoqo::Circuit; use roqoqo_quest::Backend; // initialize |psi> = (|0> + |1>)/ sqrt(2) let mut circuit = Circuit::new(); circuit += ops::Hadamard::new(0); // Add definition for state-vector readout circuit += ops::DefinitionComplex::new("state_vec".to_string(), 2, true); // Defining the sparse operator let operator: Vec<(usize, usize, Complex64)> = vec![ (0, 0, 0.2.into()), (0, 1, 0.1.into()), (1, 0, 0.1.into()), (1, 1, (-0.2).into()), ]; // Directly get the state vector from the simulator backend circuit += ops::PragmaGetStateVector::new("state_vec".to_string(), None); // Preparing the measurement input for CheatedPauliZProductInput let mut measurement_input = CheatedInput::new(1); // Add the measured operator measurement_input.add_operator_exp_val("".to_string(), operator, "state_vec".to_string()).unwrap(); let measurement = Cheated { constant_circuit: None, circuits: vec![circuit], input: measurement_input, }; let backend = Backend::new(1); let result = backend.run_measurement(&measurement); println!("{result:?}"); ``` -------------------------------- ### Initialize PauliZProduct Measurement Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/high-level/pauliz.md Instantiate a PauliZProduct measurement with a constant circuit, computation circuits, and measurement input. ```python measurement = PauliZProduct( constant_circuit=init_circuit, circuits=[circuit1, circuit2, ... ], input=measurement_input) ``` -------------------------------- ### Build and Serialize QuantumProgram to JSON Source: https://context7.com/hqsquantumsimulations/qoqo/llms.txt Illustrates the creation of a QuantumProgram, including measurements and input parameters, followed by its serialization to JSON. This format is suitable for API calls and storage. ```python # QuantumProgram serialization (for API calls, storage, etc.) measurement_input = PauliZProductInput(2, False) measurement_input.add_pauliz_product("ro", [0, 1]) measurement_input.add_linear_exp_val("", {0: 1.0}) measurement = PauliZProduct(constant_circuit=None, circuits=[circuit], input=measurement_input) program = QuantumProgram(measurement=measurement, input_parameter_names=[]) program_json = program.to_json() restored_program = QuantumProgram.from_json(program_json) ``` -------------------------------- ### Python Cheated Measurement with State Vector Readout Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/high-level/cheated.md This snippet demonstrates how to perform a cheated measurement in Python using the qoqo library. It initializes a quantum state, defines a circuit to get the state vector, and then prepares a measurement input for a specific operator. The `Cheated` measurement is run on a `qoqo_quest` backend, and the results are printed. ```python from qoqo import Circuit from qoqo import operations as ops from qoqo.measurements import Cheated, CheatedInput from qoqo import QuantumProgram from qoqo_quest import Backend import numpy as np # initialize |psi> = (|0> + |1>)/ sqrt(2) circuit = Circuit() circuit += ops.Hadamard(0) # Add definition for state-vector readout circuit += ops.DefinitionComplex("state_vec", 2, is_output=True) # The dictionary of the pauli matrix to measure for each qubit in the product in the form {qubit: pauli}. # Allowed values to be provided for 'pauli' are: 1 = PauliX, 2 = PauliY, 3 = PauliZ. x_matrix = np.array([[0, 1],[1, 0]]) z_matrix = np.array([[1, 0],[0, -1]]) h_matrix = 0.1 * x_matrix + 0.2 * z_matrix operator = [(0,0, 0.2), (0,1, 0.1), (1,0, 0.1), (1,1, -0.2)] # Directly get the state vector from the simulator backend circuit += ops.PragmaGetStateVector(readout="state_vec", circuit=Circuit()) # Preparing the measurement input for CheatedPauliZProductInput measurement_input = CheatedInput(number_qubits=1) # Add the measured operator measurement_input.add_operator_exp_val(name="", operator=operator, readout="state_vec") measurement = Cheated( constant_circuit=None, circuits=[circuit,], input=measurement_input, ) backend = Backend(1) result = backend.run_measurement(measurement) print(result) ``` -------------------------------- ### Run QuantumProgram with Parameter Value (Python) Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/high-level/program.md Execute a QuantumProgram on a backend by providing a list of parameter values. This is useful for evaluating a program with specific inputs. ```python expectation_values = program.run(backend, [0.785]) ``` -------------------------------- ### Build and Serialize Circuit to JSON Source: https://context7.com/hqsquantumsimulations/qoqo/llms.txt Demonstrates building a quantum circuit with operations and then serializing it to a JSON string. This is useful for storing or transmitting circuit definitions. ```python circuit = Circuit() circuit += ops.DefinitionBit("ro", 2, is_output=True) circuit += ops.Hadamard(0) circuit += ops.CNOT(0, 1) circuit += ops.PragmaRepeatedMeasurement("ro", 500, None) # Serialize to JSON string json_str = circuit.to_json() print(json.loads(json_str).keys()) ``` -------------------------------- ### Cite qoqo Project Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/README.md Use this BibTeX entry to cite the qoqo toolkit in your publications. Ensure you include the URL of the GitHub repository. ```bibtex @misc{qoqo2021, title={qoqo - toolkit to represent quantum circuits}, author={HQS Quantum Simulations GmbH}, year={2021}, url={https://github.com/HQSquantumsimulations/qoqo}, } ``` -------------------------------- ### Create SquareLatticeDevice in Python Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/devices.md Initializes a SquareLatticeDevice with specified dimensions, gates, and default gate time. This device type is suitable for simulating systems with nearest-neighbor interactions on a square grid. ```python from qoqo import devices rows = 1 columns = 2 # Create a two-qubit device with `RotateZ` and `CNOT` as the only gates and 1.0 as the default gate time square_lattice = devices.SquareLatticeDevice(rows, columns, ["RotateZ"], ["CNOT"], 1.0) ``` -------------------------------- ### Build qoqo on Apple Silicon macOS Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/installation.md Specific build command for Apple Silicon Macs, including necessary RUSTFLAGS for maturin to build the qoqo Python package. ```shell RUSTFLAGS="-C link-arg=-undefined -C link-arg=dynamic_lookup" maturin build -m qoqo/Cargo.toml --release ``` ```shell pip install target/wheels/$NAME_OF_WHEEL ``` -------------------------------- ### Create and Populate a Quantum Circuit in Python Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/circuits/intro.md Construct a quantum circuit by adding operations like definitions, gates, and measurements. Ensure a classical register is defined for readout. ```python from qoqo import Circuit from qoqo import operations as ops # create a new circuit circuit = Circuit() # Define the readout for two qubits circuit += ops.DefinitionBit(name="ro", length=2, is_output=True) # Rotation around Z axis by pi/2 on qubit 0 circuit += ops.RotateZ(qubit=0, theta=1.57) # Entangling qubits 0 and 1 with CNOT gate circuit += ops.CNOT(control=0, target=1) # Measuring the qubits circuit += ops.MeasureQubit(qubit=0, readout="ro", readout_index=0) circuit += ops.MeasureQubit(qubit=1, readout="ro", readout_index=1) ``` -------------------------------- ### Circuit Visualization with qollage (Rust) Source: https://context7.com/hqsquantumsimulations/qoqo/llms.txt Generate circuit images in Rust using the roqollage crate. Add 'qollage' to Cargo.toml dependencies. ```rust // Cargo.toml: qollage = "0.5" let image = roqollage::circuit_to_image( &circuit, None, roqollage::RenderPragmas::All, None, None, ).expect("Failed to render circuit"); ``` -------------------------------- ### Create and Configure ContinuousDecoherenceModel in Python Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/noise_models.md Shows how to instantiate and configure a ContinuousDecoherenceModel in Python, including setting decoherence rates and directly manipulating the noise operator. ```python from qoqo import noise_models import numpy as np continuous_model = noise_models.ContinuousDecoherenceModel() continuous_model = continuous_model.add_damping_rate([0, 1, 2], 0.001) continuous_model = continuous_model.add_dephasing_rate([0, 1, 2], 0.0005) continuous_model = continuous_model.add_depolarising_rate([0, 1, 2], 0.0001) continuous_model = continuous_model.add_excitation_rate([0, 1, 2], 0.0006) # Access the underlying struqture operator lindblad_noise = continuous_model.get_noise_operator() lindblad_noise.add_operator_product(("0+", "0+"), 0.1) new_continuous_model = noise_models.ContinuousDecoherenceModel(lindblad_noise) ``` -------------------------------- ### Create and Populate a Quantum Circuit in Rust Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/circuits/intro.md Build a quantum circuit in Rust by appending operations such as definitions, gates, and measurements. A classical register must be defined for readout. ```rust use roqoqo::{Circuit, operations::*}; // Create a new _modifiable_ circuit let mut circuit = Circuit::new(); // Define the readout for two qubits circuit += DefinitionBit::new("ro".to_string(), 2, true); // Apply rotation around Z axis by pi/2 on qubit 0 circuit += RotateZ::new(0, 1.57.into()); // Establish entanglement between qubits 0 and 1 circuit += CNOT::new(0, 1); // Measuring the qubits circuit += MeasureQubit::new(0, "ro".to_string(), 0); circuit += MeasureQubit::new(1, "ro".to_string(), 1); ``` -------------------------------- ### SquareLatticeDevice Configuration Source: https://context7.com/hqsquantumsimulations/qoqo/llms.txt Set up a SquareLatticeDevice with a 2D grid connectivity. Only nearest-neighbour two-qubit gates are supported. ```python square = devices.SquareLatticeDevice( number_rows=2, number_columns=3, single_qubit_gates=["RotateZ", "Hadamard"], two_qubit_gates=["CNOT"], default_gate_time=1.0 ) ``` -------------------------------- ### Initialize State Preparation Circuit Source: https://github.com/hqsquantumsimulations/qoqo/blob/main/documentation/src/high-level/pauliz.md Prepare the initial state |psi> using a Hadamard gate. ```python # initialize |psi> init_circuit = Circuit() init_circuit += ops.Hadamard(0) ```