### QAOA Workflow Example Source: https://context7.com/entropicalabs/openqaoa/llms.txt Demonstrates the end-to-end QAOA workflow, including device configuration, circuit setup, optimization, and result analysis. Ensure necessary libraries are installed and a compatible backend is available. ```python import networkx as nx from openqaoa import QAOA from openqaoa.problems import MaximumCut from openqaoa.backends import create_device # Create a graph for the MaxCut problem G = nx.generators.fast_gnp_random_graph(n=6, p=0.6, seed=42) # Convert to QUBO formulation maxcut_problem = MaximumCut(G) qubo = maxcut_problem.qubo # Initialize QAOA workflow q = QAOA() # Configure the device (local vectorized simulator) device = create_device(location='local', name='vectorized') q.set_device(device) # Set circuit properties q.set_circuit_properties( p=2, # Number of QAOA layers param_type='standard', # Parameterization: 'standard', 'extended', 'fourier' init_type='ramp', # Initialization: 'ramp', 'rand', 'custom' mixer_hamiltonian='x' # Mixer type: 'x', 'xy' ) # Configure backend properties q.set_backend_properties( n_shots=1000, # Number of measurement shots cvar_alpha=1.0 # CVaR parameter (1.0 = standard expectation) ) # Set classical optimizer q.set_classical_optimizer( method='cobyla', # Optimizer: 'cobyla', 'nelder-mead', 'powell', etc. maxiter=200, tol=0.001, cost_progress=True, parameter_log=True ) # Compile and optimize q.compile(qubo) q.optimize() # Access results result = q.result print(f"Optimized cost: {result.optimized['cost']}") print(f"Optimized angles: {result.optimized['angles']}") print(f"Most probable states: {result.most_probable_states}") # Plot optimization progress fig, ax = result.plot_cost() ``` -------------------------------- ### Install OpenQAOA from Cloned Repository Source: https://github.com/entropicalabs/openqaoa/blob/main/README.md After cloning the repository, navigate into the directory and use the Makefile for installation. This method is an alternative to PyPI installation. ```bash make local-install ``` -------------------------------- ### Install OpenQAOA-Braket via PyPI Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_braket/openqaoa_braket_install.md Use this command to install the latest version of openqaoa-braket. Ensure you have python>=3.8 and are in a virtual environment. This also installs openqaoa-core. ```bash pip install openqaoa-braket ``` -------------------------------- ### Install OpenQAOA from Cloned Repository Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/index.md Installs OpenQAOA after cloning the repository. Navigate to the 'openqaoa' directory first. A python virtual environment is recommended. ```bash pip install . ``` -------------------------------- ### Install OpenQAOA Azure via PyPI Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_azure/openqaoa_azure_install.md Use this command to install the latest version of openqaoa-azure. This command also installs openqaoa-core and openqaoa-qiskit by default. Ensure you have python>=3.8 and a virtual environment. ```bash pip install openqaoa-azure ``` -------------------------------- ### Install Specific OpenQAOA Plugin Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/index.md Installs a specific backend plugin for OpenQAOA. Replace '{plugin}' with the desired backend name (e.g., qiskit, pyquil). ```bash pip install openqaoa-plugin ``` -------------------------------- ### Install OpenQAOA via PyPI Source: https://github.com/entropicalabs/openqaoa/blob/main/README.md Install the latest version of OpenQAOA from PyPI. Ensure you are using Python 3.8 or newer in your virtual environment. ```bash pip install openqaoa ``` -------------------------------- ### Setup and Run QAOA Source: https://context7.com/entropicalabs/openqaoa/llms.txt Sets up a QAOA problem using a random graph, compiles the circuit, and runs the optimization. Accesses the results object for optimized parameters and cost. ```python from openqaoa import QAOA from openqaoa.problems import MaximumCut from openqaoa.utilities import ground_state_hamiltonian import networkx as nx # Setup and run QAOA G = nx.gnp_random_graph(6, 0.5, seed=42) qubo = MaximumCut(G).qubo q = QAOA() q.set_circuit_properties(p=2) q.set_classical_optimizer(method='cobyla', maxiter=200) q.compile(qubo) q.optimize() # Access result object result = q.result # Optimized parameters and cost print(f"Final cost: {result.optimized['cost']}") print(f"Optimized angles: {result.optimized['angles']}") print(f"Evaluation number: {result.optimized['eval_number']}") ``` -------------------------------- ### Configure Device Backends Source: https://context7.com/entropicalabs/openqaoa/llms.txt Create device configurations for local simulators, IBM Quantum, AWS Braket, Azure Quantum, and Rigetti QCS. Includes examples for emulator modes and checking connections. ```python from openqaoa.backends import create_device # Local simulators vectorized_sim = create_device(location='local', name='vectorized') qiskit_statevector = create_device(location='local', name='qiskit.statevector_simulator') qiskit_shot_sim = create_device(location='local', name='qiskit.shot_simulator') # IBM Quantum devices ibmq_device = create_device( location='ibmq', name='ibm_kyoto', hub='ibm-q', group='open', project='main' ) # IBM Quantum with emulator mode ibmq_emulator = create_device( location='ibmq', name='ibm_kyoto', hub='ibm-q', group='open', project='main', as_emulator=True ) # AWS Braket devices braket_sim = create_device(location='aws_braket', name='SV1') braket_ionq = create_device(location='aws_braket', name='ionq') # Rigetti QCS rigetti_qvm = create_device( location='qcs', name='7q-qvm', as_qvm=True, execution_timeout=10, compiler_timeout=100 ) # Azure Quantum azure_device = create_device( location='azure', name='ionq.simulator', resource_id='your-resource-id', az_location='eastus' ) # Check device connection if ibmq_device.check_connection(): print("Successfully connected to IBMQ") ``` -------------------------------- ### Install OpenQAOA Qiskit via PyPI Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_qiskit/openqaoa_qiskit_install.md Use this command to install the latest version of openqaoa-qiskit from PyPI. It is recommended to use a Python environment with version 3.8 or higher. ```bash pip install openqaoa-qiskit ``` -------------------------------- ### Install OpenQAOA Core via pip Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_core/openqaoa_core_install.md Use this command to install the core package in a Python 3.8+ virtual environment. ```bash pip install openqaoa-core ``` -------------------------------- ### Developer Installation of OpenQAOA Source: https://github.com/entropicalabs/openqaoa/blob/main/README.md Install OpenQAOA in developer mode for an editable installation. This is useful for contributing to the project. ```bash make dev-install ``` -------------------------------- ### Basic RQAOA Optimization Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_core/workflows.md A minimal example showing the standard workflow for compiling and optimizing a QUBO problem. ```pycon >>> r = RQAOA() >>> r.compile(QUBO) >>> r.optimize() ``` -------------------------------- ### Developer Installation with Extra Requirements Source: https://github.com/entropicalabs/openqaoa/blob/main/README.md Install OpenQAOA in developer mode with additional requirements for testing or documentation generation. Replace 'x' with 'tests', 'docs', or 'all'. ```bash make dev-install-x, with x = {tests, docs, all} ``` -------------------------------- ### Running Adaptive RQAOA Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_core/workflows.md Example of configuring and running the adaptive variant of the RQAOA algorithm. ```pycon >>> r_adaptive = RQAOA() >>> r.set_circuit_properties( p=10, param_type='extended', init_type='ramp', mixer_hamiltonian='x' ) >>> r.set_device_properties( device_location='qcs', device_name='Aspen-11', cloud_credentials={ 'name' : "Aspen11", 'as_qvm':True, 'execution_timeout' : 10, 'compiler_timeout':10 } ) >>> r_adaptive.set_backend_properties(n_shots=200, cvar_alpha=1) >>> r_adaptive.set_classical_optimizer(method='nelder-mead', maxiter=2) >>> r_adaptive.set_rqaoa_parameters(rqaoa_type = 'adaptive', n_cutoff = 5, n_max=5) >>> r_adaptive.compile(qubo_problem) >>> r_adaptive.optimize() ``` -------------------------------- ### RQAOA Workflow Example Source: https://context7.com/entropicalabs/openqaoa/llms.txt Illustrates the Recursive QAOA (RQAOA) workflow for iteratively reducing problem size. Configure RQAOA parameters, underlying QAOA settings, and the classical optimizer. ```python import numpy as np import networkx as nx from openqaoa import RQAOA from openqaoa.problems import MinimumVertexCover from openqaoa.backends import create_device # Create a ring graph for Minimum Vertex Cover n_qubits = 10 G = nx.circulant_graph(n_qubits, [1]) # Define problem with penalty coefficients problem = MinimumVertexCover(G, field=1.0, penalty=10) qubo = problem.qubo # Initialize RQAOA with adaptive strategy r = RQAOA() # Configure RQAOA parameters r.set_rqaoa_parameters( rqaoa_type='adaptive', n_cutoff=3, n_max=4 ) # Configure underlying QAOA r.set_circuit_properties(p=1, param_type='standard', init_type='ramp') r.set_device(create_device(location='local', name='vectorized')) r.set_classical_optimizer(method='cobyla', maxiter=200) # Compile and optimize r.compile(qubo) r.optimize() # Access RQAOA results result = r.result print(f"Solutions: {result['solution']}") print(f"Elimination schedule: {result['schedule']}") print(f"Number of steps: {result['number_steps']}") # Get intermediate step information for step in range(result['number_steps']): qaoa_result = result.get_qaoa_results(step) problem_step = result.get_problem(step) print(f"Step {step}: {len(problem_step.terms)} terms") # Plot correlation matrix for a specific step fig, ax = result.plot_corr_matrix(step=0) ``` -------------------------------- ### Initialize QAOA Model Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/03_qaoa_on_qpus.ipynb Initializes the QAOA model with default configurations. This is the starting point before setting specific devices or circuit properties. ```python # initialize model with default configurations q_qiskit = QAOA() ``` -------------------------------- ### Initialize QAOA with Qiskit Statevector Simulator Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/08_results_example.ipynb Initializes the QAOA object and sets the Qiskit statevector simulator as the device. Ensure Qiskit is installed and configured. ```python q_qiskit_sv = QAOA() qiskit_dev = create_device(location='local',name='qiskit.statevector_simulator') q_qiskit_sv.set_device(qiskit_dev) ``` -------------------------------- ### Problem Class Examples Source: https://context7.com/entropicalabs/openqaoa/llms.txt Demonstrates the usage of built-in problem classes to automatically generate QUBO formulations for common combinatorial optimization problems. ```python import networkx as nx from openqaoa.problems import ( MaximumCut, MinimumVertexCover, NumberPartition, TSP, Knapsack, ShortestPath, QUBO ) # Maximum Cut - find partition maximizing edge cuts G = nx.gnp_random_graph(8, 0.5, seed=42) maxcut = MaximumCut(G) maxcut_qubo = maxcut.qubo # Number Partition - divide numbers into equal-sum groups numbers = [3, 1, 1, 2, 2, 1] partition = NumberPartition(numbers) partition_qubo = partition.qubo ``` -------------------------------- ### Instantiate Backend Simulator Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/index.md Set up the backend simulator, such as QAOAvectorizedBackendSimulator, with the QAOA descriptor. ```python backend_obj = QAOAvectorizedBackendSimulator(qaoa_descriptor = qaoa_descriptor, append_state = None, prepend_state = None, init_hadamard = True) ``` -------------------------------- ### Initialize and Run QAOA Optimizer Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/11_Mixer_example.ipynb Sets up the QAOA descriptor, device, variational parameters, and backend to execute the optimization process. ```python qaoa_descriptor = QAOADescriptor(mini_cov_qubo.hamiltonian, final_gatemap_list, p=1, mixer_coeffs=final_gatemap_coeffs) device_local = create_device(location='local', name='vectorized') variate_params = create_qaoa_variational_params(qaoa_descriptor, 'standard', 'rand') backend_local = get_qaoa_backend(qaoa_descriptor, device_local) optimizer = get_optimizer(backend_local, variate_params, {'method': 'cobyla', 'maxiter': 100}) ``` ```python optimizer.optimize() ``` -------------------------------- ### Install OpenQAOA Pyquil via pip Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_pyquil/openqaoa_pyquil_install.md Installs the latest version of openqaoa-pyquil and its dependency openqaoa-core. ```bash pip install openqaoa-pyquil ``` -------------------------------- ### Configure Backend Execution Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/07_cost_landscapes_w_manual_mode.ipynb Sets up the device and initializes the backend for circuit execution with a specified number of shots. ```python # call the device to use device_qiskit = create_device(location = 'local', name = 'qiskit.qasm_simulator') # initialize the backend with the device and circuit_params backend_qiskit_p1 = get_qaoa_backend(qaoa_descriptor_p1, device_qiskit, n_shots = 500) backend_qiskit_p2 = get_qaoa_backend(qaoa_descriptor_p2, device_qiskit, n_shots = 500) ``` -------------------------------- ### Initialize and Run QAOA for Portfolio Optimization Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/community_tutorials/03_portfolio_optimization.ipynb Sets up the QAOA algorithm with specified backend properties and circuit parameters, then compiles and runs the optimization for the portfolio problem. ```python # Indicate the device, this case is a local simulator device = create_device("local", 'qiskit.qasm_simulator') # Initilize the QAOA object qaoa_po = QAOA(device) # Set the parameters to work the QAOA algorithm qaoa_po.set_backend_properties(n_shots=128, seed_simulator=1) qaoa_po.set_circuit_properties(p=2, init_type="custom", variational_params_dict={"betas":2*[0.1*np.pi],"gammas":2*[0.1*np.pi]}) qaoa_po.compile(ising_encoding_po) # Run the QAOA algorithm qaoa_po.optimize() ``` -------------------------------- ### Configure and Run QAOA Workflow Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/12_testing_azure.ipynb Sets up the QAOA object with device, backend properties, and optimizer, then executes the optimization. ```python from openqaoa import QAOA q = QAOA() q.set_device(device_azure) q.set_backend_properties(n_shots=1000) q.set_classical_optimizer(maxiter=5) ``` ```python q.compile(np_qubo) ``` ```python q.optimize() ``` ```python q.result.optimized ``` -------------------------------- ### Initialize QAOA models with different devices Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/02_simulators_comparison.ipynb Configure QAOA models using statevector and shot-based simulators. ```python # initialize model with statevector_simulator q_sv = QAOA() # device qiskit_sv = create_device(location='local', name='qiskit.statevector_simulator') q_sv.set_device(qiskit_sv) # circuit properties q_sv.set_circuit_properties(p=2, param_type='standard', init_type='rand', mixer_hamiltonian='x') # classical optimizer properties q_sv.set_classical_optimizer(method='COBYLA', maxiter=200, tol=0.001, cost_progress=True, parameter_log=True) q_sv.compile(maxcut_qubo) ``` ```python # initialize model with shot-based simulator q_shot = QAOA() # device qiskit_shot = create_device(location='local', name='qiskit.qasm_simulator') q_shot.set_device(qiskit_shot) # circuit properties q_shot.set_circuit_properties(p=2, param_type='standard', init_type='rand', mixer_hamiltonian='x') # backend properties q_shot.set_backend_properties(n_shots = 200) # classical optimizer properties q_shot.set_classical_optimizer(method='COBYLA', maxiter=200, tol=0.001, cost_progress=True, parameter_log=True) q_shot.compile(maxcut_qubo) ``` -------------------------------- ### Initialize and Run Classical Optimizer Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/index.md Configure a classical optimizer like ScipyOptimizer with the backend and parameters, then run the optimization. ```python optimizer_dict = {'method': 'cobyla', 'maxiter': 200} optimizer_obj = ScipyOptimizer(backend_obj, params, optimizer_dict) optimizer_obj() ``` -------------------------------- ### sample_from_wavefunction Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_core/backends.md Get the shot-based measurement results from the statevector. ```APIDOC ## sample_from_wavefunction ### Description Get the shot-based measurement results from the statevector. ### Parameters - **params** (QAOAVariationalBaseParams) - Required - The QAOA parameters as a 1D array. - **n_samples** (int) - Required - The number of measurement samples required. ### Response - **Returns** (np.ndarray) - A list of measurement outcomes sampled from a statevector. ``` -------------------------------- ### compile Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_core/workflows.md Initializes the trainable parameters for QAOA and builds the quantum circuit. ```APIDOC ## compile(problem: QUBO | None = None, verbose: bool = False, routing_function: Callable | None = None) ### Description Initialise the trainable parameters for QAOA according to the specified strategies and by passing the problem statement. Compilation is necessary to build the actual QAOA circuit. ### Parameters #### Request Body - **problem** (QUBO) - Optional - QUBO problem to be solved by QAOA. - **verbose** (bool) - Optional - Set True to have a summary of QAOA displayed after compilation. - **routing_function** (Callable) - Optional - Function for routing. ``` -------------------------------- ### wavefunction Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_core/backends.md Get the wavefunction of the state produced by the parametric circuit. ```APIDOC ## wavefunction ### Description Get the wavefunction of the state produced by the parametric circuit. ### Parameters - **params** (Type[QAOAVariationalBaseParams]) - Optional - The QAOA parameters. ### Response - **Returns** (list) - A list of the wavefunction amplitudes. ``` -------------------------------- ### Wavefunction Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_core/backends.md Gets the wavefunction of the state produced by the QAOA circuit. ```APIDOC ## GET /wavefunction ### Description Get the wavefunction of the state produced by the QAOA circuit. ### Parameters #### Request Body - **params** (QAOAVariationalBaseParams) - Required - The QAOA parameters - an object of one of the parameter classes, containing the variational parameters (angles). ### Response #### Success Response (200) - **wavefunction** (List[complex]) - A list of the wavefunction amplitudes. ### Response Example ```json { "wavefunction": [ "(0.707+0j)", "(0+0j)", "(0+0j)", "(0.707+0j)" ] } ``` ``` -------------------------------- ### Get Execution Counts Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_pyquil/pyquil_backends.md Executes the circuit and returns the counts of each bitstring. ```APIDOC ## get_counts(params: QAOAVariationalBaseParams, n_shots=None) -> dict ### Description Execute the circuit and obtain the counts. ### Parameters - **params** (QAOAVariationalBaseParams) - Required - The QAOA parameters - an object of one of the parameter classes, containing variable parameters. - **n_shots** (int) - Optional - The number of times to run the circuit. If None, n_shots is set to the default: self.n_shots ### Returns - **counts** (dict) – A dictionary with the bitstring as the key and the number of counts as its value. ### Return type dictionary ``` -------------------------------- ### Configure Qiskit Device and Properties Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/03_qaoa_on_qpus.ipynb Sets up the Qiskit device, circuit parameters, backend properties, and classical optimizer settings. ```python qiskit_cloud = create_device(location='ibmq', name='ibm_kyoto', **qpu_credentials, as_emulator=True) q_qiskit.set_device(qiskit_cloud) # circuit properties q_qiskit.set_circuit_properties(p=1, param_type='standard', init_type='rand', mixer_hamiltonian='x') # backend properties (already set by default) q_qiskit.set_backend_properties(prepend_state=None, append_state=None) # classical optimizer properties q_qiskit.set_classical_optimizer(method='nelder-mead', maxiter=20, cost_progress=True, parameter_log=True, optimization_progress=True) ``` -------------------------------- ### Import OpenQAOA and dependencies Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/06_fast_qaoa_simulator.ipynb Initializes the environment by importing necessary libraries for graph manipulation, problem definition, and QAOA workflow management. ```python #some regular python libraries import networkx as nx import numpy as np from pprint import pprint import matplotlib.pyplot as plt #import problem classes from OQ for easy problem creation from openqaoa.problems import MaximumCut, NumberPartition #import the QAOA workflow model from openqaoa import QAOA #import method to specify the device from openqaoa.backends import create_device #importing the time module to record time for simulations from time import time ``` -------------------------------- ### Sample from Wavefunction Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_core/backends.md Gets the shot-based measurement results from the statevector. The return object is a list of shot-results. ```APIDOC ## POST /sample_from_wavefunction ### Description Get the shot-based measurement results from the statevector. The return object is a list of shot-results. ### Parameters #### Request Body - **params** (QAOAVariationalBaseParams) - Required - The QAOA parameters as a 1D array (derived from an object of one of the parameter classes, containing hyperparameters and variable parameters). - **n_samples** (int) - Required - The number of measurement samples required; specified as integer. ### Response #### Success Response (200) - **samples** (ndarray) - A list of measurement outcomes sampled from a statevector. ### Response Example ```json { "samples": [ "01", "10", "01" ] } ``` ``` -------------------------------- ### Initialize RQAOA Workflow Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/12_testing_azure.ipynb Sets up the RQAOA workflow using an existing Azure device. ```python from openqaoa import RQAOA r = RQAOA(device=device_azure_qvm) ``` -------------------------------- ### Get Minimum Vertex Cover Solution Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/community_tutorials/mvc_examples/bipartite_graphs.ipynb Calculates the minimum vertex cover solution for a bipartite graph. ```python G_sol = mvc_bg_solution(G) ``` -------------------------------- ### Initialize Qiskit Shot Simulator Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/08_results_example.ipynb Sets up the QAOA object with the Qiskit shot-based simulator device. ```python q_qiskit_shot = QAOA() qiskit_shot_dev = create_device(location='local',name='qiskit.shot_simulator') q_qiskit_shot.set_device(qiskit_shot_dev) ``` -------------------------------- ### Get QAOA Workflow as JSON String Source: https://context7.com/entropicalabs/openqaoa/llms.txt Serializes the QAOA workflow into a JSON string with specified indentation. ```python # Get JSON string json_str = q.dumps(indent=2) ``` -------------------------------- ### Get Lowest Cost Bitstrings Source: https://context7.com/entropicalabs/openqaoa/llms.txt Retrieves a specified number of the lowest cost bitstrings from the QAOA results. ```python # Get lowest cost bitstrings best = result.lowest_cost_bitstrings(n_bitstrings=5) print(f"Best bitstrings: {best}") ``` -------------------------------- ### Import OpenQAOA Components Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/index.md Import all necessary functions for building QAOA circuits and parameters. ```python from openqaoa.qaoa_components import Hamiltonian, QAOADescriptor, create_qaoa_variational_params from openqaoa.utilities import X_mixer_hamiltonian from openqaoa.backends.qaoa_backend import QAOAvectorizedBackendSimulator from openqaoa.optimizers.qaoa_optimizer import ScipyOptimizer ``` -------------------------------- ### Create and Set Device Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/community_tutorials/01_tutorial_quantum_approximate_optimization_algorithm.ipynb Creates a local 'vectorized' simulation device and configures the QAOA object to use this device. ```python from openqaoa.backends import create_device sim = create_device(location='local', name='vectorized') after that you can configurate the object QAOA with the device that you specified previously called *sim* q.set_device(sim) ``` -------------------------------- ### GET /utilities/ring_of_disagrees Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_core/utilities.md Constructs the cost Hamiltonian for the Ring of Disagrees model based on a provided qubit register. ```APIDOC ## GET /utilities/ring_of_disagrees ### Description Builds the cost Hamiltonian for the “Ring of Disagrees” model. ### Parameters #### Request Body - **reg** (List[int]) - Required - Register of qubits in the system. ### Response #### Success Response (200) - **ring_hamil** (Hamiltonian) - Hamiltonian object containing Ring of Disagrees model. ``` -------------------------------- ### Import OpenQAOA Modules Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/04_qaoa_variational_parameters.ipynb Initializes the environment by importing standard Python libraries and specific OpenQAOA parameterization and utility classes. ```python # import the standard modules from python import numpy as np import matplotlib.pyplot as plt # import the OpenQAOA Parameterisation classes manually: Manual Mode from openqaoa.qaoa_components import (PauliOp, Hamiltonian, QAOADescriptor, create_qaoa_variational_params, QAOAVariationalStandardParams, QAOAVariationalExtendedParams) # import the other OpenQAOA modules required for this example from openqaoa.utilities import X_mixer_hamiltonian ``` -------------------------------- ### Optimization Result Data Structure Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/X_dumping_data.ipynb Example of the dictionary structure containing optimization parameters and measurement outcomes. ```python '4d00c5b2-3afa-4436-97bb-94eac763d4a8', '076a3f72-5612-4749-b7f5-4c03fbfb731c', '7bd1f184-a1a9-4f95-9144-14db36c60cd7', 'a18784bb-cf17-4286-a19a-97c58b86b760', 'eff50f77-0224-409f-83c0-504219e4d580', 'b0c20a57-28b8-4435-bc1b-a3b684f5f187', 'aa3ca3ae-9046-4721-98eb-09e29d29e9ae', '8646cd83-af5e-4a38-b49e-0a5b6f025963', '38c159dc-6910-4b8e-83b5-d277eaf40c86', '7423e07b-d4f1-47ea-a9ee-505622e59fcd', '5dbce945-3340-4fba-9048-f9edcaffc46e']}, 'optimized': {'angles': [2.324583746892, -612.776430421385], 'cost': 167.15172430448, 'measurement_outcomes': array([ 1.47465215e-02-2.00730828e-02j, -7.27171252e-03-3.81774001e-03j, 5.02878963e-02-2.65685629e-02j, -1.54756068e-02+7.92107431e-03j, 1.11028554e-02-4.17034895e-02j, -6.91502249e-03+7.06052023e-03j, -9.37592355e-03+7.52398779e-03j, 2.57997597e-03+1.42141931e-02j, -2.73677076e-02-4.45385159e-02j, -1.63426856e-02+4.68385544e-02j, 6.28607919e-02+1.19923003e-01j, -2.10790239e-02-1.19611313e-02j, 8.64608059e-03-4.65860748e-03j, -7.72493413e-04-1.29581738e-03j, -3.23329692e-02-1.70234391e-02j, 1.49656662e-02+1.41915070e-02j, 2.19894317e-02-5.36895028e-02j, -1.45819036e-02+1.17782404e-02j, 1.16427617e-02+9.93279587e-03j, -3.67046308e-03+1.91458112e-02j, 1.08830831e-02-1.68886025e-02j, -1.38382809e-02+1.89022477e-02j, 1.19595890e-02+3.34321684e-02j, -5.94743409e-04+6.49380526e-03j, -2.31072850e-02-3.83382929e-02j, -1.37272572e-02+1.98664577e-02j, 1.97961888e-02+3.52051356e-02j, 2.38625750e-03+1.39374913e-02j, -6.77232976e-02-5.25186288e-02j, -2.01664837e-02+1.56394293e-02j, 8.99314891e-02+3.28011206e-02j, -1.37331553e-02+1.01237333e-02j, 6.97833071e-03-1.53079773e-02j, 2.54954154e-02-1.33329052e-02j, 7.31746662e-03-9.85964688e-04j, 1.64551173e-02+1.17486265e-03j, 4.15604484e-04-9.81202924e-03j, 1.00474076e-02-6.96651354e-03j, -1.67328548e-03+1.57905074e-02j, -1.09714119e-03-2.99596243e-03j, -3.00048738e-02+2.99235713e-02j, -7.51546465e-03-1.73230416e-03j, -4.18326843e-03+2.99113370e-02j, -1.25754795e-02+3.48129251e-03j, 6.08007092e-03-4.11795950e-04j, 1.11796054e-02+6.89418359e-03j, 2.43283315e-03+8.52747583e-03j, -2.68620926e-03-5.54388506e-04j, 2.30104870e-03-9.90707728e-03j, 2.72407394e-02-8.61461824e-03j, 7.12450875e-04+2.20935787e-02j, 3.71762393e-03-1.17061924e-03j, -2.74199687e-03+1.48595069e-02j, 2.35328028e-02+6.17808807e-03j, 2.02081281e-03+1.93821295e-02j, -2.71296061e-03+3.96908310e-03j, -1.89898282e-02+7.99520308e-03j, 9.56251920e-03+5.87655356e-03j, 7.54771787e-03+2.65918528e-02j, -2.21599821e-03+9.76929043e-04j, -4.24422116e-02-4.65074258e-03j, 3.61989923e-03-2.54103171e-03j, 2.12854870e-02+2.20052602e-02j, 1.39700506e-02+1.28357677e-03j, 4.21874063e-02-3.56457196e-02j, -1.56257399e-02+1.38648686e-02j, -4.22489947e-02-1.21861680e-02j, 8.21416024e-03+2.30768559e-02j, 6.72247043e-03+1.62232554e-02j, -8.34832455e-04+4.12150747e-03j, 3.72299563e-02+6.71772298e-02j, -1.85773775e-03-3.65301468e-02j, -1.59910422e-04+5.23805017e-02j, -1.31440361e-02+2.50627187e-02j, -1.45048736e-01-1.55908781e-01j, 4.02545997e-02+6.30286068e-02j, 1.11865111e-02-1.06335635e-02j, -4.16589612e-03+1.42069702e-02j, 1.16199194e-01+2.45851501e-02j, -5.30825335e-02+6.57110494e-04j, 3.07755324e-02-1.78429854e-03j, -1.52914681e-02+2.39028242e-02j, 3.41827474e-02+1.69196990e-02j, -1.64978239e-02+3.26008841e-03j, 2.86958921e-02-1.91112525e-02j, -2.46538303e-02+4.46989423e-02j, 3.87086347e-02-1.38531472e-01j, -5.29076729e-02+9.38330847e-02j, 3.58335093e-02+9.93544458e-03j, -1.98057393e-02+2.98513285e-02j, 7.26167605e-02-3.86917373e-02j, -4.80561310e-02+2.75289028e-02j, 7.18126760e-02+4.47713464e-03j, -2.95623853e-02+2.19635300e-02j, 1.73764527e-02-4.01138688e-02j, -2.38486914e-02+2.15428446e-02j, 7.79948615e-03-1.61912063e-03j, 2.67307039e-02-8.90103049e-03j, -5.74107570e-03+1.25091648e-02j, 3.90667193e-03-1.87113101e-02j, 7.32874845e-03+8.67593367e-03j, 1.78351561e-02-3.38574633e-03j, 2.73197585e-02-1.12419556e-02j, 4.46217567e-02+4.77303618e-03j, -1.90486676e-02+4.29842785e-02j, -1.27086122e-02+1.79046076e-03j, -8.62315534e-03+9.57571935e-03j, 7.46192062e-03-1.58561502e-03j, -6.45571784e-04+1.26343364e-02j, 7.53158871e-04+6.36343971e-03j, -1.36953398e-02+1.22453165e-02j, -8.06898043e-04+1.33518273e-02j, 2.62834414e-03+2.22982274e-02j, 2.42771571e-02-2.08174834e-03j, ``` -------------------------------- ### Get Counts Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_core/backends.md Provides measurement outcome versus frequency information from a circuit execution, represented as a Python dictionary. ```APIDOC ## POST /get_counts ### Description Measurement outcome vs frequency information from a circuit execution represented as a python dictionary. ### Parameters #### Request Body - **params** (QAOAVariationalBaseParams) - Required - The QAOA parameters as a 1D array (derived from an object of one of the parameter classes, containing hyperparameters and variable parameters). - **n_shots** (int) - Optional - The number of shots to be used for the measurement. If None, the backend default is used. ### Response #### Success Response (200) - **counts** (Dict[str, float]) - A dictionary of measurement outcomes vs frequency sampled from a statevector. ### Response Example ```json { "counts": { "00": 500, "11": 500 } } ``` ``` -------------------------------- ### List Available Backends Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/community_tutorials/01_tutorial_quantum_approximate_optimization_algorithm.ipynb Displays the available local simulators and cloud provider integrations for the QAOA object. ```python q.local_simulators, q.cloud_provider ``` -------------------------------- ### Configure Quantum Device Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/community_tutorials/02_docplex_example.ipynb Initializes a local device using a specific backend, such as the Qiskit qasm_simulator. ```python #Specific local device usign qiskit backend device = create_device("local", 'qiskit.qasm_simulator') ``` -------------------------------- ### Optimize QAOA problem Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/X_dumping_data.ipynb Optimizes the QAOA problem. After optimization, the header is updated with execution start and end times. ```python # optimize problem q.optimize() # here we show what we have in the header after optimization, now everything is set q.header ``` -------------------------------- ### Clone OpenQAOA Repository Source: https://github.com/entropicalabs/openqaoa/blob/main/README.md Clone the OpenQAOA GitHub repository to install it manually. It is recommended to use a Python virtual environment. ```bash git clone https://github.com/entropicalabs/openqaoa.git ``` -------------------------------- ### Initialize QAOABenchmark Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/14_qaoa_benchmark.ipynb Creates the benchmark object using the configured QAOA instance. ```python from openqaoa import QAOABenchmark # create the QAOABenchmark object, passing the QAOA object to benchmark as an argument benchmark = QAOABenchmark(q) ``` -------------------------------- ### QAOAQiskitBackendStatevecSimulator Initialization Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_qiskit/qiskit_backends.md Initializes a statevector-based simulator for QAOA circuits using Qiskit. Supports prepending/appending states and controlling initial Hadamard gates. ```python QAOAQiskitBackendStatevecSimulator(qaoa_descriptor: QAOADescriptor, prepend_state: ndarray | qiskit.QuantumCircuit | None, append_state: qiskit.QuantumCircuit | ndarray | None, init_hadamard: bool, cvar_alpha: float = 1) ``` -------------------------------- ### Import Necessary Libraries Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/11_Mixer_example.ipynb Imports essential libraries for graph manipulation, plotting, QAOA backend, and problem definition. Ensure these are installed before running. ```python %matplotlib inline import numpy as np import networkx as nx import matplotlib.pyplot as plt from openqaoa.utilities import plot_graph, ground_state_hamiltonian from openqaoa.backends import create_device from openqaoa.problems import MinimumVertexCover from openqaoa import QAOA ``` -------------------------------- ### RQAOA Initialization and Basic Compilation Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_core/workflows.md Illustrates the basic usage of the RQAOA class, including initialization and compiling a QUBO problem. ```APIDOC ## RQAOA Initialization and Basic Compilation ### Description This section shows how to initialize the RQAOA class and compile a QUBO problem with default parameters. ### Method Not Applicable (Class Initialization and Method Calls) ### Endpoint Not Applicable ### Parameters None for initialization. See individual methods for parameter details. ### Request Example ```pycon >>> from openqaoa import RQAOA >>> from openqaoa.problems import QUBO >>> # Assuming QUBO is defined elsewhere >>> # QUBO = ... >>> r = RQAOA() >>> r.compile(QUBO) >>> r.optimize() ``` ### Response Not Applicable for initialization. See individual methods for response details. ``` -------------------------------- ### Solve QUBO with DOCPLEX Source: https://github.com/entropicalabs/openqaoa/blob/main/examples/community_tutorials/03_portfolio_optimization.ipynb Solves the QUBO problem classically using DOCPLEX to obtain the optimal solution for comparison with the QAOA results. Ensure cplex is installed. ```python # Docplex QUBO model mdl_qubo_po = qubo_po.qubo_docplex # Obtain the docplex solution sol_po_docplex = mdl_qubo_po.solve() sol_po = {i.name: int(sol_po_docplex.get_value(i)) for i in mdl_qubo_po.iter_binary_vars()} sol_po ``` -------------------------------- ### Get QAOA Circuit Counts Source: https://github.com/entropicalabs/openqaoa/blob/main/docs/source/openqaoa_qiskit/qiskit_backends.md Retrieves the counts of a QAOA circuit after binding variational parameters. Specify the number of shots for execution; defaults to self.n_shots if not provided. ```python get_counts(params: QAOAVariationalBaseParams, n_shots=None) → dict ``` -------------------------------- ### Configure Classical Optimizers Source: https://context7.com/entropicalabs/openqaoa/llms.txt Set up various classical optimizers for QAOA, including SciPy gradient-free and gradient-based methods, custom gradient optimizers, and PennyLane optimizers. Demonstrates logging options. ```python from openqaoa import QAOA q = QAOA() # SciPy gradient-free optimizers q.set_classical_optimizer( method='cobyla', # COBYLA - Constrained Optimization BY Linear Approximation maxiter=500, tol=1e-5 ) q.set_classical_optimizer( method='nelder-mead', # Nelder-Mead simplex algorithm maxiter=1000, optimizer_options={'xatol': 1e-4, 'fatol': 1e-4} ) # SciPy gradient-based optimizers q.set_classical_optimizer( method='l-bfgs-b', # Limited-memory BFGS with bounds maxiter=200, jac='finite_difference', # Gradient method jac_options={'stepsize': 0.01} ) # Custom gradient optimizers q.set_classical_optimizer( method='vgd', # Vanilla gradient descent maxiter=500, jac='param_shift', # Parameter shift rule for gradients optimizer_options={'stepsize': 0.1} ) q.set_classical_optimizer( method='rmsprop', # RMSProp optimizer maxiter=300, jac='param_shift', optimizer_options={'stepsize': 0.01, 'decay': 0.9} ) q.set_classical_optimizer( method='spsa', # SPSA - no gradient required maxiter=200, jac='grad_spsa', jac_options={'stepsize': 0.1} ) # PennyLane optimizers q.set_classical_optimizer( method='pennylane_adam', # Adam from PennyLane maxiter=500, jac='param_shift', optimizer_options={'stepsize': 0.01} ) # Logging options q.set_classical_optimizer( method='cobyla', maxiter=200, cost_progress=True, # Track cost function values parameter_log=True, # Track parameter values optimization_progress=True # Show progress during optimization ) ```