Software Development

Hybrid Quantum-Classical Computing: Examples for Optimization (Updated)

Editor’s note:
Earlier drafts of this article used imports like

import org.redfx.strange.algorithm.QAOA;
import org.redfx.strange.algorithm.QAOAProblem;
import org.redfx.strange.algorithm.QAOAResult;

These classes do not exist in the current Strange library. They were placeholders for a high-level QAOA API that was never merged.

This version has been updated with working Strange examples that show how to build QAOA circuits manually using gates and a classical optimizer.

What Changed Since the Previous Version

Old VersionNew VersionReason for Change
Imports used high-level classes:
import org.redfx.strange.algorithm.QAOA;
import org.redfx.strange.algorithm.QAOAProblem;
import org.redfx.strange.algorithm.QAOAResult;
No longer present in Strange.
Replaced with manual circuit construction using gates (Hadamard, RX, RZ, Cnot).
These classes were never released in Strange’s official API. They were placeholders or experimental.
Code showed a direct QAOAProblem / QAOAResult workflow.Example now builds a QAOA circuit by hand and connects it with a classical optimizer (Nelder–Mead).Keeps examples executable with the latest Strange release.
Rotation gate import was used.Now using RX and RZ gates from org.redfx.strange.gate.Rotation is not part of the latest Strange version; RX/RZ are the correct gates for mixers/cost unitaries.
Assumed Strange had a built-in QAOA API.Explicitly states that Strange is gate-level only right now.Prevents confusion for readers trying to reproduce the code.

1. Introduction

Hybrid quantum-classical computing combines the strengths of classical and quantum systems to solve complex optimization problems. While quantum computers excel at exploring large solution spaces, classical computers handle preprocessing, postprocessing, and control logic.

In this article, you’ll learn how to build hybrid optimization workflows in Java with the Strange library, focusing on implementing the Quantum Approximate Optimization Algorithm (QAOA).

2. Key Concepts

2.1 What is Hybrid Quantum-Classical Computing?

Hybrid quantum-classical computing
https://www.epiqc.cs.uchicago.edu/hybrid-quantum-classical-computing
  • Classical Computing: Handles data processing, control logic, and refinement.
  • Quantum Computing: Solves specific tasks like optimization using quantum algorithms.
  • Synergy: Combines both to tackle problems more efficiently.

2.2 Applications in Optimization

  • Traveling Salesman Problem (TSP)
  • Portfolio Optimization
  • Supply Chain Optimization
  • Machine Learning Hyperparameter Tuning

3. Tools for Hybrid Quantum-Classical Computing in Java

1. Strange

  • Java library for simulating quantum circuits.
  • Provides qubits, gates, and a local execution environment.
  • Does not currently include a built-in QAOA API — you construct circuits manually.

2. JQuantum

  • Another Java-based simulator.
  • Less active, but educational for learning the basics.

4. Implementing Hybrid Optimization with Strange

QAOA requires:

  • A classical optimizer to tune variational parameters (γ, β).
  • A cost Hamiltonian encoding the optimization problem.
  • A mixer Hamiltonian (typically RX rotations).

Step 1: Add Dependencies

<dependency>
    <groupId>org.redfx</groupId>
    <artifactId>strange</artifactId>
    <version>0.1.3</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-math3</artifactId>
    <version>3.6.1</version>
</dependency>
  • strange → quantum circuit simulator.
  • commons-math3 → classical optimization routines.

Step 2: QAOA Example in Java

Below is a simplified Max-Cut example using QAOA with depth p = 1.

import org.redfx.strange.Program;
import org.redfx.strange.Step;
import org.redfx.strange.gate.Hadamard;
import org.redfx.strange.gate.Cnot;
import org.redfx.strange.gate.RX;
import org.redfx.strange.gate.RZ;
import org.redfx.strange.local.SimpleQuantumExecutionEnvironment;
import org.redfx.strange.QuantumExecutionEnvironment;
import org.redfx.strange.Result;

import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.NelderMeadSimplex;
import org.apache.commons.math3.optim.nonlinear.scalar.noderiv.SimplexOptimizer;
import org.apache.commons.math3.optim.MaxEval;
import org.apache.commons.math3.optim.InitialGuess;
import org.apache.commons.math3.optim.PointValuePair;
import org.apache.commons.math3.optim.nonlinear.scalar.GoalType;

public class HybridQAOAExample {

    // Example Hamiltonian: Max-Cut on a 2-node graph with one edge
    private static double[][] hamiltonian = {
        {0, 1},
        {1, 0}
    };

    public static void main(String[] args) {
        int p = 1; // QAOA depth
        double[] initialParams = {0.5, 0.5}; // gamma, beta

        SimplexOptimizer optimizer = new SimplexOptimizer(1e-6, 1e-6);
        NelderMeadSimplex simplex = new NelderMeadSimplex(initialParams.length);

        PointValuePair result = optimizer.optimize(
            new MaxEval(200),
            org.apache.commons.math3.optim.nonlinear.scalar.ObjectiveFunction.wrap(params -> {
                return -evaluateQAOA(params, p); // optimizer minimizes
            }),
            GoalType.MINIMIZE,
            new InitialGuess(initialParams),
            simplex
        );

        double[] best = result.getPoint();
        System.out.println("Best params: ?=" + best[0] + ", β=" + best[1]);
        System.out.println("Optimal value: " + (-result.getValue()));
    }

    private static double evaluateQAOA(double[] params, int p) {
        double gamma = params[0];
        double beta = params[1];

        Program program = new Program(2);

        // Initial superposition
        Step init = new Step();
        init.addGate(new Hadamard(0));
        init.addGate(new Hadamard(1));
        program.addStep(init);

        // Cost unitary (ZZ interaction)
        Step cost = new Step();
        cost.addGate(new Cnot(0, 1));
        cost.addGate(new RZ(gamma, 1));
        cost.addGate(new Cnot(0, 1));
        program.addStep(cost);

        // Mixer unitary
        Step mix = new Step();
        mix.addGate(new RX(2 * beta, 0));
        mix.addGate(new RX(2 * beta, 1));
        program.addStep(mix);

        QuantumExecutionEnvironment env = new SimpleQuantumExecutionEnvironment();
        Result r = env.runProgram(program);

        // Compute expected cost from measurement outcomes
        double expectedValue = 0.0;
        for (int i = 0; i < r.getProbability().length; i++) {
            double prob = r.getProbability(i);
            int[] bits = decodeBits(i, 2); // helper to decode basis state
            expectedValue += costFunction(bits) * prob;
        }
        return expectedValue;
    }

    // Max-Cut cost function
    private static double costFunction(int[] bits) {
        return (bits[0] ^ bits[1]) == 1 ? 1.0 : 0.0;
    }

    // Convert integer index to bitstring
    private static int[] decodeBits(int index, int n) {
        int[] bits = new int[n];
        for (int i = 0; i < n; i++) {
            bits[i] = (index >> i) & 1;
        }
        return bits;
    }
}

5. Classical Preprocessing & Postprocessing

In a hybrid workflow:

  • Preprocessing: Translate your problem into a Hamiltonian (e.g., adjacency matrix for Max-Cut).
  • Quantum Computation: Build parameterized circuits and simulate them.
  • Postprocessing: Extract solutions, refine them, and possibly combine with local search.

Example preprocessing helper:

private static double[][] generateHamiltonian() {
    return new double[][] {
        {0, 1, 1, 0},
        {1, 0, 0, 1},
        {1, 0, 0, 1},
        {0, 1, 1, 0}
    };
}

6. Conclusion

Hybrid quantum-classical computing is a powerful way to tackle optimization problems. While Java libraries like Strange don’t yet provide high-level algorithm APIs such as QAOAProblem, you can still implement QAOA circuits manually and pair them with classical optimizers.

This not only gives you flexibility but also helps you understand the mechanics of hybrid algorithms. As the Java quantum ecosystem grows, more complete abstractions may emerge.

For now, building QAOA by hand in Strange provides a hands-on path to experiment with hybrid computing in logistics, finance, and machine learning.

Happy coding!

Eleftheria Drosopoulou

Eleftheria is an Experienced Business Analyst with a robust background in the computer software industry. Proficient in Computer Software Training, Digital Marketing, HTML Scripting, and Microsoft Office, they bring a wealth of technical skills to the table. Additionally, she has a love for writing articles on various tech subjects, showcasing a talent for translating complex concepts into accessible content.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Eckehart Stamer
Eckehart Stamer
8 months ago

I tried to reproduce the examples, but couldn’t get the following imports:
import org.redfx.strange.algorithm.QAOA;
import org.redfx.strange.algorithm.QAOAProblem;
import org.redfx.strange.algorithm.QAOAResult;
import org.redfx.strange.gate.Rotation;
Have they meanwhile been removed from the github? If “yes”, do you know if there is a replacement?

Back to top button