### Setup and Install Dependencies Source: https://github.com/qoroquantum/divi/blob/main/docs/source/development/contributing.rst Clone the repository, navigate to the directory, and install development dependencies using uv. ```bash git clone https://github.com/QoroQuantum/divi.git cd divi uv sync # installs dev, testing, and docs groups pre-commit install ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/qoroquantum/divi/blob/main/AGENTS.md Install documentation dependencies by navigating to the 'docs/' directory and running 'make install'. ```bash cd docs make install ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/qoroquantum/divi/blob/main/CONTRIBUTING.md Install the necessary dependencies for building and working with the Divi documentation using uv. ```bash uv sync --group docs ``` -------------------------------- ### Install Divi with uv Source: https://github.com/qoroquantum/divi/blob/main/docs/source/index.rst Install the Divi library using the uv package manager. This is the recommended installation method. ```bash uv add qoro-divi ``` -------------------------------- ### Install Dependencies with uv Source: https://github.com/qoroquantum/divi/blob/main/AGENTS.md Use 'uv sync' to install project dependencies. Ensure you are within the project's virtual environment. ```bash uv sync ``` -------------------------------- ### Install uv Dependency Manager Source: https://github.com/qoroquantum/divi/blob/main/CONTRIBUTING.md Install uv, the dependency manager used by Divi, using the provided installation script. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### QAOA with Checkpointing Example Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/resuming_long_runs.rst Demonstrates how to run a QAOA algorithm with checkpointing enabled and then resume the run from a saved checkpoint. ```python import networkx as nx from pathlib import Path from divi.qprog import QAOA from divi.qprog.problems import MaxCliqueProblem from divi.qprog.checkpointing import CheckpointConfig from divi.qprog.optimizers import PymooOptimizer, PymooMethod from divi.backends import MaestroSimulator # Create problem G = nx.bull_graph() checkpoint_dir = Path("qaoa_checkpoints") # Initial run - first half qaoa1 = QAOA( MaxCliqueProblem(G), n_layers=2, optimizer=PymooOptimizer(method=PymooMethod.CMAES, population_size=10), max_iterations=10, backend=MaestroSimulator(), ) # Run with checkpointing qaoa1.run(checkpoint_config=CheckpointConfig(checkpoint_dir=checkpoint_dir)) # Later: Resume from checkpoint qaoa2 = QAOA.load_state( checkpoint_dir=checkpoint_dir, backend=MaestroSimulator(), problem=MaxCliqueProblem(G), # Must provide original problem n_layers=2, ) # Continue optimization qaoa2.max_iterations = 10 qaoa2.run() # Access results print(f"Best loss: {qaoa2.best_loss}") print(f"Solution: {qaoa2.solution}") ``` -------------------------------- ### Develop Documentation with Live Reload Source: https://github.com/qoroquantum/divi/blob/main/AGENTS.md Start a live-reloading documentation server by navigating to the 'docs/' directory and running 'make dev'. ```bash cd docs make dev ``` -------------------------------- ### VQE Program Lifecycle Example Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/core_concepts.rst Demonstrates the initialization and execution of a Variational Quantum Eigensolver (VQE) program using Divi. This example sets up a molecular system, defines the ansatz, selects a backend and optimizer, and then runs the optimization process. ```python import numpy as np import pennylane as qp from divi.qprog import VQE, HartreeFockAnsatz from divi.backends import MaestroSimulator from divi.qprog.optimizers import ScipyOptimizer, ScipyMethod # 1. Initialization - Define your quantum problem molecule = qp.qchem.Molecule( symbols=["H", "H"], coordinates=np.array([[0.0, 0.0, -0.6614], [0.0, 0.0, 0.6614]]), ) vqe = VQE( molecule=molecule, # Your molecular system ansatz=HartreeFockAnsatz(), # Quantum circuit template n_layers=2, # Circuit depth backend=MaestroSimulator(), # Where to run circuits optimizer=ScipyOptimizer(method=ScipyMethod.COBYLA), # Choose optimizer seed=42 # For reproducibility ) # 2-5. Expansion, execution, reduction, and parameter update # happen inside run() on each optimization iteration. vqe.run() print(f"Ground state energy: {vqe.best_loss:.6f}") ``` -------------------------------- ### Install Divi from source with uv Source: https://github.com/qoroquantum/divi/blob/main/docs/source/index.rst Clone the Divi repository and install it from source using uv. This method is useful for development or when needing the latest unreleased code. ```bash git clone https://github.com/QoroQuantum/divi.git cd divi uv sync ``` -------------------------------- ### Install Divi with pip Source: https://github.com/qoroquantum/divi/blob/main/docs/source/index.rst Install the Divi library using pip. This is an alternative to using uv for package management. ```bash pip install qoro-divi ``` -------------------------------- ### Install Divi AI with Prebuilt Wheel Source: https://github.com/qoroquantum/divi/blob/main/docs/source/tools/divi_ai.rst Installs a prebuilt wheel for llama-cpp-python and the divi-ai package. Use --only-binary=:all: to ensure a wheel is used and avoid silent source compilation. ```bash pip install "llama-cpp-python==0.3.19" \ --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu \ --only-binary=:all: pip install "qoro-divi[ai]" ``` -------------------------------- ### Set Up Pre-Commit Hooks Source: https://github.com/qoroquantum/divi/blob/main/CONTRIBUTING.md Install pre-commit hooks to automatically enforce code formatting and license headers. Run all hooks manually with 'pre-commit run -a'. ```bash pre-commit install ``` ```bash pre-commit run -a ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/qoroquantum/divi/blob/main/CONTRIBUTING.md Synchronize project dependencies using uv. Use the --extra flag to include AI-specific dependencies. ```bash uv sync ``` ```bash uv sync --extra ai # divi-ai dependencies ``` -------------------------------- ### Supervised Training with QNN Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/quantum_neural_networks.rst Example of setting up and running a QNN for supervised classification. It demonstrates defining training data, labels, and configuring the QNN with a feature map, ansatz, optimizer, and backend. ```python import numpy as np from qiskit.circuit.library import CXGate, RYGate, RZGate from divi.qprog import QNN, AngleEmbedding, GenericLayerAnsatz from divi.qprog.optimizers import ScipyMethod, ScipyOptimizer from divi.backends import MaestroSimulator X_train = np.array([[0.1, 0.2], [0.3, 0.5], [2.0, 2.1], [2.3, 2.4]]) y_train = np.array([-1.0, -1.0, 1.0, 1.0]) # one label per sample clf = QNN( n_qubits=2, feature_map=AngleEmbedding(rotation="Y"), ansatz=GenericLayerAnsatz( gate_sequence=[RYGate, RZGate], entangler=CXGate, entangling_layout="linear", ), feature_batch=X_train, labels=y_train, loss_fn="squared_error", # default; or a callable (pred, label) -> float n_layers=2, optimizer=ScipyOptimizer(method=ScipyMethod.COBYLA), max_iterations=5, backend=MaestroSimulator(), seed=1997, ) clf.run(perform_final_computation=False) ``` -------------------------------- ### Install Divi with AI Features Source: https://github.com/qoroquantum/divi/blob/main/README.md Install Divi along with its AI coding assistant features. This command includes the necessary dependencies for the AI component. ```bash pip install qoro-divi[ai] divi-ai ``` -------------------------------- ### Sample Solution from Pre-Trained Parameters Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/core_concepts.rst Directly sample the solution distribution using pre-trained parameters without running the optimization loop. This is the most efficient way to get results when parameters are already known. ```python # Skip the training loop entirely — just sample with the known-good # parameters and decode the result. vqe_sample = VQE(molecule=molecule, n_layers=2, backend=MaestroSimulator()) vqe_sample.sample_solution(best_params) print(vqe_sample.eigenstate) ``` -------------------------------- ### Graph Partitioning with PartitioningProgramEnsemble Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/combinatorial_optimization_qaoa_pce.rst Use PartitioningProgramEnsemble with GraphPartitioningConfig for large graphs that exceed quantum hardware limitations. This example sets up a MaxCut problem with partitioning configuration and executes the ensemble workflow. ```python import networkx as nx from divi.qprog.problems import MaxCutProblem, GraphPartitioningConfig from divi.qprog.workflows import PartitioningProgramEnsemble from divi.qprog.optimizers import ScipyMethod, ScipyOptimizer from divi.backends import MaestroSimulator # Large graph large_graph = nx.erdos_renyi_graph(20, 0.3) # Configure partitioning config = GraphPartitioningConfig( max_n_nodes_per_cluster=8, # Maximum nodes per quantum partition minimum_n_clusters=3, # Minimum number of partitions (optional) partitioning_algorithm="metis" # Algorithm: "spectral", "metis", or "kernighan_lin" ) # Create the problem with partitioning config problem = MaxCutProblem(large_graph, config=config) ensemble = PartitioningProgramEnsemble( problem=problem, n_layers=2, optimizer=ScipyOptimizer(method=ScipyMethod.NELDER_MEAD), max_iterations=10, backend=MaestroSimulator(), ) # Execute workflow ensemble.create_programs() ensemble.run(blocking=True) # Aggregate results from all partitions quantum_solution, energy = ensemble.aggregate_results() print(f"MaxCut value: {energy}") print(f"Total circuits executed: {ensemble.total_circuit_count}") ``` -------------------------------- ### QAOA with QDrift Trotterization Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/combinatorial_optimization_qaoa_pce.rst Example of configuring and running QAOA with the QDrift randomized Trotterization strategy. This is useful for reducing circuit depth on noisy hardware by approximating the cost Hamiltonian. ```python import networkx as nx from divi.qprog import QAOA from divi.hamiltonians import QDrift from divi.qprog.problems import MaxCutProblem from divi.qprog.optimizers import ScipyMethod, ScipyOptimizer from divi.backends import MaestroSimulator G = nx.erdos_renyi_graph(12, 0.3, seed=1997) qdrift = QDrift( keep_fraction=0.2, sampling_budget=5, n_hamiltonians_per_iteration=3, sampling_strategy="weighted", seed=1997, ) qaoa = QAOA( MaxCutProblem(G), n_layers=2, trotterization_strategy=qdrift, optimizer=ScipyOptimizer(method=ScipyMethod.NELDER_MEAD), max_iterations=10, backend=MaestroSimulator(), ) qaoa.run() ``` -------------------------------- ### Testing RST Code Snippets Source: https://github.com/qoroquantum/divi/blob/main/AGENTS.md Run `make test-snippets` in the `docs` directory after changing user-guide examples to ensure they are correctly processed. CI also runs this test. ```bash cd docs && make test-snippets ``` -------------------------------- ### QAOA for Max-Clique Problem Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/combinatorial_optimization_qaoa_pce.rst Example of finding the maximum clique in a graph using QAOA. Requires networkx, divi, and a backend simulator. ```python import networkx as nx from divi.qprog import QAOA from divi.qprog.problems import MaxCliqueProblem from divi.qprog.optimizers import ScipyMethod, ScipyOptimizer from divi.backends import MaestroSimulator # Create a graph G = nx.bull_graph() qaoa_problem = QAOA( MaxCliqueProblem(G, is_constrained=True), n_layers=2, optimizer=ScipyOptimizer(method=ScipyMethod.NELDER_MEAD), max_iterations=10, backend=MaestroSimulator(), ) qaoa_problem.run() print(f"Quantum Solution: {set(qaoa_problem.solution)}") print(f"Total circuits: {qaoa_problem.total_circuit_count}") # Get top-N solutions by probability top_solutions = qaoa_problem.get_top_solutions(n=5, include_decoded=True) print("\nTop 5 solutions by probability:") for i, sol in enumerate(top_solutions, 1): print(f"{i}. Nodes: {sol.decoded} (probability: {sol.prob:.2%})") ``` -------------------------------- ### Train a Variational Classifier with QNN Source: https://github.com/qoroquantum/divi/blob/main/docs/source/quickstart.rst Use QNN to train a variational classifier. This example sets up a QNN with a specified feature map, ansatz, and optimizer, then runs the training process. ```python import numpy as np from qiskit.circuit.library import CXGate, RYGate, RZGate from divi.qprog import QNN, AngleEmbedding, GenericLayerAnsatz from divi.qprog.optimizers import ScipyMethod, ScipyOptimizer from divi.backends import MaestroSimulator qnn = QNN( n_qubits=2, feature_map=AngleEmbedding(rotation="Y"), ansatz=GenericLayerAnsatz( gate_sequence=[RYGate, RZGate], entangler=CXGate, entangling_layout="linear", ), feature_batch=np.array([[0.1, 0.2], [2.0, 2.1]]), max_iterations=5, optimizer=ScipyOptimizer(method=ScipyMethod.COBYLA), backend=MaestroSimulator(), ) qnn.run(perform_final_computation=False) ``` -------------------------------- ### Submit Circuits to QoroService Source: https://github.com/qoroquantum/divi/blob/main/docs/source/quickstart.rst Submit circuits to the Qoroquantum cloud service for simulation. This example defines a Bell pair circuit in OpenQASM 2.0 and submits it using QoroService with a specific simulator cluster. ```python from divi.backends import QoroService, JobConfig # Bell pair: H + CNOT, then measure both qubits (OpenQASM 2.0) qasm = ( 'OPENQASM 2.0;\n' 'include "qelib1.inc";\n' 'qreg q[2];\n' 'creg c[2];\n' 'h q[0];\n' 'cx q[0],q[1];\n' 'measure q[0] -> c[0];\n' 'measure q[1] -> c[1];\n' ) service = QoroService() # Uses QORO_API_KEY from .env file result = service.submit_circuits( {"my_circuit": qasm}, override_job_config=JobConfig(simulator_cluster="qoro_maestro"), ) ``` -------------------------------- ### Initialize QiskitSimulator for Reproducible Noisy Simulation Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/backends.rst Use QiskitSimulator to wrap Qiskit's AerSimulator for thread-count control and Qiskit-native noise configuration. This example demonstrates setting up a backend for reproducible noisy simulations with a specified number of shots, processes, and a simulation seed. ```python from divi.backends import QiskitSimulator # Reproducible noisy simulation backend = QiskitSimulator( shots=10000, n_processes=8, qiskit_backend="auto", # Auto-select a Qiskit fake backend by qubit count simulation_seed=42 # Deterministic results for debugging ) ``` -------------------------------- ### Run Documentation Snippet Tests Source: https://github.com/qoroquantum/divi/blob/main/docs/source/development/building_docs.rst Executes Python examples embedded in documentation files using Sybil. Use 'make test-snippets-fast' or 'PYTEST_ADDOPTS=-x make test-snippets' to stop at the first failure during debugging. ```bash cd docs make test-snippets ``` ```bash make test-snippets-fast ``` -------------------------------- ### Get Top Solutions with Feasibility Filtering/Repairing Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/routing.rst Demonstrates how to retrieve top solutions from a QAOA run, specifying how to handle feasibility. 'filter' keeps only feasible solutions, while 'repair' projects infeasible ones to the nearest valid solution before ranking. ```python # PHQC mode (arXiv:2511.14296, Algorithm 4): keep only feasible # solutions, rank by objective energy (not probability). solutions = qaoa.get_top_solutions(n=5, feasibility="filter") # Repair infeasible solutions before ranking by energy. solutions = qaoa.get_top_solutions(n=5, feasibility="repair") ``` -------------------------------- ### Serve Built Documentation Source: https://github.com/qoroquantum/divi/blob/main/AGENTS.md Serve the pre-built documentation by navigating to the 'docs/' directory and running 'make serve'. ```bash cd docs make serve ``` -------------------------------- ### Run Tutorial with Backend Flags Source: https://github.com/qoroquantum/divi/blob/main/tutorials/README.md Run Divi tutorials that use `get_backend()` with specific CLI flags to select the backend or sampling method. ```bash python tutorials/optimization/qaoa_graph_problems.py --local-qiskit ``` ```bash python tutorials/optimization/qaoa_graph_problems.py --cloud-maestro ``` ```bash python tutorials/optimization/qaoa_graph_problems.py --local-qiskit --force-sampling ``` -------------------------------- ### Serve Built Divi Documentation Source: https://github.com/qoroquantum/divi/blob/main/CONTRIBUTING.md Serve the pre-built Divi documentation locally to preview the final output. ```bash cd docs make serve ``` -------------------------------- ### Install specific Divi nightly build Source: https://github.com/qoroquantum/divi/blob/main/docs/source/index.rst Install a specific nightly development build of Divi by pinning the version number, including the date. Use this for reproducible nightly installations. ```bash pip install qoro-divi==0.8.0.dev20260305 ``` -------------------------------- ### Build Documentation Source: https://github.com/qoroquantum/divi/blob/main/AGENTS.md Build the project documentation by navigating to the 'docs/' directory and running 'make build'. Ensure 'make clean' is run beforehand. ```bash cd docs make build ``` -------------------------------- ### Run a Divi Tutorial Source: https://github.com/qoroquantum/divi/blob/main/tutorials/README.md Execute any Divi tutorial script by pointing Python at the file from the repository root. ```bash python tutorials/optimization/qaoa_graph_problems.py ``` -------------------------------- ### Install latest Divi nightly build Source: https://github.com/qoroquantum/divi/blob/main/docs/source/index.rst Install the most recent nightly development build of Divi. These builds are published daily and may contain unstable features. ```bash pip install qoro-divi --pre ``` -------------------------------- ### Select Divi Execution Backend Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/core_concepts.rst Demonstrates how to instantiate and select different Divi backends, such as a local simulator or a cloud service. This allows swapping execution environments without changing the program code. ```python from divi.qprog import VQE from divi.backends import MaestroSimulator, QoroService local_backend = MaestroSimulator(shots=1000) # Development/testing cloud_backend = QoroService(auth_token="your-api-key") # Production/cloud backend = local_backend # Swap to cloud_backend without changing program code vqe = VQE(molecule=molecule, backend=backend) ``` -------------------------------- ### Python Docstring Example Source: https://github.com/qoroquantum/divi/blob/main/docs/source/development/building_docs.rst Example of a Google-style docstring for a Python method, including type hints, arguments, return values, and potential exceptions. This format is recommended for Sphinx's autodoc extension. ```python def optimize_circuit(self, circuit: Circuit, method: str = "default") -> Circuit: """Optimize a quantum circuit using the specified method. Args: circuit: The quantum circuit to optimize method: Optimization method to use Returns: The optimized circuit Raises: ValueError: If the method is not supported """ pass ``` -------------------------------- ### QuEPP Shallow Circuit Warning Example Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/improving_results_qem.rst This is an example of a user warning emitted by QuEPP when the truncation order K replaces a large fraction of non-Clifford rotations, indicating potential degradation in mitigation quality on shallow circuits. ```text UserWarning: QuEPP: truncation order K=2 replaces a large fraction of the 4 non-Clifford rotations (50%). Mitigation quality may degrade on shallow circuits — consider reducing truncation_order or using a deeper circuit. ``` -------------------------------- ### QUBO Partitioning with QAOA and PCE Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/combinatorial_optimization_qaoa_pce.rst Demonstrates running partitioned QUBO problems using PartitioningProgramEnsemble with different quantum routines: QAOA (default) and PCE. This includes setting up BinaryOptimizationProblem with decomposers and composers, and configuring PCE-specific parameters. ```python import dimod import hybrid from qiskit.circuit.library import RYGate, RZGate from divi.qprog import InterpolationStrategy from divi.qprog.problems import BinaryOptimizationProblem from divi.qprog.workflows import PartitioningProgramEnsemble from divi.qprog.algorithms import GenericLayerAnsatz from divi.qprog.optimizers import ScipyMethod, ScipyOptimizer from divi.backends import MaestroSimulator def run_partitioned(ensemble): ensemble.create_programs() ensemble.run() return ensemble.aggregate_results() large_bqm = dimod.generators.gnp_random_bqm(25, 0.5, vartype="BINARY") decomposer = hybrid.EnergyImpactDecomposer(size=5) optimizer = ScipyOptimizer(method=ScipyMethod.COBYLA) backend = MaestroSimulator() # --- QAOA partitions (default ``quantum_routine``): add a composer --- problem = BinaryOptimizationProblem( large_bqm, decomposer=decomposer, composer=hybrid.SplatComposer(), ) ensemble = PartitioningProgramEnsemble( problem=problem, n_layers=2, optimizer=optimizer, max_iterations=10, backend=backend, ) sol_qaoa, energy_qaoa = run_partitioned(ensemble) # --- PCE partitions --- problem = BinaryOptimizationProblem(large_bqm, decomposer=decomposer) ensemble = PartitioningProgramEnsemble( problem=problem, quantum_routine="pce", ansatz=GenericLayerAnsatz([RYGate, RZGate]), n_layers=2, encoding_type="dense", alpha=2.0, optimizer=optimizer, max_iterations=10, backend=backend, ) ``` -------------------------------- ### Clone Divi Repository Source: https://github.com/qoroquantum/divi/blob/main/CONTRIBUTING.md Clone your forked repository to start making changes. ```bash git clone https://github.com/your-username/divi.git cd divi ``` -------------------------------- ### Example of Incorrect Cross-Referencing Source: https://github.com/qoroquantum/divi/blob/main/AGENTS.md Do not use top-level re-exports for cross-references as they may not resolve correctly. ```rst :class:`~divi.qprog.VQE` ``` -------------------------------- ### Build Divi Documentation Source: https://github.com/qoroquantum/divi/blob/main/CONTRIBUTING.md Build the Divi documentation locally by navigating to the docs directory and running the 'make build' command. ```bash cd docs make build ``` -------------------------------- ### Get the Latest Checkpoint Path Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/resuming_long_runs.rst Finds and returns the path to the most recent checkpoint in a given directory. ```python from divi.qprog.checkpointing import get_latest_checkpoint latest = get_latest_checkpoint(Path("my_checkpoints")) if latest: print(f"Latest checkpoint: {latest}") ``` -------------------------------- ### Example of Correct Cross-Referencing Source: https://github.com/qoroquantum/divi/blob/main/AGENTS.md Use the submodule path for cross-references to ensure they resolve correctly. Avoid using top-level re-exports. ```rst :class:`~divi.qprog.algorithms.VQE` ``` -------------------------------- ### Develop Divi Documentation with Live Reload Source: https://github.com/qoroquantum/divi/blob/main/CONTRIBUTING.md Set up a live development environment for the Divi documentation. Changes will be reflected automatically upon saving. ```bash cd docs make dev ``` -------------------------------- ### Get Information for a Specific Checkpoint Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/resuming_long_runs.rst Retrieves detailed information about a single checkpoint, including its iteration, timestamp, size, and validity. ```python from divi.qprog.checkpointing import get_checkpoint_info info = get_checkpoint_info(Path("my_checkpoints/checkpoint_005")) print(f"Iteration: {info.iteration}") print(f"Timestamp: {info.timestamp}") print(f"Size: {info.size_bytes} bytes") print(f"Valid: {info.is_valid}") ``` -------------------------------- ### Initialize Nelder-Mead Optimizer Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/optimizers.rst Set up the ScipyOptimizer to use the Nelder-Mead method for gradient-free local optimization. ```python from divi.qprog.optimizers import ScipyOptimizer, ScipyMethod optimizer = ScipyOptimizer(method=ScipyMethod.NELDER_MEAD) ``` -------------------------------- ### Run pytest with coverage Source: https://github.com/qoroquantum/divi/blob/main/docs/source/development/testing.rst Execute pytest with coverage enabled. Generates HTML and terminal reports. Requires uv and pytest to be installed. ```bash uv run pytest --cov=divi --cov-report=html --cov-report=term-missing ``` -------------------------------- ### Initialize QiskitSimulator to Mimic Real Hardware Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/backends.rst Configure QiskitSimulator to use a specific Qiskit fake backend, such as FakeManilaV2, to mimic realistic noise models. This is useful when you need to test your quantum programs against a noise profile similar to actual hardware. ```python # Noisy simulation to mimic real hardware from qiskit_ibm_runtime.fake_provider import FakeManilaV2 backend = QiskitSimulator( shots=5000, qiskit_backend=FakeManilaV2(), # Use a fake backend with a realistic noise model n_processes=2 ) ``` -------------------------------- ### Defining a HUBO Problem Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/combinatorial_optimization_qaoa_pce.rst Example of defining a Higher-Order Binary Optimization (HUBO) problem using a dictionary. Variables can be any hashable type. ```python hubo = { ("a",): -2.0, # linear ("a", "b"): 1.5, # quadratic ("a", "b", "c"): 2.0, # cubic } Variables can use any hashable labels (strings, integers, etc.). ``` -------------------------------- ### Configure QUBO Characterization Options Source: https://github.com/qoroquantum/divi/blob/main/docs/source/tools/qubo_characterization.rst Set up analysis options for QUBO characterization. Use this to enable parameter sweeps, sensitivity analysis, and auto-tuning of the penalty parameter. ```python from divi.backends import CharacterizationOptions opts = CharacterizationOptions( parameter_sweep=True, # sweep γ, β server-side sensitivity=True, # per-qubit fragility report auto_tune=True, # recommend a penalty λ ansatz={"mixer": "x", "layers": 1}, ) ``` -------------------------------- ### ExecutionResult Example Data Format Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/backends.rst Illustrates the structure of the 'results' attribute within an ExecutionResult object, showing circuit labels and their corresponding execution outcomes. ```python [ {"label": "circuit_0", "results": {"00": 500, "11": 500}}, {"label": "circuit_1", "results": {"01": 1000}} ] ``` -------------------------------- ### Custom Stage Validation Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/pipelines.rst Implement custom validation logic for pipeline stages by overriding the 'validate' method. This example ensures a MeasurementStage follows 'MyStage'. ```python from divi.pipeline.abc import ContractViolation class MyStage(BundleStage): def validate(self, before, after): if not any(isinstance(s, MeasurementStage) for s in after): raise ContractViolation( "MyStage requires a MeasurementStage after it." ) ``` -------------------------------- ### Initialize COBYLA Optimizer Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/optimizers.rst Instantiate the ScipyOptimizer with the COBYLA method, suitable for constrained optimization problems without gradients. ```python from divi.qprog.optimizers import ScipyOptimizer, ScipyMethod optimizer = ScipyOptimizer(method=ScipyMethod.COBYLA) ``` -------------------------------- ### Divi AI Development Tools Source: https://github.com/qoroquantum/divi/blob/main/docs/source/tools/divi_ai.rst Commands for Divi contributors to manage the search index, inspect prompts, and run evaluations. Ensure AI dependencies are installed first. ```bash python -m divi.ai help # Show commands and workflow overview ``` ```bash python -m divi.ai build # Rebuild the FAISS index from source ``` ```bash python -m divi.ai search # Interactive search against the index ``` ```bash python -m divi.ai inspect # Inspect assembled prompts (no LLM) ``` ```bash python -m divi.ai eval # Run eval queries, save results ``` ```bash python -m divi.ai compare # Compare two eval runs side-by-side ``` -------------------------------- ### Adaptive Iterations for IterativeQAOA Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/combinatorial_optimization_qaoa_pce.rst Configure IterativeQAOA with a callable for max_iterations_per_depth to adaptively allocate more iterations to deeper circuits. This example uses a lambda function for dynamic iteration budgeting. ```python iterative = IterativeQAOA( MaxCutProblem(graph), max_depth=5, strategy=InterpolationStrategy.FOURIER, max_iterations_per_depth=lambda depth: 10 + 5 * depth, convergence_threshold=1e-4, # stop early if improvement is negligible backend=MaestroSimulator(shots=5000), optimizer=ScipyOptimizer(method=ScipyMethod.COBYLA), ) ``` -------------------------------- ### Initialize CMA-ES Optimizer Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/optimizers.rst Set up the PymooOptimizer to utilize the CMA-ES method for derivative-free optimization of non-linear problems. ```python from divi.qprog.optimizers import PymooOptimizer, PymooMethod optimizer = PymooOptimizer(method=PymooMethod.CMAES) ``` -------------------------------- ### Initialize and Run Time Evolution Trajectory Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/hamiltonian_time_evolution.rst Sets up a TimeEvolutionTrajectory with a specified Hamiltonian, time points, and observable, then runs the simulation on a backend and aggregates the results. The visualization function can be called to plot the expectation value of the observable over time. ```python import math import numpy as np import pennylane as qp from divi.backends import MaestroSimulator from divi.qprog import TimeEvolutionTrajectory backend = MaestroSimulator(shots=5000) trajectory = TimeEvolutionTrajectory( hamiltonian=qp.PauliX(0), time_points=np.linspace(0.01, math.pi, 20).tolist(), observable=qp.PauliZ(0), backend=backend, ) trajectory.create_programs() trajectory.run(blocking=True) results = trajectory.aggregate_results() # results: {0.01: 0.9996, 0.166: 0.944, ..., 3.14: 0.998} trajectory.visualize_results() # plots ⟨Z⟩ vs time ``` -------------------------------- ### Plot PCA Scan with Trajectory Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/visualization.rst Visualizes the optimization path as a connected line on top of the PCA scan heatmap. Start and end points are marked with distinct markers. ```python pca_scan.plot(show=True, show_trajectory=True) ``` -------------------------------- ### Analyze Top Solutions with QAOA Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/core_concepts.rst Demonstrates how to run a QAOA problem, retrieve the top solutions by probability, and print their bitstrings, probabilities, and energies. It also shows how to filter solutions by minimum probability and include decoded values. ```python import dimod import numpy as np from divi.qprog import QAOA from divi.qprog.problems import BinaryOptimizationProblem from divi.qprog.optimizers import ScipyMethod, ScipyOptimizer from divi.backends import MaestroSimulator # Create a QUBO problem bqm = dimod.generators.gnp_random_bqm(10, 0.5, vartype="BINARY", random_state=1997) qubo_array = bqm.to_numpy_matrix() qaoa_problem = QAOA( BinaryOptimizationProblem(qubo_array), n_layers=2, optimizer=ScipyOptimizer(method=ScipyMethod.COBYLA), max_iterations=10, backend=MaestroSimulator(shots=5000), ) qaoa_problem.run() # Get top 10 solutions by probability top_solutions = qaoa_problem.get_top_solutions(n=10) print("Top 10 solutions:") for i, sol in enumerate(top_solutions, 1): # Convert bitstring to numpy array for energy calculation solution_array = np.array([int(bit) for bit in sol.bitstring]) solution_dict = {var: int(val) for var, val in zip(bqm.variables, solution_array)} energy = bqm.energy(solution_dict) print(f"{i}. {sol.bitstring}: prob={sol.prob:.2%}, energy={energy:.4f}") # Filter solutions by minimum probability high_prob_solutions = qaoa_problem.get_top_solutions(n=5, min_prob=0.01) print(f"\nSolutions with probability >= 1%: {len(high_prob_solutions)}") # Get solutions with decoded values (for graph problems, this would be node lists) # For QUBO problems, decoded values are NumPy arrays decoded_solutions = qaoa_problem.get_top_solutions(n=5, include_decoded=True) for sol in decoded_solutions: print(f"Bitstring: {sol.bitstring}, Decoded: {sol.decoded}") ``` -------------------------------- ### Basic VQE with QuEPP Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/improving_results_qem.rst Demonstrates the basic usage of VQE with the QuEPP error mitigation protocol. Ensure necessary libraries are imported and the molecule is defined. ```python from divi.circuits.quepp import QuEPP from divi.qprog import VQE from divi.backends import QiskitSimulator import pennylane as qp import numpy as np h2_molecule = qp.qchem.Molecule( symbols=["H", "H"], coordinates=np.array([[0.0, 0.0, -0.6614], [0.0, 0.0, 0.6614]]) ) vqe = VQE( molecule=h2_molecule, qem_protocol=QuEPP(truncation_order=2), backend=QiskitSimulator(qiskit_backend="auto"), max_iterations=10, ) vqe.run() print(f"Mitigated energy: {vqe.best_loss:.6f}") ``` -------------------------------- ### Implement Custom CircuitRunner Backend Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/core_concepts.rst Example of how to implement a custom backend by inheriting from CircuitRunner and defining the submit_circuits method. This is used when you need to add a new execution backend to Divi. ```python from divi.backends import ExecutionResult class MyCustomBackend(CircuitRunner): def submit_circuits(self, circuits: Mapping[str, str], **kwargs) -> ExecutionResult: # Your custom execution logic here # Return ExecutionResult(results=...) for sync backends # or ExecutionResult(job_id=...) for async backends pass ``` -------------------------------- ### Enable and Disable Logging in Python Source: https://github.com/qoroquantum/divi/blob/main/docs/source/api_reference/reporting.rst Demonstrates how to control logging for quantum program execution. Logging is enabled by default upon import. ```python from divi.reporting import enable_logging, disable_logging # Enable logging (called automatically on import) enable_logging() # Disable logging if needed disable_logging() ``` -------------------------------- ### Run Qiskit QuantumCircuit with CircuitPipeline Source: https://github.com/qoroquantum/divi/blob/main/docs/source/user_guide/pipelines.rst Demonstrates how to use the CircuitPipeline with a Qiskit QuantumCircuit. Imports necessary components and defines a pipeline with QiskitSpecStage and MeasurementStage. ```python from qiskit import QuantumCircuit from divi.pipeline import CircuitPipeline, PipelineEnv from divi.pipeline.stages import QiskitSpecStage, MeasurementStage from divi.backends import MaestroSimulator pc = QuantumCircuit(2, 2) pc.h(0) pc.cx(0, 1) pc.measure([0, 1], [0, 1]) pipeline = CircuitPipeline(stages=[ QiskitSpecStage(), MeasurementStage(), ]) env = PipelineEnv(backend=MaestroSimulator()) result = pipeline.run(initial_spec=qc, env=env) print(result.value) # {"00": ~0.5, "11": ~0.5} ```