Manuscript Offprint
arXiv:2609.30914Cross-Backend QIEO: Universal Runtime Portability across OpenMP5, CUDA, HIP, and Multi-Language Interfaces
Aman Mittal
BQP
Bengaluru, India
Ferdin Sagai Don Bosco
BQP
Bengaluru, India
Kasturi Venkata Srikanth
BQP
Bengaluru, India
Abhishek Singh
BQP
Bengaluru, India
Aditya Singh
BQP
Bengaluru, India
Abhishek Chopra
BQP
Bengaluru, India
Abstract—Quantum-inspired algorithms emulate quantum mechanical principles, such as, superposition, interference, and probabilistic amplitude evolution, on classical hardware by representing candidate solutions as qubit vectors and evolving them through rotation-gate operators. This approach offers higher optimization performance without physical qubits, and has been shown to achieve order-of-magnitude speedups (10–80×) over traditional solvers on combinatorial, high-dimensional NP-hard problems.
A critical barrier to adoption, however, is the lack of a unified execution framework that delivers both algorithmic performance and hardware portability. We present Cross-Backend Quantum Inspired Evolutionary Optimizer (QIEO), the runtime core of BQP's BQPhy QuantumNOW solver, which addresses this gap through a single-source-of-truth architecture. One C++ implementation of the QIEO algorithm is compiled once per hardware target and exposed to multiple high-level languages via thin binding layers. The framework dispatches to CPU (sequential), OpenMP 5 (multi-core), CUDA (NVIDIA), and HIP (AMD) backends at runtime, adapting kernels to each device's memory hierarchy and warp/wavefront execution model.
Multi-language accessibility is provided through a header-only C++ library, a Python wheel (via pybind11), a MATLAB toolbox (via the MEX API), and a Julia package (via CxxWrap), making the solver immediately usable across HPC, machine learning, scientific computing, and industrial simulation workflows. Experimental results demonstrate up to 72× speedup over a sequential CPU baseline on large-scale benchmark problems, with negligible cross-language interface overhead (<1.2%).
The framework’s real-world utility is validated through binding demonstrations that share the identical C++ runtime. BQ-Phy’s Python library is demonstrated on a neural network hyperparameter optimisation (Python API, PyTorch) achieving 88.60% test accuracy on MNIST. BQPhy’s MATLAB’s Toolkit is tested on wind farm layout optimisation attaining MWh/yr, which is statistically indistinguishable from particle swarm optimisation and +7.6% above genetic algorithms on a 32-variable constrained engineering problem. The Julia package tackles the Lotka–Volterra parameter estimation where BQPhy replaces native Julia solvers (Optim.jl, BlackBoxOptim.jl, CMAEvolutionStrategy.jl) on the same residual, cutting mean SSE by versus Optim.NelderMead.
Index Terms—quantum-inspired evolutionary optimization, heterogeneous computing, performance portability, OpenMP, CUDA, HIP, multi-language interface, Julia, CxxWrap, Lotka–Volterra, hardware abstraction layer, single source of truth
I. INTRODUCTION
Quantum computing promises transformational advances for combinatorial, high-dimensional optimization; yet fault-tolerant, large-scale quantum hardware remains an open engineering challenge [2]. Quantum-Inspired Evolutionary Algorithms(QIEAs) bridge this gap by transplanting quantum mechanical principles, such as, qubit representation, superposition, and rotation-gate updates [1], onto classical HPC, achieving superior convergence characteristics relative to classical metaheuristics without requiring physical qubits.
Despite algorithmic maturity, a critical bottleneck persists, namely, efficient and portable execution across heterogeneous computing architectures. Modern HPC clusters are inherently heterogeneous, pairing multi-core CPUs with GPU accelerators from multiple vendors. Targeting these systems requires navigating disjoint programming ecosystems: OpenMP for shared-memory CPU parallelism [7], CUDA for NVIDIA GPUs [3], and HIP for AMD devices [8]. Each platform exposes distinct execution models, memory hierarchies, and concurrency primitives, forcing practitioners to maintain vendor-specific codebases that erode both portability and maintainability.
General-purpose performance-portability frameworks such as Kokkos [4] and RAJA [5] partially address this challenge by abstracting parallel execution and memory management. However, they are designed for generic numerical workloads and do not incorporate domain-specific optimizations for quantum-inspired computation, namely probabilistic qubit state updates, trigonometric rotation operators, and population-level synchronization barriers. Similarly, SYCL [6] offers a single-source C++ model for heterogeneous systems but provides no algorithmic scaffolding for Quantum Inspired Evolutionary Optimizer (QIEO) primitives.
This work makes the following novel contributions:
• Unified QIEO Runtime: The first backend-agnostic execution framework specifically designed for quantum-inspired evolutionary optimization, supporting CPU, OpenMP 5, CUDA, and HIP from a single algorithmic source.
• Algorithm–Architecture Co-Design: A disciplined separation of QIEO algorithmic phases, namely Quantum Information Processing(QIP), Fitness Evaluation(FE), Classical Information Processing(CIP), from hardware-specific kernel specializations, enabling near-native performance on each target without modifying core logic.
• Single-Source-of-Truth Binding Architecture: A lightweight, layered binding design that exposes the identical C++ runtime to Python (pybind11 [9]), MATLAB (MEX API), and Julia (CxxWrap [11]) with <1.2% measured interface overhead on the Python and MATLAB paths, eliminating per-language re-implementation.
• Comprehensive Evaluation: Benchmarks across diverse hardware and problem scales demonstrating up to speedup over sequential baselines, with portability validated on NVIDIA(V100, A100) and AMD (MI300X) GPUs.
• Real-World Multi-Language Validation: Application-level demonstrations using the identical C++ runtime, covering, neural network hyperparameter optimisation (Python/PyTorch), wind farm layout optimisation (MATLAB/Global Optimization Toolbox), and Lotka–Volterra parameter estimation (Julia/CxxWrap) against the Julia packages practitioners already use, confirming that the single-source-of-truth architecture delivers competitive performance against domain-specific baselines without per-language re-implementation.
The remainder of this paper is organized as follows. Section II surveys related work. Section III presents the system architecture. Section IV reports benchmark results. Section V reports results for various applications. Section VII concludes. Appendix A lists equivalent Rastrigin drivers in C++, Python, MATLAB, and Julia. Appendix B lists the Python hyperparameter-optimisation, MATLAB wind-farm, and Julia Lotka–Volterra drivers.
A. Quantum-Inspired Evolutionary Algorithms
QIEAs were formalized by Han and Kim [1], who introduced qubit chromosome representation and a rotation-gate update operator to guide probabilistic evolution toward optimal solutions. Subsequent work extended this foundation to multi-objective optimization [22], combinatorial problems [20], and continuous parameter spaces [21]. Comprehensive reviews of rotation gate variants and their convergence properties are provided in [19].
Unlike classical genetic algorithms, QIEAs maintain a probability amplitude representation of the solution space, enabling implicit parallelism and improved exploration of the fitness landscape. However, evaluating and updating a population of qubit individuals involves dense trigonometric operations that scale quadratically with problem dimensionality, motivating hardware acceleration. Recent work [25] has demonstrated GPU-based speedups for QIEO kernels, but without a unified, multi-backend abstraction.
B. Portability–Performance Trade-off
Native, vendor-specific programming models such as CUDA [3] and HIP [8] express the computational kernels directly in the device's native language. This affords explicit control over the thread hierarchy, on-chip memory, and intrawarp (or intra-wavefront) synchronization, and thereby permits aggressive, architecture-specific performance engineering. The corresponding cost is fragmentation of the software stack: semantically equivalent QIEO phases must be implemented, tuned, and maintained independently for each vendor, so that algorithmic evolution incurs a multiplicative development and validation burden.
Performance-portability frameworks invert this trade-off. A single source is written against an abstract execution and memory model (Kokkos [4], RAJA [5], SYCL [6], or OpenMP [7] device offload) and is subsequently lowered onto whichever backend the runtime provides. The application is thereby decoupled from both the accelerator and the vendor language used to program it. That decoupling, however, is realized by an intervening layer that mediates kernel launch, data motion, and specialization. The resulting overhead precludes a substantial fraction of the performance that is attainable only through the native APIs, i.e., portability is obtained at the expense of efficiency.
Cross-Backend QIEO occupies a third position. The QIEO algorithm, consisting of Q-bit representation, rotation-gate updates, and population-level synchronization, is specified once, as a single source of truth. Execution, by contrast, remains native, i.e. the same algorithmic specification is instantiated as distinct OpenMP, CUDA, and HIP kernels that bind directly to the target's memory hierarchy and SIMD execution model. No portability runtime is interposed between the QIEO primitives and the device. In this design, portability is confined to the algorithmic and dispatch interface, while performance is retained at the vendor-kernel boundary. The framework therefore avoids both the replicated-algorithm cost of purely native development and the abstraction tax of GPU-agnostic programming models.
C. Multi-Language Integration
Bridging high-performance C++ kernels to user-facing environments is a recognized challenge in scientific computing. A mature family of foreign-function and wrapper generators already addresses the language boundary. SWIG [39] produces bindings from a common interface specification to several scripting languages; Boost.Python [40] and Cython [41] specialize that idea for Python, while pybind11 [9] continues the same line with header-only C++11 metaprogramming and very low call overhead. On the commercial side, the MATLAB MEX API [10] exposes native extensions as ordinary MATLAB functions. In the Julia ecosystem, the language's C ABI (ccall) [42] and CxxWrap [11] attach a compiled shared library to Julia types without a second implementation of the algorithm.
The present framework does not replace these mechanisms. It adopts three of them, namely, pybind11, MEX, and CxxWrap, as thin, language-specific facades over a single C++ QIEO runtime. Existing solutions, however, treat language integration as an independent problem from hardware-runtime portability, and therefore yield fragmented ecosystems in which high-performance kernels cannot be reused across languages without re-engineering. The single-source-of-truth architecture resolves that fragmentation by construction, in which one compiled library is linked from every binding.
III. METHODOLOGY AND SYSTEM DESIGN
A. Computational Model
QIEO encodes each candidate solution as a vector of qubits, where the -th qubit is defined by the amplitude pair satisfying [1]. The probability of observing bit value 1 at position is , providing a continuous, differentiable representation of the solution space that subsumes classical binary strings.
- State Representation: The population of individuals is stored as a matrix , where each row contains the and amplitudes for one individual. Classical bit strings are obtained by collapsing each qubit as,
if , else 0.
This stochastic measurement step is embarrassingly parallel across both individuals and bit positions, making it a prime candidate for GPU kernel acceleration.
- Core Operators: Quantum Information Processing (QIP): Each qubit amplitude is updated via a rotation gate parameterized by angle [1]:
The rotation angle magnitude and sign are determined by a lookup table [1] that steers each qubit toward the best observed solution (the “best individual”).
Classical Information Processing (CIP): After measurement, classical fitness is evaluated for each individual. The best individual b is identified, and for the next generation is computed from the comparison between and . A controller adaptively scales step sizes to balance exploration and exploitation across generations.
The full three-phase optimization loop is summarized in previous works [43].
B. System Design Objectives
Cross-Backend QIEO is guided by three primary design objectives that collectively distinguish it from prior work.
- Performance Portability: The framework must achieve near-native throughput on CPUs and GPUs from multiple vendors without per-backend algorithm re-implementation. This is realized through the Hardware Abstraction Layer (HAL). The HAL decouples algorithmic phases from execution targets through a compile-time policy pattern. Each backend provides specialisations of three core kernel templates: measure_population, evaluate_fitness, and update_qubits. At runtime, the framework queries available hardware and selects the highest-ranked backend for which a compiled specialisation exists.
On CPU, kernels execute sequentially, serving as the reference implementation for correctness validation. On OpenMP, #pragma omp parallel for directives distribute individuals across threads, with SIMD hints applied to the inner rotation-gate loop. On CUDA/HIP, each individual maps to one GPU thread block; the rotation-gate and measurement loops are parallelised across threads within a block, with shared memory used to cache the best individual's bit-string and avoid redundant global memory accesses [3].
-
Algorithm–Architecture Co-Design: QIEO primitives are mapped to hardware execution models via a disciplined separation of concerns. Algorithmic logic (QIP, CIP, fitness evaluation) is implemented once in portable C++/CUDA and compiled per target; the HAL provides hardware-specific specializations. Table I summarizes the three supported execution modes.
-
Multi-Language Accessibility via Single Source of Truth: The BQPhy QuantumNOW framework embodies a single-source-of-truth (SSOT) architecture [26]: the complete QIEO algorithm, including quantum-inspired primitives, hardware acceleration dispatch, and parameter management, exists as one canonical C++ implementation. High-level language interfaces (Python, MATLAB, Julia) are exposed through thin wrapper bindings that translate language-specific data structures into C++ equivalents and invoke the shared library directly. This pattern guarantees algorithmic consistency across languages, eliminates maintenance divergence, and enables new features to propagate to all interfaces without per-language re-implementation.
Figure 1 illustrates the resulting layered architecture.
C. Usage
Table II summarises the binding mechanism for each supported language. All bindings adhere to a unified interface contract (Table III), ensuring that the same five-step workflow is preserved across environments.
Regardless of language, users follow an identical workflow:
TABLE I EXECUTION MODES SUPPORTED BY THE HARDWARE ABSTRACTION LAYER (HAL)
| Mode | Target | Parallelism Model | Best For | Compile Flag |
|---|---|---|---|---|
| CPU | Single-core CPU | Sequential (scalar) | Debugging, correctness validation, small problems | Default (no flag) |
| OpenMP | Multi-core CPU | Loop parallelism via #pragma omp parallel for; SIMD vectorisation | Mid-scale problems (-) on multi-socket servers | -DUSE_OPENMP=ON |
| GPU/CUDA | NVIDIA GPU (cc ≥ 7.0) | Warp-level parallelism + Thrust reduction algorithms | Large-scale problems () where PCIe transfer is amortised | -DUSE_CUDA=ON |
| GPU/HIP | AMD GPU (GFX9+) | Wavefront-level parallelism; mirrors CUDA kernel structure | Same as CUDA target on AMD hardware | -DUSE_HIP=ON |

Fig. 1. Layered architecture of the BQPhy® QuantumNOW™ framework. A single C++ implementation is compiled once per hardware target and shared across all language bindings, realising the single-source-of-truth principle.
-
Create an optimizer instance
-
Initialize with configuration parameters
a) population size
b) dimensionality
c) bounds
d) maximum generation
-
Define the objective function
-
Execute the optimization with a selected backend
-
Retrieve the best design and fitness value
Appendix A instantiates this contract for the Rastrigin function in all four languages.
IV. BENCHMARK STUDIES
We evaluate Cross-Backend QIEO on three representative benchmark classes: (i) binary combinatorial problems (0/1 Knapsack, ), (ii) continuous global optimization (Rastrigin, Rosenbrock, ), and (iii) a real-world antenna array pattern synthesis problem drawn from industrial use cases. Hardware platforms are: an Intel Xeon Gold 6338 (32 cores, OpenMP baseline), an NVIDIA A100-SXM4 80 GB (CUDA), and an AMD MI300X (HIP).
Table IV reports wall-clock speedup relative to the sequential CPU baseline for a population size of and 1,000 generations.
The CUDA backend achieves a geometric mean speedup of over the sequential baseline, with the Rastrigin-200 case reaching the peak of . The HIP backend on AMD MI300X achieves of the CPU throughput, demonstrating robust cross-vendor portability. OpenMP provides a mean speedup with zero additional hardware beyond the host CPU, making it well-suited for mid-scale deployments.
TABLE II BINDING ARCHITECTURE OVERVIEW
| Language | Library | Mechanism | Role |
|---|---|---|---|
| C++ | Header-only | Direct inclusion | Zero-overhead integration; exposes full API including template parameters for custom fitness functors. |
| Python | pybind11 [9] | C++ template-based Python–C interoperability | Converts Python dict and callable objects into C++ data structures; exposes core runtime as Python classes. |
| MATLAB | MEX API [10] | Native MATLAB C++ interface | Receives struct and function_handle arguments, invokes C++ runtime, returns results as native MATLAB arrays. |
| Julia | CxxWrap [11] | Automatic C++ wrappers around libBQPhy_Optimiser.so | Converts Julia Dict and Function objects into C++ data structures; exposes the runtime as a native Julia module. |
TABLE III UNIFIED INTERFACE CONTRACT ACROSS LANGUAGE BINDINGS
| Step | C++ Core | Python | MATLAB | Julia |
|---|---|---|---|---|
| Initialize | opt.initialize(params) | opt.initialize(dict) | BQPhy_MEX("init", struct) | Optimizer(Dict) |
| Set model | opt.setModel(fn) | opt.set_model(callable) | Pass @function_handle | set_fitness_function!(opt, fn) |
| Run | opt.runOptimization(acc) | opt.run_optimization(acc) | BQPhy_MEX("run", ...) | optimize!(opt; device) |
| Get result | opt.getBestDesign() | opt.get_result() | BQPhy_MEX("result") | get_best_design(opt) |
TABLE IV SPEEDUP OVER SEQUENTIAL CPU BASELINE (, )
| Problem | OpenMP | CUDA (A100) | HIP (MI300X) |
|---|---|---|---|
| Knapsack-512 | |||
| Rastrigin-200 | |||
| Rosenbrock-200 | |||
| Antenna Synth. | |||
| Geometric mean |
V. DEMONSTRATION ON REAL-WORLD APPLICATIONS
A. BQPhy Python library: Neural Network Hyperparameter Optimisation
A key demonstration of the Python binding's real-world utility is its operation as a drop-in hyperparameter optimiser inside a PyTorch [33] training loop. We conduct a two-phase benchmark on the MNIST handwritten-digit dataset [27]: a variable-budget study (each baseline uses its default evaluation count) and an iso-budget study (all methods fixed at 240 evaluations), isolating search algorithm quality from evaluation count.
- Hyperparameter Optimisation Baselines: Ray Tune [28] is a scalable, distributed HPO framework built on the Ray runtime. It supports a broad suite of search algorithms (random search, HyperBand [32], Population-Based Training) and is designed for massively parallel, multi-node execution. Its primary overhead arises from the Ray actor system, which serialises trial launching when parallelism is constrained (max_concurrent_trials=1).
Optuna [29] is a define-by-run framework that dynamically constructs search spaces using a Tree-structured Parzen Estimator (TPE) sampler combined with aggressive trial pruning
TABLE V HYPERPARAMETER SEARCH SPACE FOR MNIST OPTIMIZATION
| Variable | Type | Range / Choices |
|---|---|---|
| Learning rate | Continuous | (log-uniform) |
| Hidden units | Integer | [32, 256] |
| Hidden layers | Integer | |
| Activation | Categorical | {ReLU, Tanh, Sigmoid, LeakyReLU} |
| Dropout rate | Continuous | [0.0, 0.5] |
(MedianPruner). Its lightweight design excels when a small per-evaluation budget is available.
Grid Search [30] exhaustively enumerates all combinations of a pre-specified discrete parameter grid. It guarantees full coverage of the grid, but is combinatorially intractable for continuous or high-dimensional spaces, and does not adapt based on observed results [31].
-
Experimental Setup: A fully connected neural network (DynamicNet) is optimised over five mixed-type design variables on MNIST (60,000 training / 10,000 test images, grayscale, 10 classes) [27]; see Table V. All methods minimise the same objective: negative test-set classification accuracy after one training epoch. BQPhy is invoked entirely through its Python API (pybind11 binding, Listing 14) with no modification to the C++ core, directly validating the single-source-of-truth architecture described in Section III-B3.
-
Phase 1 — Variable-Budget Results: Table VI reports results when each method uses its natural evaluation budget: 240 for BQPhy (population 12, generations 20) and 12 for the baselines.
BQPhy delivers competitive accuracy (87.40%) at a per-evaluation cost of only 0.19 s, enabled by GPU-parallel population evaluation (CUDA backend). Ray Tune, despite achiev-
TABLE VI VARIABLE-BUDGET RESULTS ON MNIST
| Method | Evals | Accuracy | Time (s) | s/Eval |
|---|---|---|---|---|
| BQPhy (QIEO) | 240 | 0.8740 | 46.42 | 0.19 |
| Ray Tune | 12 | 0.8760 | 206.92 | 17.24 |
| Optuna | 12 | 0.8640 | 3.41 | 0.28 |
| Grid Search | 12 | 0.8700 | 2.71 | 0.23 |

Fig. 2. Test accuracy under variable and iso-budget (240 evaluations) conditions. BQPhy improves by +1.20 pp; Ray Tune degrades by -0.40 pp under serialised execution.
ing the highest accuracy (87.60%), incurs 17.24 s per evaluation due to Ray actor initialization overhead [28], resulting in a total wall time longer than BQPhy. Optuna and Grid Search complete rapidly but with only 12 evaluations each, yielding suboptimal configurations (86.40% and 87.00%).
- Phase 2 — Iso-Budget Results (240 Evaluations): To isolate search algorithm quality from evaluation count, all methods were re-run with a fixed budget of 240 evaluations. Table VII and Fig. 2 report the full comparison.
a) Accuracy Analysis.: Under iso-budget conditions, Optuna achieves the highest accuracy (89.20%), followed by BQPhy (88.60%), Grid Search (87.60%), and Ray Tune (87.20%). Notably, BQPhy improves by +1.20 percentage points (pp) relative to its variable-budget result, confirming that QIEO's population-level Q-bit exploration exploits additional evaluations effectively [1]. In contrast, Ray Tune's accuracy degrades by -0.40 pp—a direct consequence of serialised trial execution (max_concurrent_trials=1) disrupting its HyperBand scheduler's [32] early-stopping logic, which assumes parallel fidelity ladders.
Grid Search exhausts its discrete combinatorial grid at 216 evaluations ( ), failing to reach the 240-evaluation target and confirming the well-known exponential scaling limitation of exhaustive enumeration [31].
b) Time-Efficiency Analysis.: Table VIII quantifies accuracy-per-second and speedup ratios at iso-budget.
BQPhy achieves a speedup over Ray Tune at the same evaluation count while delivering +1.40 pp higher accuracy. This disproportionate time advantage is explained by two compounding effects: (i) GPU-parallel population evaluation amortises per-trial overhead across 12 individuals simultaneously, reducing effective per-evaluation cost to 0.19 s; and (ii) Ray Tune's actor framework introduces 22.46 s of per-trial scheduling overhead under serialised execution, which does not diminish with additional trials.
Wall-Clock Time: Variable vs Iso-Budget (log scale)

Fig. 3. Wall-clock time (log scale) for variable and iso-budget conditions. Ray Tune requires more wall time than BQPhy under serialized execution at 240 evaluations.
Although Optuna achieves the best absolute accuracy (89.20%), BQPhy attains 88.60%—only 0.60 pp lower—at less wall time (45.05 s vs. 63.30 s), making it the dominant method on the accuracy–time Pareto frontier for practitioners with GPU resources.
c) Search Strategy Comparison.: All four methods converge on shallow single-layer networks (1 hidden layer) and LeakyReLU activations at iso-budget, validating the landscape geometry independently. Key divergences arise in regularisation: BQPhy selects near-zero dropout ( ) while Optuna selects aggressive dropout ( ), yielding a 0.60 pp accuracy difference that warrants further investigation as a landscape multi-modality indicator. Grid Search is constrained to three pre-defined activation choices and misses LeakyReLU entirely, confirming that discrete grids systematically exclude continuous optima [31].
d) Multi-Language Binding Transparency.: The hyperparameter configurations and fitness traces produced through the Python API are identical (to floating-point precision, ) to those obtained by invoking the C++ binary directly. The pybind11 binding layer introduces no algorithmic side-effects, confirming the single-source-of-truth guarantee: BQPhy's Python interface behaves as a first-class scientific computing tool within PyTorch [33] and NumPy [34] workflows without sacrificing reproducibility.
e) Interface Overhead (Binding Cost).: Averaged over five independent runs, the Python binding introduces 0.9% overhead relative to native C++ invocation, consistent with prior measurements in Section IV. This confirms that the 45.05 s wall time is dominated by MNIST training computation, not binding or serialization cost.
TABLE VII ISO-BUDGET RESULTS ON MNIST (240 EVALUATIONS, ALL METHODS)
| Method | Lr | Hidden | Layers | Activation | Dropout | Accuracy | Time (s) |
|---|---|---|---|---|---|---|---|
| BQPhy (QIEO) | 238 | 1 | LeakyReLU | 0.011 | 0.8860 | 45.05 | |
| Ray Tune [28] | 223 | 3 | LeakyReLU | 0.101 | 0.8720 | 5389.79 | |
| Optuna [29] | 227 | 1 | LeakyReLU | 0.398 | 63.30 | ||
| Grid Search [30] | 200 | 1 | ReLU | 0.300 | 0.8760 | 56.60 |
Note: Grid Search exhausted its discrete grid at 216 evaluations (could not reach 240).
TABLE VIII ISO-BUDGET EFFICIENCY METRICS (240 EVALUATIONS)
| Method | Time (s) | s/Eval | Accuracy | Speedup vs. RT |
|---|---|---|---|---|
| BQPhy (QIEO) | 45.05 | 0.19 | 0.8860 | |
| Ray Tune | 5389.79 | 22.46 | (ref.) | |
| Optuna | 63.30 | 0.26 | 0.8920 | |
| Grid Search | 0.8760 |
Grid Search exhausted at 216 evaluations.
B. BQPhy MATLAB Toolkit: Wind Farm Layout Optimisation
A key demonstration of the MATLAB binding’s real-world utility is its operation as a drop-in optimizer inside the Global Optimization Toolbox [38] ecosystem for a challenging industrial engineering design problem: wind farm layout optimization (WFLO). The objective is to place N turbines within a bounded domain such that the farm’s annual energy production (AEP) is maximized while respecting a minimum inter-turbine separation constraint. WFLO is a notoriously difficult continuous optimization problem because the wake interaction between turbines creates a highly multi-modal fitness landscape [36], [37]. A layout that performs well under one wind direction may suffer severe wake losses when the wind shifts, requiring the optimizer to balance competing directional objectives simultaneously.
- Problem Formulation: We consider a m domain with turbines, each having a rotor diameter m and rated power MW. The search space comprises continuous variables representing turbine coordinates.
Wake model: Power losses due to upstream turbine wakes are modeled using the Jensen model [35]. For a turbine located at a downstream distance from an upstream turbine , the fractional velocity deficit at the rotor is
where is the thrust coefficient and is the wake expansion rate (typical for offshore conditions). Multiple wakes are combined via the sum-of-squares rule:
where tests streamwise alignment and lateral wake coverage. The instantaneous power of turbine is obtained from a
TABLE IX 12-SECTOR WIND ROSE USED IN THE BENCHMARK. AZIMUTH IN METEOROLOGICAL CONVENTION ().
| Azimuth (°) | Probability | Azimuth (°) | Probability |
|---|---|---|---|
| 0 | 0.03 | 180 | 0.10 |
| 30 | 0.04 | 210 | 0.12 |
| 60 | 0.05 | 240 | 0.14 |
| 90 | 0.06 | 270 | 0.18 |
| 120 | 0.07 | 300 | 0.08 |
| 150 | 0.10 | 330 | 0.03 |
piecewise-linear power curve with cut-in 3 m/s, rated 12 m/s, and cut-out 25 m/s.
Wind rose: The wind resource is modeled as a Rayleigh distribution (mean 8.5 m/s) discretized into 20 speed bins, combined with a 12-sector directional wind rose (Table IX). The dominant westerlies (270°, 18%) compete with prevailing easterlies (90°, 6%), producing a landscape where a layout aligned for one predominant direction incurs wakes when the wind reverses.
Constraint: A minimum separation of m between any pair of turbines is enforced via a quadratic penalty:
with penalty weight . The composite objective is minimized; a feasible solution has .
- Benchmark Methodology: We conduct an iso-budget statistical study of 20 independent runs at a unified budget of 100 individuals and 500 generations (50,000 function evaluations per solver). Three solvers are compared:
- BQPhy — quantum-inspired evolutionary algorithm (BQPhy_Optimiser MEX binding, );
- GA — genetic algorithm (ga, Global Optimization Toolbox);
- PSO — particle swarm optimisation (particleswarm, Global Optimization Toolbox).
All solvers share the identical objective function and use the same population/swarm size; the run-time timing excludes MEX-loading latency and is averaged over the 20 trials.
- Results and Analysis:
a) Convergence behavior.: Figure 4 shows the mean AEP trajectory across the 20 runs. BQPhy’s early generations are dominated by the spacing penalty (negative AEP values).

Fig. 4. Convergence comparison (mean over 20 runs). BQPhy overtakes PSO at generation 150 and sustains the highest final AEP. GA exhibits the slowest convergence and the widest variance.
until generation 50), after which feasible layouts are discovered and the objective rises steeply. By generation 150, BQPhy overtakes PSO and maintains a modest advantage through generation 500. PSO converges fastest in the first 30 generations due to its velocity-driven attraction mechanism, but plateaus earlier. GA converges most slowly and exhibits the widest confidence band, indicating poor reliability across restarts.

Fig. 5. Final AEP distribution over 20 independent runs (box-and-whisker with individual scatter overlay). BQPhy and PSO are statistically indistinguishable; GA suffers severe outlier runs.
b) Final AEP distribution.: Figure 5 summarises the empirical distribution of final AEP across the 20 runs. The quantitative results are:
• BQPhy: MWh/yr (mean std), median , maximum 374 659.
• PSO: MWh/yr, median , maximum 371 497, two mild outliers.
• GA: MWh/yr, median , maximum 361 177, three severe outliers below 290 000.
BQPhy and PSO achieve statistically indistinguishable mean AEP (p > 0.05, two-sample t-test), while both significantly outperform GA (BQPhy +7.6%, PSO +8.1%). Critically, BQPhy attains the highest peak AEP of any solver in any single run (374 659 MWh/yr, Fig. 6), demonstrating its capacity to discover exceptional configurations that are missed by the other methods in the finite evaluation budget. GA's enormous standard deviation (eight times that of BQPhy) reveals a fundamental reliability deficit: in several runs, GA fails to escape the penalty-dominated region and returns substantially sub-optimal layouts, rendering it impractical for production use without multiple restarts.
c) Layout quality.: Figure 6 visualizes the highest-AEP layout discovered by each solver. BQPhy's configuration exhibits pronounced spatial irregularity: turbines exploit the full domain, including edges and corners, with staggered positions that minimize wake overlap across the competing easterly and westerly wind sectors. PSO's layout is notably more regular and grid-like, a signature of its velocity-attraction mechanism drawing particles toward a consensus configuration that, while safe, leaves energy unrealized. GA's layout shows visible clustering, with several pairs near or at the separation boundary, confirming its difficulty in managing the spacing constraint.
d) Discussion.: The WFLO benchmark demonstrates that the BQPhy MATLAB binding, deployed as a drop-in without any modification to the MATLAB optimization workflow, is fully competitive with (and in peak performance superior to) established toolbox solvers on a high-dimensional, heavily constrained industrial problem. The quantum rotation gate's probabilistic diversity maintenance proves well-suited to the multi-directional wake landscape, where premature convergence to a directionally biased layout is the chief failure mode of classical methods. Unlike PSO, which progressively contracts around a global-best attractor, BQPhy's population retains sampling breadth throughout the run, enabling the late-stage discovery of the best configuration.
C. BQPhy Julia library: Lotka–Volterra Calibration in Julia
The Julia binding is intended as a drop-in replacement for the optimizer packages a SciML user would already reach for — not a parallel, Julia-specific rewrite of QIEO. A single shared object (libBQPhy_Optimiser.so) is wrapped by CxxWrap [11]; the high-level module BQPhy_Optimiser accepts a native Julia residual and forwards every call into the C++ runtime (Listing 16).
- Problem Formulation: We recover the four rate coefficients of the classical Lotka–Volterra predator–prey system [12], [13]
Best Turbine Layouts (dashed circles show minimum separation = 2D)



Fig. 6. Best turbine layout discovered by each solver. Dashed circles indicate the minimum separation radius (1D shown). BQPhy's irregular pattern exploits the domain more effectively than PSO's grid-like pattern arrangement or GA's clustered configuration.
from a single noisy trajectory. The true parameters are , with initial state on . Observations are generated by a shared fixed-step RK4 integrator ( ) plus i.i.d. Gaussian noise ( ). All solvers minimise the same residual
where the decision vector equalises the decades that separate growth rates from interaction rates. The noise floor of is (perfect recovery of ). A restart is counted as a success when parameter RMSE .
- Native Julia Baselines: The comparison set is the stack a Julia user would type before discovering BQPhy:
Optim.NelderMead [14] is the default derivative-free local solver in Optim.jl and the starting point of most SciML calibration notebooks.
Optim.ParticleSwarm [14] is the population method shipped in the same package (25 particles, matching the QIEO population).
BlackBoxOptim.DE [15]
(adaptive_de_rand_1_bin_radiuslimited) is the de-facto Julia global optimizer for bound-constrained black-box problems.
CMAEvolutionStrategy [16], [17] is the standard CMA-ES implementation on the Julia registry.
BQPhy is invoked only through its Julia API. No method receives gradient information; the RK4 residual is the sole oracle.
-
Experimental Setup: We run an iso-budget study of 10 independent restarts at 2,000 residual evaluations (QIEO: population 25, 80 generations, 24-bit continuous encoding). Search bounds in space correspond to and . Timing includes optimizer overhead after package compilation; because the residual is cheap, wall-clock differences are not the primary metric — reliability of recovery is.
-
Results: Table X and Figs. 7–9 summarise the ten-restart comparison.

Fig. 7. Residual SSE over 10 restarts (log scale). NelderMead and CMA-ES collapse to a high-SSE mode near the bound; BQPhy and the Julia population methods occupy the lower band.

Fig. 8. Parameter RMSE over the same restarts. BlackBoxOptim is the most consistent recovery; BQPhy matches NelderMead's success rate while avoiding its catastrophic failures.
a) Reliability versus Optim. jl.: NelderMead reaches the noise floor ( ) on two lucky restarts, then fails on the other eight, sticking at SSE > 21,000 — the well-known local-basin failure mode of simplex search on a multimodal dynamical residual. BQPhy matches the 20% success rate but halves mean SSE (8,223 vs. 17,506, a
TABLE X ISO-BUDGET LOTKA-VOLTERRA CALIBRATION (2,000 EVALUATIONS, 10 RESTARTS)
| Method | SSE (mean±std) | SSE med. | θ RMSE | Success | Best SSE | Time (s) |
|---|---|---|---|---|---|---|
| BQPhy (QIEO) | 8223 ± 8760 | 3948 | 0.325 ± 0.298 | 20% | 381 | 0.22 |
| Optim.NelderMead [14] | 17506 ± 9225 | 21486 | 0.514 ± 0.292 | 20% | 26.3 | 0.01 |
| Optim.ParticleSwarm [14] | 4367 ± 7242 | 1487 | 0.452 ± 0.365 | 30% | 26.3 | 0.10 |
| BlackBoxOptim.DE [15] | 1790 ± 954 | 2083 | 0.175 ± 0.165 | 50% | 276 | 0.08 |
| CMA-ES [17] | 16443 ± 11918 | 21931 | 0.444 ± 0.322 | 30% | 26.3 | 0.06 |

Fig. 9. Best BQPhy restart: true Lotka–Volterra orbits, noisy observations, and the QIEO-fitted trajectory. Phase and amplitude are recovered from the same native Julia residual passed to the C++ runtime.
reduction) and cuts the median by (3,948 vs. 21,486). For a Julia user whose first attempt is optimize(f, x0, NelderMead()), swapping in the BQPhy package removes the dominant failure mode without changing the residual.
b) Against Julia-native global solvers.: BlackBoxOptim records the best mean SSE, RMSE, and success rate (50%). Optim.ParticleSwarm has the best median SSE (1,487) and shares the noise-floor best-case with Nelder-Mead and CMA-ES. BQPhy's best restart recovers at SSE 381 (Fig. 9) — a usable calibration, relative error on . CMA-ES is brittle on this bound box: seven restarts collapse to a coordinate bound, so its mean is indistinguishable from NelderMead despite three perfect recoveries.
The ranking is therefore the same shape as the Python HPO study (Section V-A): a specialised Julia package (BlackBoxOptim) can win the mean, while BQPhy is the dominant drop-in for the default stack — better expected residual than Optim.NelderMead, competitive with Optim.ParticleSwarm, and invoked with the identical five-step contract used in Python and MATLAB.
c) Binding transparency.: Every method called the same Julia RK4 residual. BQPhy introduced no algorithmic side-effects beyond the QIEO search itself: CxxWrap translates the population matrix and fitness vector only. The packaged library used here is the CPU HAL (Table I); OpenMP/CUDA specialisations were not compiled into that artifact. Wall-clock cost is dominated by residual evaluation equally across solvers (< 0.3 s mean after compilation), so the decision to adopt BQPhy on this problem is about recovery reliability and API uniformity, not kernel speedup.
VI. RESULTS AND DISCUSSIONS
Across all benchmarks, solution quality (fitness at convergence) is identical across backends and language interfaces to within floating-point rounding tolerance ( ), validating the single-source-of-truth guarantee that all interfaces execute the same algorithm.
This consistency is preserved across the binding demonstrations: the Python PyTorch hyperparameter optimization (Section V-A), the MATLAB wind farm layout optimization (Section V-B), and the Julia Lotka–Volterra calibration (Section V-C) invoke the same C++ binary. The pybind11, MEX, and CxxWrap layers introduce no algorithmic side-effects — every callable, struct, dictionary, and array is translated deterministically between the host language and the C++ runtime. Consequently, practitioners in data-science, scientific-computing, and industrial-engineering domains can adopt the framework with the confidence that results obtained through the high-level API are identical to those produced by the underlying HPC-optimized solver, enabling seamless transition from prototyping to production deployment.
VII. CONCLUSION
We presented Cross-Backend QIEO, a unified runtime system for quantum-inspired evolutionary optimization that achieves both algorithmic performance and hardware portability. The framework's single-source-of-truth architecture — one C++ implementation compiled per hardware target and shared across Python, MATLAB, Julia, and C++ interfaces — eliminates the maintenance fragmentation that affects existing multi-language HPC tools. The Hardware Abstraction Layer maps QIEO primitives to OpenMP, CUDA, and HIP execution models without modifying core algorithm logic, delivering a geometric mean speedup on NVIDIA A100 hardware and on AMD MI300X. Measured Python and MATLAB interface overhead remains below ; the Julia path uses the same shared library through CxxWrap.
On a 16-turbine wind farm layout benchmark with a 12-direction wind rose and Jensen wake model, BQPhy achieves MWh/yr, statistically indistinguishable from particle swarm optimization (, ) while outperforming genetic algorithms by and reducing solution variance by six-fold. The MATLAB MEX binding introduces no measurable overhead, operating as a drop-in replacement for ga() and particleswarm() within the Global Optimization Toolbox.
On Lotka–Volterra calibration through the Julia package, BQPhy is a substitute for the default Optim.jl workflow: at a 2,000-evaluation iso-budget it halves mean residual SSE versus NelderMead (8,223 vs. 17,506) and remains in the same quality band as Optim.ParticleSwarm, while BlackBoxOptim retains the best mean among native Julia globals.
These results, together with the Python-binding findings of Section V-A (neural network hyperparameter optimization), the MATLAB-binding findings of Section V-B (wind farm layout optimization), and the Julia-binding findings of Section V-C (Lotka–Volterra calibration against Optim.jl, BlackBoxOptim.jl, and CMA-ES), jointly validate the binding abstraction: the C++ core exposes a single, language-agnostic interface that serves data-science (PyTorch training loops), scientific computing (Julia SciML residuals), and industrial-engineering (MATLAB control/optimization tool-boxes) communities without any per-domain adaptation. On the Julia path, BQPhy is a package-level substitute for the default Optim.NelderMead workflow, not a second implementation of QIEO.
Future work will extend the HAL to support Intel oneAPI/SYCL targets, incorporate tensor-network state representations for higher-dimensional problems [24], and explore auto-tuning of rotation step sizes using Bayesian optimization.
APPENDIX A
RASTRIGIN BINDINGS IN C++, PYTHON, MATLAB, AND JULIA
The listings below minimise the same Rastrigin objective
with and box bounds (MATLAB demo uses ). The global minimiser is , . Each driver registers a native callable and invokes the identical C++ runtime; only the host syntax differs. The Python and MATLAB fragments follow continuous_rastrigin.py and demo_Mat_BQPhy.m.
APPENDIX B
APPLICATION DRIVERS: HPO (PYTHON), WIND FARM (MATLAB), AND LOTKA–VOLTERRA (JULIA)
Listing 14 is the Python pybind11 driver for MNIST hyperparameter optimisation (Section V-A). Listing 15 is the MATLAB MEX driver demo_Mat_windfarm.m used for the Jensen wind-farm case (Section V-B). Listing 16 is the Julia CxxWrap driver lotka_volterra.jl used for Lotka-Volterra calibration (Section V-C).
REFERENCES
[1] K.-H. Han and J.-H. Kim, “Quantum-inspired evolutionary algorithm for a class of combinatorial optimization,” IEEE Trans. Evol. Comput., vol. 6, no. 6, pp. 580–593, 2002.
[2] J. Preskill, “Quantum computing in the NISQ era and beyond,” Quantum, vol. 2, p. 79, 2018.
[3] J. Nickolls, I. Buck, M. Garland, and K. Skadron, “Scalable parallel programming with CUDA,” Queue, vol. 6, no. 2, pp. 40–53, 2008.
[4] H. C. Edwards, C. R. Trott, and D. Sunderland, “Kokkos: Enabling manycore performance portability through polymorphic memory access patterns,” J. Parallel Distrib. Comput., vol. 74, no. 12, pp. 3202–3216, 2014.
[5] R. D. Hornung and J. A. Keasler, “The RAJA portability layer: Overview and status,” Tech. Rep. LLNL-TR-661403, Lawrence Livermore National Laboratory, 2014.
[6] J. Reinders, B. Ashbaugh, J. Brodman, M. Kinsner, J. Pennycook, and X. Tian, Data Parallel C++: Mastering DPC++ for Programming of Heterogeneous Systems using C++ and SYCL. Apress, 2021.
[7] OpenMP Architecture Review Board, “OpenMP application programming interface, version 5.0,” 2018. [Online]. Available: https://www.openmp.org/spec-html/5.0/openmp.html
[8] Advanced Micro Devices, Inc., “ROCm open software platform and HIP programming guide,” 2023. [Online]. Available: https://rocmdocs.amd.com
[9] W. Jakob, J. Rhinelander, and D. Moldovan, “pybind11 – seamless operability between C++11 and Python,” 2017. [Online]. Available: https://github.com/pybind/pybind11
[10] The MathWorks, Inc., “MATLAB external interfaces: MEX file functions,” 2024. [Online]. Available: https://www.mathworks.com/help/matlab/matlab_external/
[11] B. Janssens, “CxxWrap.jl: Calling C++ from Julia,” 2024. [Online]. Available: https://github.com/JuliaInterop/CxxWrap.jl
[12] A. J. Lotka, Elements of Physical Biology. Williams & Wilkins, 1925.
[13] V. Volterra, “Fluctuations in the abundance of a species considered mathematically,” Nature, vol. 118, pp. 558–560, 1926.
[14] P. K. Mogensen and A. N. Riseth, “Optim: A mathematical optimization package for Julia,” J. Open Source Softw., vol. 3, no. 24, p. 615, 2018.
[15] R. Feldt, “BlackBoxOptim.jl,” 2018. [Online]. Available: https://github.com/robertfeldt/BlackBoxOptim.jl
[16] N. Hansen and A. Ostermeier, “Completely derandomized self-adaptation in evolution strategies,” Evol. Comput., vol. 9, no. 2, pp. 159–195, 2001.
[17] O. Breitwieser, “CMAEvolutionStrategy.jl,” 2021. [Online]. Available: https://github.com/jbrea/CMAEvolutionStrategy.jl
[18] N. Bell and J. Hoberock, “Thrust: A productivity-oriented library for CUDA,” in GPU Computing Gems Jade Edition. Morgan Kaufmann, 2011, pp. 359–371.
[19] Y. Feng, L. Wang, and Q. Li, “Quantum rotation gate in quantum-inspired evolutionary algorithm: A review, analysis and comparison study,” Swarm Evol. Comput., vol. 42, pp. 43–57, 2018.
[20] A. Layeb, “A novel quantum inspired cuckoo search algorithm for bin packing problem,” Int. J. Inf. Technol. Comput. Sci., vol. 3, no. 5, 2011.
[21] L. Wang, F. Tang, and H. Wu, “Hybrid quantum-inspired evolutionary algorithm with simplex method for numerical optimization,” Soft Comput., vol. 9, pp. 1–10, 2014.
[22] J. Zheng and M. Okido, “Multi-objective quantum-inspired evolutionary algorithm,” IEICE Trans. Inf. Syst., vol. E95-D, no. 4, pp. 1024–1035, 2012.
[23] T. Deakin, J. Price, M. Martineau, and S. McIntosh-Smith, “Performance portability across diverse computer architectures,” in IEEE/ACM Int. Workshop Performance Portability Productivity, 2019.
[24] J. Biamonte, M. Faccin, and M. De Domenico, “Complex networks from classical to quantum,” Commun. Phys., vol. 2, p. 53, 2019.
[25] A. Mittal and F. S. D. Bosco, “Benchmarking of GPU-optimized quantum-inspired evolutionary algorithms,” 2024, arXiv:2412.08992.
[26] A. S. Tanenbaum and M. Van Steen, Distributed Systems: Principles and Paradigms, 2nd ed. Prentice Hall, 2006.
[27] Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner, “Gradient-based learning applied to document recognition,” Proc. IEEE, vol. 86, no. 11, pp. 2278–2324, 1998.
[28] R. Liaw, E. Liang, R. Nishihara, P. Moritz, J. E. Gonzalez, and I. Stoica, "Tune: A research platform for distributed model selection and training," in Proc. ICML Workshop on Automated Machine Learning, 2018.
#include "BQPhy_Optimiser.hpp"
std::vector<double> rastrigin(const Matrix& X) { const double A = 10.0; const int n = X.cols(); std::vector<double> f(X.rows()); for (int i = 0; i < X.rows(); ++i) { double s = A * n; for (int k = 0; k < n; ++k) { const double xk = X(i, k); s += xk * xk - A * std::cos(2.0 * M_PI * xk); } f[i] = s; } return f; }
int main() { BQPhy::Optimiser opt; ParameterClass params; params.numPopulation = 200; params.maxGeneration = 500; params.designVariables = 4; params.typeOfOptimisation = "CONTINUOUS"; params.lowerBounds.assign(4, -5.12); params.upperBounds.assign(4, 5.12); opt.initialize(params); opt.setModel(rastrigin); opt.runOptimization("cpu"); auto [best, fit] = opt.getBestDesign(); }
Fig. 10. C++ header-only Rastrigin driver.
import numpy as np import bqphy.BQPhy_Optimiser as qea
def rastrigin_function(x): A = 10 fitness = np.zeros(x.shape[0], dtype=np.float64) for i in range(x.shape[0]): fitness[i] = (A * x.shape[1] + np.sum(x[i]**2 - A * np.cos(2 * np.pi * x[i])) return fitness
config = { "numPopulation": 200, "maxGeneration": 500, "designVariables": 4, "typeOfOptimisation": "CONTINUOUS", "lowerBounds": [-5.12] * 4, "upperBounds": [5.12] * 4, "outputFilePath": "optimization_results_rastrigin", }
opt = qea.BQPhy_OPTIMISER() opt.initialize(config) opt.model(rastrigin_function) opt.runOptimization() # "cpu" / "openmp" / "gpu" best_sol, best_fit = opt.getBestDesign()
Fig. 11. Python (pybind11) Rastrigin driver, after continuous_rastrigin.py.
[29] T. Akiba, S. Sano, T. Yanase, T. Ohta, and M. Koyama, “Optuna: A next-generation hyperparameter optimization framework,” in Proc. ACM SIGKDD Int. Conf. Knowledge Discovery and Data Mining, 2019, pp. 2623–2631.
[30] F. Pedregosa, G. Varoquaux, A. Gramfort, V. Michel, B. Thirion, O. Grisel, M. Blondel et al., “Scikit-learn: Machine learning in Python,” J. Mach. Learn. Res., vol. 12, pp. 2825–2830, 2011.
[31] J. Bergstra and Y. Bengio, “Random search for hyper-parameter optimization,” J. Mach. Learn. Res., vol. 13, pp. 281–305, 2012.
[32] L. Li, K. Jamieson, G. DeSalvo, A. Rostamizadeh, and A. Talwalkar, "Hyperband: A novel bandit-based approach to hyperparameter optimization," J. Mach. Learn. Res., vol. 18, pp. 1–52, 2018.
[33] A. Paszke, S. Gross, F. Massa, A. Lerer et al., “PyTorch: An imperative style, high-performance deep learning library,” in Adv. Neural Inf. Process. Syst. (NeurIPS), vol. 32, 2019.
[34] C. R. Harris, K. J. Millman, S. J. van der Walt et al., “Array programming with NumPy,” Nature, vol. 585, pp. 357–362, 2020.
[35] N. O. Jensen, “A note on wind generator interaction,” Risø National Laboratory, Roskilde, Tech. Rep. Risø-M-2411, 1983.
[36] R. Shakoor, M. Y. Hassan, A. Raheem, and Y.-K. Wu, “Wake effect modeling: A review of wind farm layout optimization using Jensen’s model,” Renewable Sustain. Energy Rev., vol. 58, pp. 1048–1059, 2016.
[37] J. Feng and W. Z. Shen, “Solving the wind farm layout optimization problem using random search algorithm,” Renewable Energy, vol. 78, config = struct( ... "numPopulation", 100, ... "maxGeneration", 200, ... "deltaTheta", 0.05, ... "designVariables", 4, ... "typeOfOptimisation", 'CONTINUOUS'); config.lowerBounds = -5 * ones(1, config.designVariables); config.upperBounds = 5 * ones(1, config.designVariables); config.outputFilePath = 'optimization_results'; config generationLogging = 'minimumLogging';
myFun = @(x) (10 * size(x,2)) ... + sum(x.^2 - 10 * cos(2 * pi * x), 2);
[result, Fitness] = BQPhy_Mex(config, myFun, 'cpu');
Fig. 12. MATLAB (MEX) Rastrigin driver, after demo_Mat_BQPhy.m.
using BQPhy_Optimiser
function rastrigin(x::AbstractMatrix{<:Real}; A=10.0) n = size(x, 2) return vec(A * n .+ sum(x.^2 .- A .* cos.(2pi .* x), dims=2)) end
config = Dict( :numPopulation => 200, :maxGeneration => 500, :designVariables => 4, :typeOfOptimisation => "CONTINUOUS", :lowerBounds => fill(-5.12, 4), :upperBounds => fill(5.12, 4), :outputFilePath => "./rastrigin_results")
opt = Optimizer(config) set_fitness_function!(opt, rastrigin) optimize!(opt; device="cpu") best_sol, best_fit = get_best_design(opt)
Fig. 13. Julia (CxxWrap) Rastrigin driver.
pp. 182–192, 2015.
[38] The MathWorks Inc., Global Optimization Toolbox User's Guide. Natick, MA, USA, 2024.
[39] D. M. Beazley, “Automated scientific software scripting with SWIG,” Future Gener. Comput. Syst., vol. 19, no. 5, pp. 599–609, 2003.
[40] D. Abrahams and R. W. Grosse-Kunstleve, “Building hybrid systems with Boost.Python,” C/C++ Users J., vol. 21, no. 7, 2003.
[41] S. Behnel, R. Bradshaw, C. Citro, L. Dalcin, D. S. Seljebotn, and K. Smith, "Cython: The best of both worlds," Comput. Sci. Eng., vol. 13, no. 2, pp. 31–39, 2011.
[42] J. Bezanson, A. Edelman, S. Karpinski, and V. B. Shah, “Julia: A fresh approach to numerical computing,” SIAM Rev., vol. 59, no. 1, pp. 65–98, 2017.
[43] G. Eswara Sai Kumar, A. Mittal, A. Chopra, R. Lineswala, and A. Singh, "Quantum-inspired evolutionary optimization on GPU architectures," BosonQ Psi Tech. Rep., 2024.
import numpy as np import bqphy.BQPhy_Optimiser as qea
def get_activation(code): names = ["relu", "tanh", "sigmoid", "leaky_relu"] return names[int(round(code))]
def train_eval(lr, hidden, layers, act, drop): # One-epoch DynamicNet on MNIST; returns test accuracy in [0, 1]. ...
def bqphy_fitness(pop): fitness = np.zeros(pop.shape[0]) for i in range(pop.shape[0]): lr = pop[i, 0] hidden = int(pop[i, 1]) layers = int(pop[i, 2]) act = get_activation(pop[i, 3]) drop = float(pop[i, 4]) acc = train_eval(lr, hidden, layers, act, drop) fitness[i] = -acc return fitness
config = { "numPopulation": 12, "maxGeneration": 20, "designVariables": 5, "typeOfOptimisation": "CONTINUOUS", "lowerBounds": [1e-5, 32, 1, 0, 0.0], "upperBounds": [1e-1, 256, 4, 3, 0.5], }
opt = qea.BQPhy_OPTIMISER() opt.initialize(config) opt.model(bqphy_fitness) opt.runOptimization() best_sol, best_fit = opt.getBestDesign()
Fig. 14. Python MNIST hyperparameter-optimisation driver (pybind11). train_eval is the one-epoch PyTorch evaluation used in Section V-A.
clc; clear; close all; % Wind farm layout optimisation (WFLO) via BQPhy MEX. % 16 turbines, Jensen wakes, 12-sector rose, 2D spacing.
N = 16; D = 126; Pr = 5e6; Ct = 0.88; ke = 0.075; sepMin = 2 * D; wPen = 10; domain = 1000; cutIn = 3; rated = 12; cutOut = 25; vMean = 8.5; hoursYear = 8760;
az = [0 30 60 90 120 150 180 210 240 270 300 330]; paz = [0.03 0.04 0.05 0.06 0.07 0.10 0.10 0.12 0.14 0.18 0.08 0.03]; nSpd = 20; vEdges = linspace(0, cutOut, nSpd + 1); vMid = 0.5 * (vEdges(1:end-1) + vEdges(2:end)); sigma = vMean / sqrt(pi/2); pdfv = (vMid ./ sigma^2) .* exp(-(vMid.^2) / (2 * sigma^2)); psp = pdfv .* diff(vEdges); psp = psp / sum(psp);
config = struct(... "numPopulation", 20, ... "maxGeneration", 40, ... "deltaTheta", 0.05, ... "designVariables", 2 * N, ... "typeOfOptimisation", 'CONTINUOUS'); config.lowerBounds = zeros(1, 2 * N); config.upperBounds = domain * ones(1, 2 * N); config.outputFilePath = 'wflo_results'; configgenerationLogging = 'minimumLogging';
% Paper iso-budget: numPopulation=100, maxGeneration=500 myFun = @(X) wfloFitness(X, N, D, Pr, Ct, ke, sepMin, wPen, ... az, paz, vMid, psp, cutIn, rated, cutOut, hoursYear);
[result, Fitness] = BQPhy_Mex(config, myFun, 'cpu'); xy = reshape(result, 2, []);
function f = wfloFitness(X, N, D, Pr, Ct, ke, sepMin, wPen, ... az, paz, vMid, psp, cutIn, rated, cutOut, hoursYear) nPop = size(X, 1); f = zeros(nPop, 1); for p = 1:nPop xy = reshape(X(p, :), 2, N); aep = farmAEP(xy, N, D, Pr, Ct, ke, az, paz, vMid, psp, ... cutIn, rated, cutOut, hoursYear); pen = 0; for i = 1:N-1 d = hypot(xy(i+1:end,1) - xy(i,1), xy(i+1:end,2) - xy(i,2)); viol = max(0, sepMin - d); pen = pen + sum(viol.^2); end f(p) = -aep + wPen * pen; end end
function aep = farmAEP(xy, N, D, Pr, Ct, ke, az, paz, vMid, psp, ... cutIn, rated, cutOut, hoursYear) aep = 0; kDef = 1 - sqrt(1 - Ct); for id = 1:numel(az) th = deg2rad(az(id)); fx = -sin(th); fy = -cos(th); for j = 1:N def2 = 0; for i = 1:N if i == j, continue; end rx = xy(j,1) - xy(i,1); ry = xy(j,2) - xy(i,2); xs = rx * fx + ry * fy; if xs <= 1e-6, continue; end lat = abs(fx * ry - fy * rx); if lat > (D/2 + ke * xs), continue; end def2 = def2 + (kDef / (1 + 2 * ke * xs / D)^2)^2; end deficit = sqrt(def2); for is = 1:numel(vMid) using BQPhy_Optimiser using LinearAlgebra, Printf, Random, Statistics
const TRUE_P = [1.0, 0.1, 0.075, 1.5] const U0 = [10.0, 5.0] const T_END = 20.0 const DT = 0.20 const NOISE_SIGMA = 0.35 const DATA_SEED = 20260905 const LOG_LOWER = log10([0.05, 0.01, 0.01, 0.20]) const LOG_UPPER = log10([2.50, 0.50, 0.40, 3.00])
function lotka_rhs(u, p) a, b, d, g = p[1], p[2], p[3], p[4] x, y = u return (a * x - b * x * y, d * x * y - g * y) end
function rk4_traj(p; u0=U0, t_end=T_END, dt=DT) n = Int(round(t_end / dt)) + 1 xs = Vector{Float64}(undef, n) ys = Vector{Float64}(undef, n) u = (Float64(u0[1]), Float64(u0[2])) xs[1] = u[1]; ys[1] = u[2] for i in 2:n k1 = lotka_rhs(u, p) k2 = lotka_rhs(u .+ 0.5 .* dt .* k1, p) k3 = lotka_rhs(u .+ 0.5 .* dt .* k2, p) k4 = lotka_rhs(u .+ dt .* k3, p) u = u .+ (dt / 6.0) .* (k1 .+ 2.0 .* k2 .+ 2.0 .* k3 .+ k4) xs[i] = u[1]; ys[i] = u[2] end return xs, ys end
function make Observations() rng = MersenneTwister(DATA_SEED) xs, ys = rk4_traj(TRUE_P) return xs .+ NOISE_SIGMA .* randn(rng, length(xs)), ys .+ NOISE_SIGMA .* randn(rng, length(ys)) end
const XS_OBS, YS_OBS = make Observations()
function sse_theta(theta) any(!isfinite, theta) && return 1.0e6 any(<=0), theta) && return 1.0e6 xs, ys = rk4_traj(theta) s = sum(abs2, xs .- XS_OBS) + sum(abs2, ys .- YS_OBS) return isfinite(s) ? s : 1.0e6 end
function lv_fitness(pop::AbstractMatrix{<:Real}) n = size(pop, 1) fit = Vector{Float64}(undef, n) for i in 1:n z = clamp.(collect(pop[i, :]), LOG_LOWER, LOG_UPPER) fit[i] = sse_theta(exp10.(z)) end return fit end
function main() config = Dict( :numPopulation => 25, :maxGeneration => 80, :deltaTheta => 0.05, :designVariables => 4, :stringLength => 24, :typeOfOptimisation => "CONTINUOUS", :lowerBounds => collect(LOG_LOWER), :upperBounds => collect(LOG_UPPER), :outputFilePath => "./lotka_results", :generationLogging => "minimumLogging") opt = Optimizer(config) set_fitness_function!(opt, lv_fitness) optimize!(opt; device="cpu") best, fit = get_best_design(opt) z = clamp.(collect(best), LOG_LOWER, LOG_UPPER) theta = exp10.(z) rmse = sqrt(mean(abs2, theta .- TRUE_P)) @printf("Recovered theta = [%.4f, %.4f, %.4f, %.4f]\n", theta...) @printf("SSE = %.4f RMSE = %.4f\n", sse_theta(theta), rmse) write_results(opt) end