F# library for Azure Quantum with quantum-first optimization (Graph Coloring, TSP, MaxCut, Knapsack, Network Flow, Portfolio), Azure Quantum backend integration (IonQ, Rigetti, Quantinuum, Atom Computing), extensible circuit validation, local quantum simulation, QAOA with automatic parameter optimization (Nelder-Mead), OpenQASM 2.0 support, error mitigation techniques (ZNE, PEC, REM), Quantum Random Number Generation (QRNG), and educational quantum algorithms (Grover, QFT, Amplitude Amplification) with cloud backend execution. Multi-provider architecture supports IonQ, Rigetti, Quantinuum, Atom Computing, IBM, Amazon Braket, and Google Cirq.
$ dotnet add package FSharp.Azure.QuantumQuantum-First F# Library - Solve combinatorial optimization problems using quantum algorithms (QAOA - Quantum Approximate Optimization Algorithm) with automatic cloud/local backend selection.
Architecture: Quantum-First Hybrid Library - Quantum algorithms as primary solvers, with intelligent classical fallback for small problems
Current Version: 1.2.3 (Enhanced Quantum Algorithms and Builder API Improvements)
Current Features:
dotnet add package FSharp.Azure.Quantumopen FSharp.Azure.Quantum
// Graph Coloring: Register Allocation
let problem = graphColoring {
node "R1" ["R2"; "R3"]
node "R2" ["R1"; "R4"]
node "R3" ["R1"; "R4"]
node "R4" ["R2"; "R3"]
colors ["EAX"; "EBX"; "ECX"; "EDX"]
}
// Solve using quantum optimization (QAOA)
match GraphColoring.solve problem 4 None with
| Ok solution ->
printfn "Colors used: %d" solution.ColorsUsed
solution.Assignments
|> Map.iter (fun node color -> printfn "%s → %s" node color)
| Error msg ->
printfn "Error: %s" msgusing FSharp.Azure.Quantum;
using static FSharp.Azure.Quantum.CSharpBuilders;
// MaxCut: Circuit Partitioning
var vertices = new[] { "A", "B", "C", "D" };
var edges = new[] {
(source: "A", target: "B", weight: 1.0),
(source: "B", target: "C", weight: 2.0),
(source: "C", target: "D", weight: 1.0),
(source: "D", target: "A", weight: 1.0)
};
var problem = MaxCutProblem(vertices, edges);
var result = MaxCut.solve(problem, null);
if (result.IsOk) {
var solution = result.ResultValue;
Console.WriteLine($"Cut Value: {solution.CutValue}");
Console.WriteLine($"Partition S: {string.Join(", ", solution.PartitionS)}");
Console.WriteLine($"Partition T: {string.Join(", ", solution.PartitionT)}");
}What happens:
GraphColoring.solve calls QuantumGraphColoringSolver internally7 Production-Ready Optimization Builders using QAOA:
Use Case: Register allocation, frequency assignment, exam scheduling
open FSharp.Azure.Quantum
let problem = graphColoring {
node "Task1" ["Task2"; "Task3"]
node "Task2" ["Task1"; "Task4"]
node "Task3" ["Task1"; "Task4"]
node "Task4" ["Task2"; "Task3"]
colors ["Slot A"; "Slot B"; "Slot C"]
objective MinimizeColors
}
match GraphColoring.solve problem 3 None with
| Ok solution ->
printfn "Valid coloring: %b" solution.IsValid
printfn "Colors used: %d/%d" solution.ColorsUsed 3
printfn "Conflicts: %d" solution.ConflictCount
| Error msg -> printfn "Error: %s" msgUse Case: Circuit design, community detection, load balancing
let vertices = ["A"; "B"; "C"; "D"]
let edges = [
("A", "B", 1.0)
("B", "C", 2.0)
("C", "D", 1.0)
("D", "A", 1.0)
]
let problem = MaxCut.createProblem vertices edges
match MaxCut.solve problem None with
| Ok solution ->
printfn "Partition S: %A" solution.PartitionS
printfn "Partition T: %A" solution.PartitionT
printfn "Cut value: %.2f" solution.CutValue
| Error msg -> printfn "Error: %s" msgUse Case: Resource allocation, portfolio selection, cargo loading
let items = [
("laptop", 3.0, 1000.0) // (id, weight, value)
("phone", 0.5, 500.0)
("tablet", 1.5, 700.0)
("monitor", 2.0, 600.0)
]
let problem = Knapsack.createProblem items 5.0 // capacity = 5.0
match Knapsack.solve problem None with
| Ok solution ->
printfn "Total value: $%.2f" solution.TotalValue
printfn "Total weight: %.2f/%.2f" solution.TotalWeight problem.Capacity
printfn "Items: %A" (solution.SelectedItems |> List.map (fun i -> i.Id))
| Error msg -> printfn "Error: %s" msgUse Case: Route optimization, delivery planning, logistics
let cities = [
("Seattle", 0.0, 0.0)
("Portland", 1.0, 0.5)
("San Francisco", 2.0, 1.5)
("Los Angeles", 3.0, 3.0)
]
let problem = TSP.createProblem cities
match TSP.solve problem None with
| Ok tour ->
printfn "Optimal route: %s" (String.concat " → " tour.Cities)
printfn "Total distance: %.2f" tour.TotalDistance
| Error msg -> printfn "Error: %s" msgUse Case: Investment allocation, asset selection, risk management
let assets = [
("AAPL", 0.12, 0.15, 150.0) // (symbol, return, risk, price)
("GOOGL", 0.10, 0.12, 2800.0)
("MSFT", 0.11, 0.14, 350.0)
]
let problem = Portfolio.createProblem assets 10000.0 // budget
match Portfolio.solve problem None with
| Ok allocation ->
printfn "Portfolio value: $%.2f" allocation.TotalValue
printfn "Expected return: %.2f%%" (allocation.ExpectedReturn * 100.0)
printfn "Risk: %.2f" allocation.Risk
allocation.Allocations
|> List.iter (fun (symbol, shares, value) ->
printfn " %s: %.2f shares ($%.2f)" symbol shares value)
| Error msg -> printfn "Error: %s" msgUse Case: Supply chain optimization, logistics, distribution planning
let nodes = [
NetworkFlow.SourceNode("Factory", 100)
NetworkFlow.IntermediateNode("Warehouse", 80)
NetworkFlow.SinkNode("Store1", 40)
NetworkFlow.SinkNode("Store2", 60)
]
let routes = [
NetworkFlow.Route("Factory", "Warehouse", 5.0)
NetworkFlow.Route("Warehouse", "Store1", 3.0)
NetworkFlow.Route("Warehouse", "Store2", 4.0)
]
let problem = { NetworkFlow.Nodes = nodes; Routes = routes }
match NetworkFlow.solve problem None with
| Ok flow ->
printfn "Total cost: $%.2f" flow.TotalCost
printfn "Fill rate: %.1f%%" (flow.FillRate * 100.0)
| Error msg -> printfn "Error: %s" msgUse Case: Manufacturing workflows, project management, resource allocation with dependencies
open FSharp.Azure.Quantum
// Define tasks with dependencies
let taskA = scheduledTask {
taskId "TaskA"
duration (hours 2.0)
priority 10.0
}
let taskB = scheduledTask {
taskId "TaskB"
duration (hours 1.5)
after "TaskA" // Dependency
requires "Worker" 2.0
deadline 180.0
}
let taskC = scheduledTask {
taskId "TaskC"
duration (minutes 30.0)
after "TaskA"
requires "Machine" 1.0
}
// Define resources
let worker = resource {
resourceId "Worker"
capacity 3.0
}
let machine = resource {
resourceId "Machine"
capacity 2.0
}
// Build scheduling problem
let problem = scheduling {
tasks [taskA; taskB; taskC]
resources [worker; machine]
objective MinimizeMakespan
timeHorizon 500.0
}
// Solve with quantum backend for resource constraints
let backend = BackendAbstraction.createLocalBackend()
match solveQuantum backend problem with
| Ok solution ->
printfn "Makespan: %.2f hours" solution.Makespan
solution.Schedule
|> List.iter (fun assignment ->
printfn "%s: starts %.2f, ends %.2f"
assignment.TaskId assignment.StartTime assignment.EndTime)
| Error msg -> printfn "Error: %s" msgFeatures:
API Documentation: TaskScheduling-API.md
Examples:
Smart solver that automatically chooses between classical and quantum execution based on problem analysis.
The HybridSolver provides a unified API that:
Decision Framework:
The HybridSolver supports all 5 main optimization problems:
open FSharp.Azure.Quantum.Classical.HybridSolver
// TSP with automatic routing
let distances = array2D [[0.0; 10.0; 15.0];
[10.0; 0.0; 20.0];
[15.0; 20.0; 0.0]]
match solveTsp distances None None None with
| Ok solution ->
printfn "Method used: %A" solution.Method // Classical or Quantum
printfn "Reasoning: %s" solution.Reasoning // Why this method?
printfn "Time: %.2f ms" solution.ElapsedMs
printfn "Route: %A" solution.Result.Route
printfn "Distance: %.2f" solution.Result.TotalDistance
| Error msg -> printfn "Error: %s" msg
// MaxCut with quantum backend config
let vertices = ["A"; "B"; "C"; "D"]
let edges = [("A", "B", 1.0); ("B", "C", 2.0); ("C", "D", 1.0)]
let problem = MaxCut.createProblem vertices edges
let quantumConfig = {
Backend = IonQ "ionq.simulator"
WorkspaceId = "your-workspace-id"
Location = "eastus"
ResourceGroup = "quantum-rg"
SubscriptionId = "sub-id"
MaxCostUSD = Some 50.0 // Cost guard
EnableComparison = true // Compare with classical
}
match solveMaxCut problem (Some quantumConfig) None None with
| Ok solution ->
printfn "Method: %A" solution.Method
printfn "Cut Value: %.2f" solution.Result.CutValue
match solution.Recommendation with
| Some recommendation -> printfn "Advisor: %s" recommendation.Reasoning
| None -> ()
| Error msg -> printfn "Error: %s" msg
// Knapsack
match solveKnapsack knapsackProblem None None None with
| Ok solution ->
printfn "Total Value: %.2f" solution.Result.TotalValue
printfn "Items: %A" solution.Result.SelectedItems
| Error msg -> printfn "Error: %s" msg
// Graph Coloring
match solveGraphColoring graphProblem 3 None None None with
| Ok solution ->
printfn "Colors Used: %d/3" solution.Result.ColorsUsed
printfn "Valid: %b" solution.Result.IsValid
| Error msg -> printfn "Error: %s" msg
// Portfolio Optimization
match solvePortfolio portfolioProblem None None None with
| Ok solution ->
printfn "Portfolio Value: $%.2f" solution.Result.TotalValue
printfn "Expected Return: %.2f%%" (solution.Result.ExpectedReturn * 100.0)
| Error msg -> printfn "Error: %s" msgMaxCostUSD prevents runaway quantum costsEnableComparison = true runs both methodsUse HybridSolver when:
Use Direct Builders when:
Location: src/FSharp.Azure.Quantum/Solvers/Hybrid/HybridSolver.fs
Status: Production-ready - Recommended for production deployments
graph TB
subgraph "Layer 1: High-Level Builders"
GC["GraphColoring Builder<br/>graphColoring { }"]
MC["MaxCut Builder<br/>MaxCut.createProblem"]
KS["Knapsack Builder<br/>Knapsack.createProblem"]
TS["TSP Builder<br/>TSP.createProblem"]
PO["Portfolio Builder<br/>Portfolio.createProblem"]
NF["NetworkFlow Builder<br/>NetworkFlow module"]
SCHED["TaskScheduling Builder<br/>scheduledTask { }"]
end
subgraph "Layer 2: Quantum Solvers"
QGC["QuantumGraphColoringSolver<br/>(QAOA)"]
QMC["QuantumMaxCutSolver<br/>(QAOA)"]
QKS["QuantumKnapsackSolver<br/>(QAOA)"]
QTS["QuantumTspSolver<br/>(QAOA)"]
QPO["QuantumPortfolioSolver<br/>(QAOA)"]
QNF["QuantumNetworkFlowSolver<br/>(QAOA)"]
QSCHED["QuantumSchedulingSolver<br/>(QAOA)"]
end
subgraph "Layer 3: Quantum Backends"
LOCAL["LocalBackend<br/>(≤20 qubits)"]
IONQ["IonQBackend<br/>(Azure Quantum)"]
RIGETTI["RigettiBackend<br/>(Azure Quantum)"]
end
GC --> QGC
MC --> QMC
KS --> QKS
TS --> QTS
PO --> QPO
NF --> QNF
SCHED --> QSCHED
QGC --> LOCAL
QMC --> LOCAL
QKS --> LOCAL
QTS --> LOCAL
QPO --> LOCAL
QNF --> LOCAL
QSCHED --> LOCAL
QGC -.-> IONQ
QMC -.-> IONQ
QKS -.-> IONQ
QTS -.-> IONQ
QPO -.-> IONQ
QNF -.-> IONQ
QSCHED -.-> IONQ
QGC -.-> RIGETTI
QMC -.-> RIGETTI
QKS -.-> RIGETTI
QTS -.-> RIGETTI
QPO -.-> RIGETTI
QNF -.-> RIGETTI
QSCHED -.-> RIGETTI
style GC fill:#90EE90
style MC fill:#90EE90
style KS fill:#90EE90
style TS fill:#90EE90
style PO fill:#90EE90
style NF fill:#90EE90
style SCHED fill:#90EE90
style QGC fill:#FFA500
style QMC fill:#FFA500
style QKS fill:#FFA500
style QTS fill:#FFA500
style QPO fill:#FFA500
style QNF fill:#FFA500
style QSCHED fill:#FFA500
style LOCAL fill:#4169E1
style IONQ fill:#4169E1
style RIGETTI fill:#4169E1Who uses it: End users (F# and C# developers)
Purpose: Business domain APIs with problem-specific validation
Features:
graphColoring { })CSharpBuilders.MaxCutProblem())Example:
// F# computation expression
let problem = graphColoring {
node "R1" ["R2"]
colors ["Red"; "Blue"]
}
// Delegates to Layer 2
GraphColoring.solve problem 2 NoneWho uses it: High-level builders (internal delegation)
Purpose: QAOA implementations for specific problem types
Features:
IQuantumBackend)Example:
// Called internally by GraphColoring.solve
QuantumGraphColoringSolver.solve
backend // IQuantumBackend
problem // GraphColoringProblem
quantumConfig // QAOA parametersWho uses it: Quantum solvers
Purpose: Quantum circuit execution
Backend Types:
| Backend | Qubits | Speed | Cost | Use Case |
|---|---|---|---|---|
| LocalBackend | ≤20 | Fast (ms) | Free | Development, testing, small problems |
| IonQBackend | 29+ (sim), 11 (QPU) | Moderate (seconds) | Paid | Production, large problems |
| RigettiBackend | 40+ (sim), 80 (QPU) | Moderate (seconds) | Paid | Production, large problems |
Example:
// Local simulation (default)
let backend = BackendAbstraction.createLocalBackend()
// Azure Quantum (cloud)
let connectionString = "InstrumentationKey=..."
let backend_ionq = BackendAbstraction.createIonQBackend(
connectionString,
"ionq.simulator"
)How LocalBackend simulates quantum circuits:
graph TB
subgraph "LocalBackend (≤20 qubits)"
INIT["StateVector.init<br/>|0⟩⊗n"]
subgraph "Gate Operations"
H["Hadamard (H)<br/>Superposition"]
CNOT["CNOT<br/>Entanglement"]
RX["RX(θ)<br/>X-axis rotation"]
RY["RY(θ)<br/>Y-axis rotation"]
RZ["RZ(θ)<br/>Z-axis rotation"]
end
subgraph "State Evolution"
STATE["Complex State Vector<br/>2^n amplitudes"]
MATRIX["Matrix Multiplication<br/>Gate × State"]
end
subgraph "Measurement"
PROB["Compute Probabilities<br/>|amplitude|²"]
SAMPLE["Sample Bitstrings<br/>(shots times)"]
COUNT["Aggregate Counts<br/>{bitstring → frequency}"]
end
INIT --> H
H --> STATE
CNOT --> STATE
RX --> STATE
RY --> STATE
RZ --> STATE
STATE --> MATRIX
MATRIX --> STATE
STATE --> PROB
PROB --> SAMPLE
SAMPLE --> COUNT
end
subgraph "QAOA Circuit Example"
Q0["Qubit 0: |0⟩"]
Q1["Qubit 1: |0⟩"]
H0["H"]
H1["H"]
COST["Cost Layer<br/>RZ(γ)"]
MIX["Mixer Layer<br/>RX(β)"]
MEAS["Measure<br/>→ '01'"]
Q0 --> H0
Q1 --> H1
H0 --> COST
H1 --> COST
COST --> MIX
MIX --> MEAS
end
COUNT --> MEAS
style INIT fill:#90EE90
style H fill:#FFD700
style CNOT fill:#FFD700
style RX fill:#FFD700
style RY fill:#FFD700
style RZ fill:#FFD700
style STATE fill:#87CEEB
style MATRIX fill:#87CEEB
style PROB fill:#FFA07A
style SAMPLE fill:#FFA07A
style COUNT fill:#FFA07A
style Q0 fill:#E6E6FA
style Q1 fill:#E6E6FA
style MEAS fill:#98FB98Key Components:
StateVector Module 🟢
2^n complex numbers (n = number of qubits)Gate Module 🟡
Measurement Module 🟠
P(x) = |amplitude(x)|²{bitstring → count}QAOA Integration 🟣
Performance:
All problem builders have C#-friendly extensions:
using FSharp.Azure.Quantum;
using static FSharp.Azure.Quantum.CSharpBuilders;
// MaxCut
var vertices = new[] { "A", "B", "C", "D" };
var edges = new[] {
(source: "A", target: "B", weight: 1.0),
(source: "B", target: "C", weight: 2.0)
};
var problem = MaxCutProblem(vertices, edges);
var result = MaxCut.solve(problem, null);
// Knapsack
var items = new[] {
(id: "laptop", weight: 3.0, value: 1000.0),
(id: "phone", weight: 0.5, value: 500.0)
};
var problem = KnapsackProblem(items, capacity: 5.0);
var result = Knapsack.solve(problem, null);
// TSP
var cities = new[] {
(name: "Seattle", x: 0.0, y: 0.0),
(name: "Portland", x: 1.0, y: 0.5)
};
var problem = TspProblem(cities);
var result = TSP.solve(problem, null);
// Portfolio
var assets = new[] {
(symbol: "AAPL", expectedReturn: 0.12, risk: 0.15, price: 150.0),
(symbol: "MSFT", expectedReturn: 0.10, risk: 0.12, price: 300.0)
};
var problem = PortfolioProblem(assets, budget: 10000.0);
var result = Portfolio.solve(problem, null);See: C# Usage Guide for complete examples
// No backend parameter = automatic LocalBackend creation
match GraphColoring.solve problem 3 None with
| Ok solution -> printfn "Solution found"
| Error msg -> printfn "Error: %s" msgWhat happens:
LocalBackend() automatically// Create Azure Quantum backend
let backend = BackendAbstraction.createIonQBackend(
connectionString = "YOUR_CONNECTION_STRING",
targetId = "ionq.simulator" // or "ionq.qpu" for hardware
)
// Pass to solver
match GraphColoring.solve problem 3 (Some backend) with
| Ok solution ->
printfn "Backend used: %s" solution.BackendName// Small problem: Use local simulation
let smallProblem = MaxCut.createProblem ["A"; "B"; "C"] [("A","B",1.0)]
let result1 = MaxCut.solve smallProblem None // Fast, free
// Large problem: Use cloud backend
let largeProblem =
MaxCut.createProblem
[for i in 1..20 -> sprintf "V%d" i]
[for i in 1..19 -> (sprintf "V%d" i, sprintf "V%d" (i+1), 1.0)]
let backend = BackendAbstraction.createIonQBackend(conn, "ionq.simulator")
let result2 = MaxCut.solve largeProblem (Some backend) // Scalable, paidImport and export quantum circuits to IBM Qiskit, Cirq, and other OpenQASM-compatible platforms.
OpenQASM (Open Quantum Assembly Language) is the industry-standard text format for quantum circuits:
F# API:
// open FSharp.Azure.Quantum
// open FSharp.Azure.Quantum.CircuitBuilder
// Build circuit using F# circuit builder
let circuit =
CircuitBuilder.empty 2
|> CircuitBuilder.addGate (H 0)
|> CircuitBuilder.addGate (CNOT (0, 1))
|> CircuitBuilder.addGate (RZ (0, System.Math.PI / 4.0))
// Export to OpenQASM 2.0 string
let qasmCode = OpenQasm.export circuit
printfn "%s" qasmCode
// Export to .qasm file
OpenQasm.exportToFile circuit "bell_state.qasm"Output (bell_state.qasm):
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
h q[0];
cx q[0],q[1];
rz(0.7853981634) q[0];F# API:
// open FSharp.Azure.Quantum
// open System.IO
// Parse OpenQASM string
let qasmCode = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
h q[0];
cx q[0],q[1];
cx q[1],q[2];
"""
match OpenQasmImport.parse qasmCode with
| Ok circuit ->
printfn "Loaded %d-qubit circuit with %d gates"
circuit.QubitCount circuit.Gates.Length
// Use circuit with LocalBackend or export to another format
| Error msg ->
printfn "Parse error: %s" msg
// Import from file
match OpenQasmImport.parseFromFile "grover.qasm" with
| Ok circuit -> printfn "Loaded %d-qubit circuit" circuit.QubitCount
| Error msg -> printfn "Error: %s" msgusing FSharp.Azure.Quantum;
using FSharp.Azure.Quantum.CircuitBuilder;
// Export circuit to OpenQASM
var circuit = CircuitBuilder.empty(2)
.AddGate(Gate.NewH(0))
.AddGate(Gate.NewCNOT(0, 1));
var qasmCode = OpenQasm.export(circuit);
File.WriteAllText("circuit.qasm", qasmCode);
// Import from OpenQASM
var qasmInput = File.ReadAllText("qiskit_circuit.qasm");
var result = OpenQasmImport.parse(qasmInput);
if (result.IsOk) {
var imported = result.ResultValue;
Console.WriteLine($"Loaded {imported.QubitCount}-qubit circuit");
}All standard OpenQASM 2.0 gates supported:
| Category | Gates |
|---|---|
| Pauli | X, Y, Z, H |
| Phase | S, S†, T, T† |
| Rotation | RX(θ), RY(θ), RZ(θ) |
| Two-qubit | CNOT (CX), CZ, SWAP |
| Three-qubit | CCX (Toffoli) |
Full interoperability workflow:
// 1. Load circuit from Qiskit
let qiskitCircuit = OpenQasmImport.parseFromFile "qiskit_algorithm.qasm"
match qiskitCircuit with
| Ok circuit ->
// 2. Run on LocalBackend for testing
let localBackend = BackendAbstraction.createLocalBackend()
let testResult = LocalSimulator.QaoaSimulator.simulate circuit 1000
printfn "Local test: %d samples" testResult.Shots
// 3. Transpile for IonQ hardware
let transpiled = GateTranspiler.transpileForBackend "ionq.qpu" circuit
// 4. Execute on IonQ
let ionqBackend = BackendAbstraction.createIonQBackend(
connectionString,
"ionq.qpu"
)
// 5. Export results back to Qiskit format
OpenQasm.exportToFile transpiled "results_ionq.qasm"
| Error msg ->
printfn "Import failed: %s" msgCircuits are preserved through export/import:
// Original circuit
let original = { QubitCount = 3; Gates = [H 0; CNOT (0, 1); RZ (1, 1.5708)] }
// Export → Import → Compare
let qasm = OpenQasm.export original
let imported = OpenQasmImport.parse qasm
match imported with
| Ok circuit ->
assert (circuit.QubitCount = original.QubitCount)
assert (circuit.Gates.Length = original.Gates.Length)
printfn "✅ Round-trip successful"
| Error msg ->
printfn "❌ Round-trip failed: %s" msgSee: tests/OpenQasmIntegrationTests.fs for comprehensive examples
Reduce quantum noise and improve result accuracy by 30-90% with production-ready error mitigation techniques.
Quantum computers are noisy (NISQ era). Error mitigation improves results without requiring error-corrected qubits:
Error mitigation achieves near-ideal results on noisy hardware - critical for real-world quantum advantage.
Richardson extrapolation to estimate error-free result.
How it works:
Performance:
F# Example:
open FSharp.Azure.Quantum.ErrorMitigation
// Configure ZNE
let zneConfig = {
NoiseScalings = [
ZeroNoiseExtrapolation.IdentityInsertion 0.0 // baseline (1.0x)
ZeroNoiseExtrapolation.IdentityInsertion 0.5 // 1.5x noise
ZeroNoiseExtrapolation.IdentityInsertion 1.0 // 2.0x noise
]
PolynomialDegree = 2
MinSamples = 1000
}
// Apply ZNE to circuit expectation value
// Mock circuit and observable for demonstration
let circuit = QuantumCircuit.empty() // Mock circuit
let observable = PauliOperator.Z(0) // Mock observable
async {
let! result = ZeroNoiseExtrapolation.mitigate circuit observable zneConfig backend
match result with
| Ok zneResult ->
printfn "Zero-noise value: %f" zneResult.ZeroNoiseValue
printfn "R² goodness of fit: %f" zneResult.GoodnessOfFit
printfn "Measured values:"
zneResult.MeasuredValues
|> List.iter (fun (noise, value) -> printfn " λ=%.1f: %f" noise value)
| Error msg ->
printfn "ZNE failed: %s" msg
}When to use:
Quasi-probability decomposition with importance sampling.
How it works:
Performance:
F# Example:
open FSharp.Azure.Quantum.ErrorMitigation
// Configure PEC with noise model
let pecConfig = {
NoiseModel = {
SingleQubitDepolarizing = 0.001 // 0.1% per single-qubit gate
TwoQubitDepolarizing = 0.01 // 1% per two-qubit gate
ReadoutError = 0.02 // 2% readout error
}
Samples = 1000
Seed = Some 42
}
// Apply PEC to circuit
async {
let! result = ProbabilisticErrorCancellation.mitigate circuit observable pecConfig backend
match result with
| Ok pecResult ->
printfn "Corrected expectation: %f" pecResult.CorrectedExpectation
printfn "Uncorrected (noisy): %f" pecResult.UncorrectedExpectation
printfn "Error reduction: %.1f%%" (pecResult.ErrorReduction * 100.0)
printfn "Overhead: %.1fx" pecResult.Overhead
| Error msg ->
printfn "PEC failed: %s" msg
}When to use:
Confusion matrix calibration with matrix inversion.
How it works:
Performance:
F# Example:
open FSharp.Azure.Quantum.ErrorMitigation
// Step 1: Calibrate (one-time cost per backend)
let remConfig =
ReadoutErrorMitigation.defaultConfig
|> ReadoutErrorMitigation.withCalibrationShots 10000
|> ReadoutErrorMitigation.withConfidenceLevel 0.95
async {
// Calibrate confusion matrix (run once, cache result)
let! calibrationResult = ReadoutErrorMitigation.calibrate remConfig backend
match calibrationResult with
| Ok calibMatrix ->
printfn "Calibration complete:"
printfn " Qubits: %d" calibMatrix.Qubits
printfn " Shots: %d" calibMatrix.CalibrationShots
printfn " Backend: %s" calibMatrix.Backend
// Step 2: Correct measurement histogram (zero overhead!)
let noisyHistogram = Map.ofList [("00", 0.9); ("01", 0.05); ("10", 0.03); ("11", 0.02)] // Mock noisy results
let correctedResult = ReadoutErrorMitigation.correctHistogram noisyHistogram calibMatrix remConfig
match correctedResult with
| Ok corrected ->
printfn "\nCorrected histogram:"
corrected.Histogram
|> Map.iter (fun state prob -> printfn " |%s⟩: %.4f" state prob)
printfn "\nConfidence intervals (95%%):"
corrected.ConfidenceIntervals
|> Map.iter (fun state (lower, upper) ->
printfn " |%s⟩: [%.4f, %.4f]" state lower upper)
| Error msg ->
printfn "Correction failed: %s" msg
| Error msg ->
printfn "Calibration failed: %s" msg
}When to use:
Let the library choose the best technique for your circuit.
F# Example:
open FSharp.Azure.Quantum.ErrorMitigation
// Define selection criteria
let criteria = {
CircuitDepth = 25
QubitCount = 6
Backend = Types.Backend.IonQBackend
MaxCostUSD = Some 10.0
RequiredAccuracy = Some 0.95
}
// Get recommended strategy
let recommendation = ErrorMitigationStrategy.selectStrategy criteria
printfn "Recommended: %s" (
match recommendation.Primary with
| ZeroNoiseExtrapolation _ -> "Zero-Noise Extrapolation (ZNE)"
| ProbabilisticErrorCancellation _ -> "Probabilistic Error Cancellation (PEC)"
| ReadoutErrorMitigation _ -> "Readout Error Mitigation (REM)"
| Combined _ -> "Combined Techniques"
)
printfn "Reasoning: %s" recommendation.Reasoning
printfn "Estimated cost multiplier: %.1fx" recommendation.EstimatedCostMultiplier
printfn "Estimated accuracy: %.1f%%" (recommendation.EstimatedAccuracy * 100.0)
// Apply recommended strategy
let noisyHistogram = Map.ofList [("00", 0.9); ("01", 0.05); ("10", 0.03); ("11", 0.02)] // Mock noisy results
let mitigatedResult = ErrorMitigationStrategy.applyStrategy noisyHistogram recommendation.Primary
match mitigatedResult with
| Ok result ->
printfn "\nMitigation successful:"
printfn " Technique: %A" result.AppliedTechnique
printfn " Used fallback: %b" result.UsedFallback
printfn " Actual cost: %.1fx" result.ActualCostMultiplier
result.Histogram |> Map.iter (fun k v -> printfn " %s: %f" k v)
| Error msg ->
printfn "Mitigation failed: %s" msgStrategy selection logic:
| Circuit Type | Best Technique | Error Reduction | Cost | Why |
|---|---|---|---|---|
| Shallow (< 20 gates) | REM | 50-90% | ~0x | Readout dominates |
| Medium (20-50 gates) | ZNE | 30-50% | 3x | Balanced gate/readout |
| Deep (> 50 gates) | PEC or ZNE+REM | 40-70% | 10-100x | High gate errors |
| Cost-constrained | REM | 50-90% | ~0x | Free after calibration |
| High accuracy | PEC | 2-3x | 10-100x | Research/benchmarking |
open FSharp.Azure.Quantum
open FSharp.Azure.Quantum.ErrorMitigation
// Define MaxCut problem
let vertices = ["A"; "B"; "C"; "D"]
let edges = [
("A", "B", 1.0)
("B", "C", 2.0)
("C", "D", 1.0)
("D", "A", 1.0)
]
let problem = MaxCut.problem vertices edges
// Solve with ZNE error mitigation
let zneConfig = {
NoiseScalings = [
ZeroNoiseExtrapolation.IdentityInsertion 0.0
ZeroNoiseExtrapolation.IdentityInsertion 0.5
ZeroNoiseExtrapolation.IdentityInsertion 1.0
]
PolynomialDegree = 2
MinSamples = 1000
}
async {
// Standard solve (noisy)
let! noisyResult = MaxCut.solve problem None
// Solve with ZNE (error-mitigated)
let! mitigatedResult = MaxCut.solveWithErrorMitigation problem (Some zneConfig) None
match noisyResult, mitigatedResult with
| Ok noisy, Ok mitigated ->
printfn "Noisy cut value: %.2f" noisy.CutValue
printfn "ZNE-mitigated cut value: %.2f" mitigated.CutValue
printfn "Improvement: %.1f%%" ((mitigated.CutValue - noisy.CutValue) / noisy.CutValue * 100.0)
| _ ->
printfn "Error occurred"
}Expected improvement: 30-50% better cut value on noisy hardware.
Error mitigation is production-ready with comprehensive testing:
See: tests/FSharp.Azure.Quantum.Tests/*ErrorMitigation*.fs
QAOA (Quantum Approximate Optimization Algorithm):
QUBO Encoding: Convert problem → Quadratic Unconstrained Binary Optimization
Graph Coloring → Binary variables for node-color assignments
MaxCut → Binary variables for partition membership
Circuit Construction: Build parameterized quantum circuit
|0⟩^n → H^⊗n → [Cost Layer (γ)] → [Mixer Layer (β)] → Measure
Parameter Optimization: Find optimal (γ, β) using Nelder-Mead
for iteration in 1..maxIterations do
let cost = evaluateCost(gamma, beta)
optimizer.Update(cost)
Solution Extraction: Decode measurement results → problem solution
Bitstring "0101" → [R1→Red, R2→Blue, R3→Red, R4→Blue]
// Custom QAOA parameters
let quantumConfig : QuantumGraphColoringSolver.QuantumGraphColoringConfig = {
OptimizationShots = 100 // Shots per optimization step
FinalShots = 1000 // Shots for final measurement
EnableOptimization = true // Enable parameter optimization
InitialParameters = (0.5, 0.5) // Starting (gamma, beta)
}
// Use custom config
let backend = BackendAbstraction.createLocalBackend()
match QuantumGraphColoringSolver.solve backend problem quantumConfig with
| Ok result -> printfn "Colors used: %d" result.ColorsUsed
| Error msg -> printfn "Error: %s" msg| Problem Type | Small (LocalBackend) | Medium | Large (Cloud Required) |
|---|---|---|---|
| Graph Coloring | ≤20 nodes | 20-30 nodes | 30+ nodes |
| MaxCut | ≤20 vertices | 20-30 vertices | 30+ vertices |
| Knapsack | ≤20 items | 20-30 items | 30+ items |
| TSP | ≤8 cities | 8-12 cities | 12+ cities |
| Portfolio | ≤20 assets | 20-30 assets | 30+ assets |
| Network Flow | ≤15 nodes | 15-25 nodes | 25+ nodes |
| Task Scheduling | ≤15 tasks | 15-25 tasks | 25+ tasks |
Note: LocalBackend limited to 20 qubits. Larger problems require Azure Quantum backends.
FSharp.Azure.Quantum is a quantum-first library - NO classical algorithms.
Why?
What this means:
// ✅ QUANTUM: QAOA-based optimization
GraphColoring.solve problem 3 None
// ❌ NO CLASSICAL FALLBACK: If quantum fails, returns Error
// Users should use dedicated classical libraries for that use caseNo leaky abstractions - Each layer has clear responsibilities.
Note: The following algorithms are provided for quantum computing education and research. They are NOT optimization solvers and should not be used for production optimization tasks. For production optimization, use the Problem Builders or HybridSolver above.
In addition to the production-ready optimization solvers above, the library includes foundational quantum algorithms for education and research:
Quantum search algorithm for finding elements in unsorted databases.
open FSharp.Azure.Quantum.GroverSearch
// Search for item satisfying predicate
let searchConfig = {
MaxIterations = Some 10
SuccessThreshold = 0.9
OptimizeIterations = true
Shots = 1000
RandomSeed = Some 42
}
// Search 8-item space for items where f(x) = true
let predicate x = x = 3 || x = 5 // Looking for indices 3 or 5
match Search.searchWithPredicate 3 predicate searchConfig with
| Ok result ->
printfn "Found solutions: %A" result.Solutions
printfn "Success probability: %.2f%%" (result.SuccessProbability * 100.0)
printfn "Iterations: %d" result.IterationsApplied
| Error msg ->
printfn "Search failed: %s" msgFeatures:
Location: src/FSharp.Azure.Quantum/Algorithms/
Status: Experimental - Research and education purposes
Note: Grover's algorithm is a standalone quantum search primitive, separate from the QAOA-based optimization builders. It does not use the IBackend abstraction and is optimized for specific search problems rather than general combinatorial optimization.
Generalization of Grover's algorithm for custom initial states.
Amplitude amplification extends Grover's algorithm to work with arbitrary initial state preparations (not just uniform superposition). This enables quantum speedups for problems beyond simple database search.
Key Insight: Grover's algorithm is a special case where:
Amplitude amplification allows:
Example:
open FSharp.Azure.Quantum.GroverSearch.AmplitudeAmplificationAdapter
open FSharp.Azure.Quantum.Core.BackendAbstraction
// Execute amplitude amplification on quantum hardware backend
let backend = createIonQBackend(connectionString, "ionq.simulator")
// Define oracle (marks solution states)
let oracle = StateOracle(fun state -> state = 3 || state = 5)
// Configure amplitude amplification
let config = {
NumQubits = 3
StatePreparation = UniformSuperposition // or BasisState(n), PartialSuperposition(states)
Oracle = oracle
Iterations = 2 // Optimal iterations for 2 solutions in 8-element space
}
match executeWithBackend config backend 1000 with
| Ok measurementCounts ->
printfn "Amplitude amplification executed on quantum hardware"
measurementCounts
|> Map.iter (fun state count -> printfn " |%d⟩: %d counts" state count)
| Error msg ->
printfn "Backend execution failed: %s" msg
// Convenience functions
executeUniformAmplification 3 oracle 2 backend 1000 // Uniform initial state
executeBasisStateAmplification 3 5 oracle 2 backend 1000 // Start from |5⟩Features:
Backend Limitations:
Use Cases:
Location: Algorithms/AmplitudeAmplificationAdapter.fs
Status: Production-ready
Quantum analog of the discrete Fourier transform - foundational building block for many quantum algorithms.
The QFT transforms computational basis states into frequency basis with exponential speedup over classical FFT:
Mathematical Transform:
QFT: |j⟩ → (1/√N) Σₖ e^(2πijk/N) |k⟩
Example:
open FSharp.Azure.Quantum.GroverSearch.QFTBackendAdapter
open FSharp.Azure.Quantum.Core.BackendAbstraction
// Execute QFT on quantum hardware backend
let backend = createIonQBackend(connectionString, "ionq.simulator")
let config = { NumQubits = 5; ApplySwaps = true; Inverse = false }
match executeQFTWithBackend config backend 1000 None with
| Ok measurementCounts ->
printfn "QFT executed on quantum hardware"
measurementCounts
|> Map.iter (fun state count -> printfn " |%d⟩: %d counts" state count)
| Error msg ->
printfn "Backend execution failed: %s" msg
// Convenience functions
executeStandardQFT 5 backend 1000 // Standard QFT with swaps
executeInverseQFT 5 backend 1000 // Inverse QFT (QFT†)
executeQFTOnState 5 7 backend 1000 // QFT on specific input state |7⟩Features:
Backend Limitations:
Use Cases:
Performance:
Location: Algorithms/QFTBackendAdapter.fs
Status: Production-ready
High-level builders for cryptography, quantum chemistry, and research applications.
The library provides three advanced builders that wrap QFT-based quantum algorithms for real-world business scenarios:
Use Case: Cryptographic operations, RSA encryption, modular arithmetic
open FSharp.Azure.Quantum.QuantumArithmeticOps
// RSA encryption: m^e mod n
let encryptOp = quantumArithmetic {
operands 5 3 // message=5, exponent=3
operation ModularExponentiate
modulus 33 // RSA modulus
qubits 8
}
match execute encryptOp with
| Ok result ->
printfn "Encrypted: %d" result.Value
printfn "Gates: %d, Depth: %d" result.GateCount result.CircuitDepth
| Error msg ->
printfn "Error: %s" msgC# API:
using static FSharp.Azure.Quantum.CSharpBuilders;
var encrypt = ModularExponentiate(baseValue: 5, exponent: 3, modulus: 33);
var result = ExecuteArithmetic(encrypt);Business Applications:
Example: examples/QuantumArithmetic/
Use Case: RSA security assessment, post-quantum cryptography planning
open FSharp.Azure.Quantum.QuantumPeriodFinder
// Factor RSA modulus (security analysis)
let problem = periodFinder {
number 15 // Composite to factor
precision 8 // QPE precision
maxAttempts 10 // Retries (probabilistic)
}
match solve problem with
| Ok result ->
match result.Factors with
| Some (p, q) ->
printfn "Factors: %d × %d" p q
printfn "⚠️ RSA Security Broken!"
| None ->
printfn "Try again (probabilistic)"
| Error msg ->
printfn "Error: %s" msgC# API:
var problem = FactorInteger(15, precision: 8);
var result = ExecutePeriodFinder(problem);Business Applications:
Example: examples/CryptographicAnalysis/
Use Case: Drug discovery, molecular simulation, materials science
open FSharp.Azure.Quantum.QuantumPhaseEstimator
// Estimate molecular ground state energy
let problem = phaseEstimator {
unitary (RotationZ (Math.PI / 3.0)) // Molecular Hamiltonian
precision 12 // 12-bit energy precision
}
match estimate problem with
| Ok result ->
printfn "Phase: %.6f" result.Phase
printfn "Energy: %.4f a.u." (result.Phase * 2.0 * Math.PI)
printfn "Application: Drug binding affinity prediction"
| Error msg ->
printfn "Error: %s" msgC# API:
var problem = EstimateRotationZ(Math.PI / 3.0, precision: 12);
var result = ExecutePhaseEstimator(problem);Business Applications:
Example: examples/PhaseEstimation/
Phase 2 Builder Features:
Current Status: Educational/research focus - Demonstrates quantum algorithms but hardware insufficient for real-world applications (2024-2025)
High-level builders for specialized quantum algorithms using computation expression syntax.
Beyond the optimization and QFT-based builders, the library provides five advanced builders for specialized quantum computing tasks:
Use Case: Graph traversal, decision trees, game tree exploration
open FSharp.Azure.Quantum.QuantumTreeSearchBuilder
// Search decision tree with quantum parallelism
let searchProblem = QuantumTreeSearch.quantumTreeSearch {
depth 5 // Tree depth
branchingFactor 3 // Children per node
target 42 // Target node value
qubits 10
}
match search searchProblem with
| Ok result ->
printfn "Found path: %A" result.Path
printfn "Depth explored: %d" result.DepthReached
printfn "Success probability: %.2f%%" (result.Probability * 100.0)
| Error msg ->
printfn "Error: %s" msgFeatures:
QuantumTreeSearch.quantumTreeSearch { }Use Case: SAT solving, constraint satisfaction problems, logic puzzles
open FSharp.Azure.Quantum.QuantumConstraintSolverBuilder
// Solve boolean satisfiability (SAT) problem
let satProblem = QuantumConstraintSolver.constraintSolver {
variables ["x"; "y"; "z"]
clause ["x"; "!y"] // x OR NOT y
clause ["!x"; "z"] // NOT x OR z
clause ["y"; "!z"] // y OR NOT z
qubits 8
}
match solve satProblem with
| Ok solution ->
printfn "Satisfying assignment:"
solution.Assignment
|> Map.iter (fun var value -> printfn " %s = %b" var value)
printfn "Clauses satisfied: %d/%d" solution.SatisfiedClauses solution.TotalClauses
| Error msg ->
printfn "Error: %s" msgFeatures:
QuantumConstraintSolver.constraintSolver { }Use Case: String matching, DNA sequence alignment, anomaly detection
open FSharp.Azure.Quantum.QuantumPatternMatcherBuilder
// Find pattern in data stream with quantum speedup
let matchProblem = QuantumPatternMatcher.patternMatcher {
haystack [1; 2; 3; 4; 5; 6; 7; 8]
needle [3; 4; 5]
tolerance 0 // Exact match
qubits 12
}
match find matchProblem with
| Ok result ->
printfn "Pattern found at positions: %A" result.Positions
printfn "Total matches: %d" result.MatchCount
printfn "Search probability: %.2f%%" (result.Probability * 100.0)
| Error msg ->
printfn "Error: %s" msgFeatures:
QuantumPatternMatcher.patternMatcher { }Use Case: Cryptographic operations, RSA encryption, modular arithmetic
open FSharp.Azure.Quantum.QuantumArithmeticBuilder
// Quantum integer addition
let addProblem = QuantumArithmeticOps.quantumArithmetic {
operands 15 27 // 15 + 27
operation Add
qubits 10
}
match compute addProblem with
| Ok result ->
printfn "Result: %d" result.Value
printfn "Carry: %b" result.Carry
printfn "Gates used: %d" result.GateCount
printfn "Circuit depth: %d" result.CircuitDepth
| Error msg ->
printfn "Error: %s" msg
// Modular exponentiation for RSA
let rsaProblem = QuantumArithmeticOps.quantumArithmetic {
operands 5 3 // base=5, exponent=3
operation ModularExponentiate
modulus 33 // RSA modulus
qubits 12
}Features:
QuantumArithmeticOps.quantumArithmetic { }Use Case: Shor's algorithm, cryptanalysis, order finding
open FSharp.Azure.Quantum.QuantumPeriodFinderBuilder
// Find period of modular function (Shor's algorithm)
let shorsProblem = QuantumPeriodFinder.periodFinder {
number 15 // Composite to factor
base_ 7 // Coprime base
precision 12 // QPE precision bits
maxAttempts 10 // Probabilistic retries
}
match findPeriod shorsProblem with
| Ok result ->
printfn "Period found: %d" result.Period
match result.Factors with
| Some (p, q) ->
printfn "Factors: %d × %d = %d" p q (p * q)
printfn "⚠️ RSA modulus factored!"
| None ->
printfn "Retry with different base (probabilistic)"
| Error msg ->
printfn "Error: %s" msgFeatures:
QuantumPeriodFinder.periodFinder { }Use Case: Eigenvalue estimation, quantum chemistry, VQE enhancement
open FSharp.Azure.Quantum.QuantumPhaseEstimatorBuilder
open FSharp.Azure.Quantum.Algorithms.QuantumPhaseEstimation
// Estimate eigenphase of unitary operator
let qpeProblem = QuantumPhaseEstimator.phaseEstimator {
unitary (RotationZ (Math.PI / 4.0)) // Operator U
eigenstate 0 // |ψ⟩ = |0⟩
precision 16 // 16-bit phase precision
qubits 20
}
match estimate qpeProblem with
| Ok result ->
printfn "Estimated phase: %.6f" result.Phase
printfn "Eigenvalue: e^(2πi × %.6f)" result.Phase
printfn "Confidence: %.2f%%" (result.Confidence * 100.0)
printfn "Application: Molecular energy = %.4f Hartree" (result.Phase * 2.0 * Math.PI)
| Error msg ->
printfn "Error: %s" msgFeatures:
QuantumPhaseEstimator.phaseEstimator { }Common Capabilities:
Current Status:
Use Cases by Builder:
| Builder | Primary Application | Quantum Advantage | Hardware Readiness |
|---|---|---|---|
| Tree Search | Game AI, Route Planning | O(√N) speedup | 2028+ (requires 50+ qubits) |
| Constraint Solver | SAT, Logic Puzzles | O(√2^n) speedup | 2030+ (requires 100+ qubits) |
| Pattern Matcher | DNA Alignment, Data Mining | O(√N) speedup | 2027+ (requires 30+ qubits) |
| Arithmetic | Cryptography, RSA | Polynomial vs exponential | 2026+ (requires 4096+ qubits for RSA-2048) |
| Period Finder | Shor's Algorithm, Cryptanalysis | Exponential speedup | 2029+ (requires 4096+ qubits) |
| Phase Estimator | Quantum Chemistry, VQE | Polynomial speedup | 2025+ (10-20 qubits sufficient for small molecules) |
Recommendation:
All advanced builders have C#-friendly fluent APIs:
using FSharp.Azure.Quantum;
using static FSharp.Azure.Quantum.CSharpBuilders;
// Tree Search
var treeSearch = TreeSearch(depth: 5, branchingFactor: 3, target: 42);
var searchResult = ExecuteTreeSearch(treeSearch);
// Constraint Solver
var satProblem = ConstraintProblem(
variables: new[] { "x", "y", "z" },
clauses: new[] {
new[] { "x", "!y" },
new[] { "!x", "z" }
}
);
var satResult = SolveConstraints(satProblem);
// Pattern Matcher
var pattern = PatternMatch(
haystack: new[] { 1, 2, 3, 4, 5, 6, 7, 8 },
needle: new[] { 3, 4, 5 },
tolerance: 0
);
var matchResult = FindPattern(pattern);
// Arithmetic
var add = ArithmeticAdd(15, 27);
var addResult = ComputeArithmetic(add);
var rsa = ModularExponentiate(baseValue: 5, exponent: 3, modulus: 33);
var rsaResult = ComputeArithmetic(rsa);
// Period Finder (Shor's)
var shors = FactorInteger(15, precision: 12);
var factorResult = FindPeriod(shors);
// Phase Estimator
var qpe = EstimateRotationZ(Math.PI / 4.0, precision: 16);
var phaseResult = EstimatePhase(qpe);Current Status: Educational/research focus - Demonstrates quantum algorithms but hardware insufficient for real-world applications (2024-2025)
Primary Focus: QAOA-Based Combinatorial Optimization
This library is designed for NISQ-era practical quantum advantage in optimization:
Secondary Focus: Quantum Algorithm Education & Research
The Algorithms/ directory contains foundational quantum algorithms for learning:
Why F# for Quantum?
Contributions welcome!
Development principles:
Unlicense - Public domain. Use freely for any purpose.
Status: Production Ready - Quantum-only architecture, 6 problem builders, full QAOA implementation