Computation Expressions (CE) Reference
This page lists every computation expression (CE) in FSharp.Azure.Quantum with its custom operations. Use it as a quick lookup when IntelliSense does not show the operations of a CE.
Overview
Computation expressions give a declarative way to describe quantum problems, circuits and schedules. Each CE has its own custom operations. What a CE returns differs between builders, so each section below states the result type:
- Problem builders (
constraintSolver,patternMatcher,quantumTreeSearch,graphColoring,circuit) return the problem or circuit and throw an exception if validation fails. - Validated problem builders (
periodFinder,phaseEstimator,quantumArithmetic,linearSystemSolver) returnResult<Problem, QuantumError>; pass theOkvalue to the module’s solve function. - Run-on-evaluation builders (the ML builders,
anomalyDetection,similaritySearch,coverageOptimizer,resourcePairing,packingOptimizer,constraintScheduler,socialNetwork,quantumRiskEngine,drugDiscovery) start the work when the CE is evaluated and return aTask<QuantumResult<_>>(QuantumResult<_>isResult<_, QuantumError>); bind it withlet!insidetask { }orquantumResultTask { }. - Configuration builders (
coloredNode,resource,scheduledTask,scheduling) return the record they build.quantumChemistryreturns aChemistryProblemand throws if a required operation is missing. optionPricingruns when evaluated and returnsTask<QuantumResult<OptionPrice>>;topologicalreturns a program to pass toTopologicalBuilder.execute.- Result builders (
quantumResult,quantumResultTask) chain steps that returnQuantumResult<_>orTask<QuantumResult<_>>; see Chaining Results.
Quick Reference Table
| CE Name | Description | Custom Operations |
|---|---|---|
| anomalyDetection | Detect outliers and anomalies in data | trainOnNormalData, sensitivity, contaminationRate, backend, shots, verbose, saveModelTo, note, progressReporter, cancellationToken |
| autoML | Automated ML - tries several model types and returns the best | trainWith, tryBinaryClassification, tryMultiClass, tryAnomalyDetection, tryRegression, trySimilaritySearch, tryArchitectures, maxTrials, maxTimeMinutes, validationSplit, backend, verbose, saveModelTo, randomSeed, progressReporter, cancellationToken |
| binaryClassification | Classify items into two categories | trainWith, architecture, learningRate, maxEpochs, convergenceThreshold, backend, shots, verbose, saveModelTo, note, progressReporter, cancellationToken |
| circuit | Build quantum circuits gate by gate | qubits, H, X, Y, Z, S, SDG, T, TDG, P, RX, RY, RZ, CNOT, CZ, CP, SWAP, RXX, RYY, RZZ, CCX, gate, Measure, Reset, Barrier |
| coloredNode | Define a node in a graph coloring problem | nodeId, conflictsWith, fixedColor, priority, avoidColors, property |
| constraintScheduler | Task-to-resource scheduling with hard and soft constraints | task, tasks, resource, resourceWithCapacity, conflict, require, precedence, prefer, optimizeFor, maxBudget, backend, shots, useGrover, useQaoa |
| constraintSolver<’T> | Constraint satisfaction problems (CSP) with Grover search | searchSpace, domain, satisfies, backend, maxIterations, shots, onProgress |
| coverageOptimizer | Set coverage (minimum-cost covering) | element, universeSize, option, backend, shots |
| drugDiscovery | Virtual screening of drug candidates | load_candidates_from_file, load_candidates_from_provider, load_candidates_from_provider_async, target_protein_from_pdb, use_method, use_feature_map, set_batch_size, shots, backend, vqc_layers, vqc_max_epochs, selection_budget, diversity_weight |
| graphColoring | Graph coloring problems | node, nodes, colors, maxColors, objective, conflictPenalty |
| linearSystemSolver | Linear systems Ax = b with the HHL algorithm | matrix, diagonalMatrix, vector, eigenvalueQubits, precision, inversionMethod, minEigenvalue, postSelection, backend, shots |
| optionPricing | Price options with quantum Monte Carlo (amplitude estimation) | spotPrice, strikePrice, riskFreeRate, volatility, expiry, optionType, qubits, iterations, shots, backend, cancellation_token |
| packingOptimizer | Bin packing (minimize containers) | item, containerCapacity, backend, shots |
| patternMatcher<’T> | Find items matching a predicate with Grover search | searchSpace, searchSpaceSize, matchPattern, findTop, backend, maxIterations, shots |
| periodFinder | Period finding (Shor’s algorithm) | number, chosenBase, precision, exactness, maxAttempts, backend, shots |
| phaseEstimator | Quantum phase estimation (QPE) | unitary, precision, targetQubits, eigenstate, applySwaps, swaps, exactness, backend, shots |
| predictiveModel | Predict continuous values or categories | trainWith, problemType, architecture, learningRate, maxEpochs, convergenceThreshold, backend, shots, verbose, saveModelTo, note, progressReporter, cancellationToken |
| quantumArithmetic | Quantum arithmetic operations | operands, operandA, operandB, operation, modulus, qubits, exponent, backend, shots |
| quantumChemistry | Ground state energy with VQE or QPE | molecule, basis, ansatz, groundStateMethod, optimizer, maxIterations, initialParameters, integralProvider, molecule_from_xyz, molecule_from_fcidump, molecule_from_provider, molecule_from_name |
| quantumRiskEngine | Portfolio risk metrics (VaR, CVaR) | load_market_data, set_confidence_level, set_simulation_paths, use_amplitude_estimation, use_error_mitigation, calculate_metric, cancellation_token, qubits, iterations, shots, backend |
| quantumTreeSearch<’T> | Game-tree and decision-tree search with Grover search | initialState, maxDepth, branchingFactor, evaluateWith, generateMovesWith, topPercentile, backend, shots, solutionThreshold, successThreshold, maxPaths, limitSearchSpace, maxIterations, onProgress |
| resource<’T> | A resource for task scheduling | resourceId, capacity, costPerUnit, availableWindow |
| resourcePairing | 1:1 pairing that maximizes total compatibility | participant, participants, compatibility, backend, shots |
| scheduledTask<’T> | A task for task scheduling | taskId, duration, after, afterMultiple, requires, priority, deadline, earliestStart |
| scheduling<’TTask, ‘TResource> | A complete task scheduling problem | tasks, resources, objective, timeHorizon |
| similaritySearch<’T> | Find similar items (cosine, Euclidean or quantum kernel) | indexItems, similarityMetric, threshold, backend, shots, verbose, saveIndexTo, note, progressReporter, cancellationToken |
| socialNetwork | Communities, monitor sets and pairings in a network | person, people, connection, connections, findCommunities, findLargestCommunity, findMonitorSet, findPairings, backend, useGrover, useQaoa, shots |
| topological | Topological programs with anyon braiding | No custom operations: let!/do! with TopologicalBuilder.initialize, braid, measure, braidSequence, getState, getResults, getLog, getContext |
Detailed Documentation
The examples on this page share these opens and a local simulator backend:
open System
open System.Threading
open FSharp.Azure.Quantum
open FSharp.Azure.Quantum.Core
open FSharp.Azure.Quantum.Core.BackendAbstraction
open FSharp.Azure.Quantum.Backends
let localBackend = LocalBackend.LocalBackend() :> IQuantumBackend
The local simulator’s qubit limit is derived from available memory and capped at 30 qubits. Most builders below apply tighter limits of their own, stated in each section.
1. circuit
Module: FSharp.Azure.Quantum.CircuitBuilder
Purpose: Build quantum circuits declaratively. The result is a CircuitBuilder.Circuit; the builder validates the circuit when the CE finishes and throws an exception if it is invalid (for example a gate on a qubit index outside qubits).
Example:
open FSharp.Azure.Quantum.CircuitBuilder
let bellState = circuit {
qubits 2
H 0
CNOT (0, 1)
}
Custom Operations:
qubits n- Number of qubits (set it before the gates)- Single-qubit gates:
H,X,Y,Z,S,SDG,T,TDGtake a qubit index;Ptakes a qubit and an angle - Rotation gates:
RX,RY,RZtake a qubit and an angle - Two-qubit gates:
CNOT,CZ,SWAPtake two qubits;CPtakes two qubits and an angle - Ising interaction gates:
RXX,RYY,RZZtake two qubits and an angle - Three-qubit gate:
CCX(Toffoli) takes two controls and a target gate g- Add anyCircuitBuilder.Gatevalue (for gates without their own operation, such asU3,CRXorMCZ)Measure q,Reset q,Barrier [qubits]
Multi-argument gates accept either a tuple (CNOT (0, 1)) or separate arguments (CNOT 0 1).
Loops: custom operations cannot use a for loop variable. Inside a loop, use yield! with the singleGate or multiGate helpers (see For Loops in CEs and Computation Expression Composition).
2. coloredNode
Module: FSharp.Azure.Quantum.GraphColoring
Purpose: Define one node of a graph coloring problem. Returns a ColoredNode.
Example:
open FSharp.Azure.Quantum.GraphColoring
let node1 = coloredNode {
nodeId "R1"
conflictsWith ["R2"; "R3"]
priority 1.0
}
Custom Operations:
nodeId- Unique identifier for the nodeconflictsWith- Node IDs that must not get the same colorfixedColor- Pre-assign a colorpriority- Priority for tie-breaking (higher = assigned first; default 0.0)avoidColors- Colors to avoid if possible (soft constraint)property key value- Add a metadata entry (valueisobj)
3. graphColoring
Module: FSharp.Azure.Quantum.GraphColoring
Purpose: Define a complete graph coloring problem. Returns a GraphColoringProblem (validated; invalid problems throw). Solve it with GraphColoring.solveAsync problem numColors backendOption cancellationToken.
Example:
let coloring = graphColoring {
node "R1" ["R2"]
node "R2" ["R1"; "R3"]
nodes [ coloredNode { nodeId "R3"; conflictsWith ["R2"] } ]
colors ["EAX"; "EBX"; "ECX"]
objective MinimizeColors
}
task {
match! GraphColoring.solveAsync coloring 3 None CancellationToken.None with
| Ok solution -> printfn "Colors used: %d, valid: %b" solution.ColorsUsed solution.IsValid
| Error err -> printfn "Error: %s" err.Message
}
Custom Operations:
node id conflicts- Add a node from its ID and the IDs it conflicts withnodes- Add a list ofColoredNodevalues (built withcoloredNode)colors- Available colorsmaxColors- Use only the firstmaxColorscolors-
objective-MinimizeColors(default)MinimizeConflictsBalanceColors conflictPenalty- Multiplier on the conflict penalty (positive; default 1.0)
4. constraintSolver<’T>
Module: FSharp.Azure.Quantum.QuantumConstraintSolver
Purpose: Find an assignment of values to variables that satisfies all constraints, using Grover search. Returns a ConstraintProblem<'T> (validated; invalid problems throw). Solve it with QuantumConstraintSolver.solve.
Example:
open FSharp.Azure.Quantum.QuantumConstraintSolver
let allDifferent (assignment: Map<int, int>) =
let values = assignment |> Map.toList |> List.map snd
List.length (List.distinct values) = List.length values
let rowProblem = constraintSolver<int> {
searchSpace 4 // 4 variables (4 × log2(4) = 8 qubits)
domain [1..4]
satisfies allDifferent
shots 1000
}
match QuantumConstraintSolver.solve rowProblem with
| Ok solution -> printfn "Assignment: %A" solution.Assignment
| Error err -> printfn "Error: %s" err.Message
Custom Operations:
searchSpace- Number of variables; each takes one value fromdomain. numVariables × log2(domainSize) qubits, up to what the backend runsdomain- Values each variable can takesatisfies- Add a constraintMap<int, 'T> -> bool(keys are variable indices 0..n-1); use it several times to add several constraints, all must holdbackend- Quantum backend (default: LocalBackend)maxIterations- Grover iterations (default: calculated from the search space)shots- Measurement shots (default: 1000)onProgress- Progress reporter (Progress.IProgressReporter)
Notes:
- At least one
satisfiesis required. - The oracle evaluates your predicates; on the local simulator every candidate assignment is evaluated, so there is no speedup over classical enumeration there.
5. patternMatcher<’T>
Module: FSharp.Azure.Quantum.QuantumPatternMatcher
Purpose: Find items that match a predicate, using Grover search. Returns a PatternProblem<'T> (validated; invalid problems throw). Solve it with QuantumPatternMatcher.solve.
Example:
open FSharp.Azure.Quantum.QuantumPatternMatcher
type Config = { Name: string; Performance: float; Cost: float }
let allConfigs =
[ for i in 0 .. 15 -> { Name = $"cfg{i}"; Performance = float i / 16.0; Cost = float (i * 10) } ]
let search = patternMatcher<Config> {
searchSpace allConfigs
matchPattern (fun cfg -> cfg.Performance > 0.8 && cfg.Cost < 150.0)
findTop 2
shots 500
}
match QuantumPatternMatcher.solve search with
| Ok solution -> printfn "Matches: %A" solution.Matches
| Error err -> printfn "Error: %s" err.Message
Custom Operations:
searchSpace- A'T listof items to search, or anintsearch space sizesearchSpaceSize- Search space size as an integer (items are then the indices)matchPattern- Predicate'T -> bool; a latermatchPatternreplaces an earlier one, so combine conditions in one predicatefindTop- Number of matches to return (default: 1)backend- Quantum backend (default: LocalBackend)maxIterations- Grover iterations (default: calculated)shots- Measurement shots (default: 1000)
Notes: the search space must fit the backend: log₂(items) qubits, up to what it runs.
6. periodFinder
Module: FSharp.Azure.Quantum.QuantumPeriodFinder
Purpose: Period finding for integer factorization (Shor’s algorithm). Returns Result<PeriodFinderProblem, QuantumError>; solve the Ok value with QuantumPeriodFinder.solve.
Example:
open FSharp.Azure.Quantum.QuantumPeriodFinder
let shorProblem = periodFinder {
number 15
precision 8
maxAttempts 10
}
match shorProblem |> Result.bind QuantumPeriodFinder.solve with
| Ok result -> printfn "Period: %d, factors: %A" result.Period result.Factors
| Error err -> printfn "Error: %s" err.Message
Custom Operations:
number- Number to factor (4 to 46340; default 15; the circuit must fit the backend)chosenBase- Base a with 2 ≤ a < N. If not set, a base is chosen automaticallyprecision- QPE precision qubits (at least 1; default 8; recommended 2·log₂(N) + 3; the circuit must fit the backend)exactness-QPE.Exact(default) orQPE.Approximate epsilonmaxAttempts- Maximum attempts (1 to 100; default 10)backend- Quantum backend (default: LocalBackend)shots- Accepted but not used: each attempt reads one measurement and turns it into a period candidate; raisemaxAttemptsfor more samples
Notes:
- Uses quantum phase estimation internally.
- Higher
precisiongives a better phase estimate but needs more qubits.
7. phaseEstimator
Module: FSharp.Azure.Quantum.QuantumPhaseEstimator (unitaries such as TGate are in FSharp.Azure.Quantum.Algorithms.QPE)
| Purpose: Estimate the phase φ in U | ψ⟩ = e^(2πiφ) | ψ⟩ with quantum phase estimation. Returns Result<PhaseEstimatorProblem, QuantumError>; run the Ok value with QuantumPhaseEstimator.estimate. |
Example:
open FSharp.Azure.Quantum.Algorithms.QPE
open FSharp.Azure.Quantum.QuantumPhaseEstimator
let qpeProblem = phaseEstimator {
unitary TGate
precision 8
targetQubits 1
shots 1024
}
match qpeProblem |> Result.bind estimate with
| Ok result -> printfn "Phase: %.6f (expected 0.125)" result.Phase
| Error err -> printfn "Error: %s" err.Message
Custom Operations:
unitary- Unitary operator:TGate,SGate,PhaseGate theta,RotationZ theta(default:TGate)precision- Counting qubits, i.e. bits of φ (1 to 30; default 8; the circuit must fit the backend)-
targetQubits- Qubits for the eigenvectorψ⟩ (1 to 10; default 1). Precision + target qubits must not exceed 25 -
eigenstate- Initial eigenvectorψ⟩ as a StateVector. When it is not set, the target qubit is prepared in1⟩ for the single-qubit gates TGate,SGate,PhaseGateandRotationZ(soTGategives φ = 1/8,PhaseGate θgives θ/2π andRotationZ θgives θ/4π) applySwaps/swaps- Apply the final bit-reversal SWAPs in the circuit (default: false, the bit order is fixed classically)exactness-Exact(default) orApproximate epsilonbackend- Quantum backend (default: LocalBackend)shots- Measurement shots; the estimate is the most frequent outcome. Default: 1024 on LocalBackend, 2048 on any other backend
Notes:
- Higher
precisiongives a finer phase estimate; moreshotsmakes the most frequent outcome more reliable. - QPE is also used inside period finding and HHL.
8. quantumArithmetic
Module: FSharp.Azure.Quantum.QuantumArithmeticOps
Purpose: Run arithmetic (addition, multiplication, modular operations) as quantum circuits. Returns Result<ArithmeticOperation, QuantumError>; run the Ok value with QuantumArithmeticOps.execute.
Example:
open FSharp.Azure.Quantum.QuantumArithmeticOps
let addition = quantumArithmetic {
operands 42 17
operation Add
qubits 8
shots 100
}
match addition |> Result.bind execute with
| Ok result -> printfn "42 + 17 = %d" result.Value
| Error err -> printfn "Error: %s" err.Message
Custom Operations:
operands a b- Set both operandsoperandA- Set the first operandoperandB- Set the second operand (the exponent forModularExponentiate)-
operation-Add(default)MultiplyModularAddModularMultiplyModularExponentiate modulus- Modulus (required for the modular operations; operands must be smaller than it forModularAddandModularMultiply)qubits- Register size in qubits (default 8, minimum 2); modular operations use extra ancilla qubits (ModularAddn + 2,ModularMultiply2n + 3,ModularExponentiate2n + 5), and the total must stay within the simulator’s practical circuit width (20 qubits by default; theFSAQ_MAX_CIRCUIT_QUBITSenvironment variable raises it, up to the memory-based limit)exponent- Same asoperandBbackend- Quantum backend (default: LocalBackend)shots- Measurement shots used to read the result register (default: 100)
Notes: the result is deterministic on a noiseless simulator; standalone quantum arithmetic is slower than CPU arithmetic and is mainly a building block (for example for Shor’s algorithm).
9. quantumTreeSearch<’T>
Module: FSharp.Azure.Quantum.QuantumTreeSearch
Purpose: Search game trees and decision trees with Grover search. Returns a TreeSearchProblem<'T> (validated; invalid problems throw). Solve it with QuantumTreeSearch.solve.
Example:
open FSharp.Azure.Quantum.QuantumTreeSearch
// Toy game: the state is a running total, each move adds 1..4
let evaluateTotal (total: int) = float (total % 7)
let legalMoves (total: int) = [ for step in 1 .. 4 -> total + step ]
let treeSearch = quantumTreeSearch<int> {
initialState 0
maxDepth 2
branchingFactor 4
evaluateWith evaluateTotal
generateMovesWith legalMoves
topPercentile 0.2
shots 100
}
match QuantumTreeSearch.solve treeSearch with
| Ok solution -> printfn "Best move: %d (score %.3f)" solution.BestMove solution.Score
| Error err -> printfn "Error: %s" err.Message
Custom Operations:
initialState- Starting state (required)maxDepth- Depth to explore (at least 1; default 3)branchingFactor- Moves per position (at least 2; default 16). The tree needs maxDepth × ⌈log₂(branchingFactor)⌉ qubits, up to what the backend runsevaluateWith- Evaluation function'T -> float(higher = better)generateMovesWith- Move generator'T -> 'T listtopPercentile- Fraction of best paths to amplify, in (0.0, 1.0] (default 0.2)backend- Quantum backend (default: LocalBackend)shots- Measurements (default: 50 on LocalBackend, 250 on other backends)solutionThreshold- Minimum fraction of shots for a state to count as a solution (default: 5%)successThreshold- Minimum total probability for the search to succeed (default: 50% on LocalBackend, 60% on other backends)maxPaths- Limit on the number of paths searched (default: full tree)limitSearchSpace-truesetsmaxPathsto a recommended limit for the currentmaxDepthandbranchingFactor, so put it after those twomaxIterations- Stored, but the current solver does not pass it on: Grover iterations are always calculated from the search space sizeonProgress- Progress reporter
Notes: the oracle evaluates your evaluation function; on the local simulator every path is evaluated, so the local run gives no speedup over classical search.
10. linearSystemSolver
Module: FSharp.Azure.Quantum.QuantumLinearSystemSolver
Purpose: Solve Ax = b with the HHL algorithm. Returns Result<LinearSystemProblem, QuantumError>; solve the Ok value with QuantumLinearSystemSolver.solve.
Example:
open FSharp.Azure.Quantum.QuantumLinearSystemSolver
let linearProblem = linearSystemSolver {
matrix [ [ 2.0; 0.0 ]; [ 0.0; 1.0 ] ]
vector [ 1.0; 1.0 ]
eigenvalueQubits 4
}
match linearProblem |> Result.bind QuantumLinearSystemSolver.solve with
| Ok solution -> printfn "Success probability: %.4f" solution.SuccessProbability
| Error err -> printfn "Error: %s" err.Message
Custom Operations:
matrix- Hermitian matrix A as rows (float list list); throws if it is not square or not HermitiandiagonalMatrix- A diagonal matrix from its eigenvaluesvector- Right-hand side b (normalized internally)eigenvalueQubits/precision- Qubits for eigenvalue estimation (default 4)inversionMethod-ExactRotation c(defaultExactRotation 1.0),LinearApproximation corPiecewiseLinear segmentsminEigenvalue- Eigenvalues below this are treated as zero (default 1e-6)postSelection- Post-select on the ancilla qubit (default true)backend- Quantum backend (default: LocalBackend)shots- Accepted but not used: the solver reads the solution and its success probability from the state vector exactly
11. resource<’T>
Module: FSharp.Azure.Quantum.TaskScheduling.Builders (also re-exported from FSharp.Azure.Quantum)
Purpose: Define a resource for task scheduling. Returns a Resource<'T>.
Example:
open FSharp.Azure.Quantum.TaskScheduling
let cpu = resource<string> {
resourceId "CPU"
capacity 4.0
costPerUnit 10.0
availableWindow 0.0 100.0
}
Custom Operations:
resourceId- Unique identifier (required)capacity- Capacity available (required)costPerUnit- Cost per unit per time unitavailableWindow start finish- Time window when the resource is available
The crew id capacity costPerUnit function is a shortcut for a Resource<string>.
12. scheduledTask<’T>
Module: FSharp.Azure.Quantum.TaskScheduling.Builders (also re-exported from FSharp.Azure.Quantum)
Purpose: Define a task for scheduling. Returns a ScheduledTask<'T>. Durations and times are TimeSpan values; build them with minutes, hours or days.
Example:
let task1 = scheduledTask<string> {
taskId "Task1"
duration (hours 2.0)
requires "CPU" 2.0
priority 1.0
deadline (hours 8.0)
}
let task2 = scheduledTask<string> {
taskId "Task2"
duration (minutes 30.0)
after "Task1"
}
Custom Operations:
taskId- Unique identifierduration- Task duration (TimeSpan)after- Must start after the named task finishesafterMultiple- Must start after all the named tasks finishrequires resourceId quantity- Resource requirementpriority- Priority for tie-breaking (higher = scheduled first)deadline- Latest completion time (TimeSpanfrom schedule start)earliestStart- Earliest start time (TimeSpanfrom schedule start)
13. scheduling<’TTask, ‘TResource>
Module: FSharp.Azure.Quantum.TaskScheduling.Builders (also re-exported from FSharp.Azure.Quantum)
Purpose: Define a complete scheduling problem. Returns a SchedulingProblem<'TTask, 'TResource>; solve it with solveQuantumAsync backend problem cancellationToken (returns Task<QuantumResult<Solution>>).
Example:
let schedulingProblem = scheduling<string, string> {
tasks [task1; task2]
resources [cpu]
objective MinimizeMakespan
timeHorizon (hours 12.0)
}
task {
match! solveQuantumAsync localBackend schedulingProblem CancellationToken.None with
| Ok solution -> printfn "Makespan: %O" solution.Makespan
| Error err -> printfn "Error: %s" err.Message
}
Custom Operations:
tasks- Tasks to schedule (dependencies declared withafterare picked up here)resources- Available resources-
objective-MinimizeMakespan(default)MinimizeCostMaximizeResourceUtilizationMinimizeLateness timeHorizon- Total time available (TimeSpan; default 1000 minutes)
14. constraintScheduler
Module: FSharp.Azure.Quantum.Business.ConstraintScheduler
Purpose: Assign tasks to resources under hard constraints (conflicts, required resources, precedence) and weighted preferences. Solves when evaluated and returns Task<QuantumResult<SchedulingResult>>.
Example:
open FSharp.Azure.Quantum.Business.ConstraintScheduler
let shiftPlan = constraintScheduler {
tasks ["Morning"; "Evening"]
resource "Alice" 20.0
resource "Bob" 25.0
conflict "Morning" "Evening"
prefer "Morning" "Alice" 1.0
optimizeFor MinimizeCost
}
task {
match! shiftPlan with
| Ok result -> printfn "%s" result.Message
| Error err -> printfn "Error: %s" err.Message
}
Custom Operations:
task/tasks- Add one task / several tasks by IDresource id cost- Add a resource with a costresourceWithCapacity id cost capacity- Add a resource with a limit on concurrent tasksconflict task1 task2- The two tasks must not share a resourcerequire task resource- The task must use the resourceprecedence before after- Ordering constraintprefer task resource weight- Soft preference-
optimizeFor-MinimizeCostMaximizeSatisfactionBalanced(default) maxBudget- Budget limitbackend- Quantum backend (default: LocalBackend)shots- Measurement shots (default: 1000)useGrover/useQaoa- Force the algorithm (default: chosen automatically)
15. anomalyDetection
Module: FSharp.Azure.Quantum.Business.AnomalyDetector
Purpose: Detect outliers with a quantum-kernel detector trained on normal examples only. Trains when evaluated and returns Task<QuantumResult<Detector>>.
Example:
open FSharp.Azure.Quantum.Business
open FSharp.Azure.Quantum.Business.AnomalyDetector
let normalTransactions : float[][] =
[| [| 0.10; 0.20 |]; [| 0.15; 0.22 |]; [| 0.12; 0.18 |]; [| 0.11; 0.21 |] |]
let suspiciousTransaction = [| 0.90; 0.95 |]
task {
let! detector = anomalyDetection {
trainOnNormalData normalTransactions
sensitivity High
contaminationRate 0.1
shots 1000
}
match detector with
| Ok model ->
match! AnomalyDetector.checkAsync suspiciousTransaction model CancellationToken.None with
| Ok result when result.IsAnomaly -> printfn "Anomaly detected. Score: %.2f" result.AnomalyScore
| Ok _ -> printfn "Looks normal"
| Error err -> printfn "Check failed: %s" err.Message
| Error err -> printfn "Training failed: %s" err.Message
}
Custom Operations:
trainOnNormalData- Training data (float[][], normal examples only)-
sensitivity-LowMedium(default)HighVeryHigh contaminationRate- Expected fraction of anomalies in the training data, 0.0 to 0.5 (default: 0.05)backend- Quantum backend (default: LocalBackend)shots- Measurement shots (default: 1000)verbose- Verbose logging (default: false)saveModelTo- Path to save the trained detectornote- Note stored with the modelprogressReporter- Progress reporter (default: none)cancellationToken- Cancellation token (default: none)
Other functions: AnomalyDetector.checkBatchAsync, explain, save, load.
Use Cases: fraud detection, security monitoring, quality control, system monitoring.
16. autoML
Module: FSharp.Azure.Quantum.Business.AutoML
Purpose: Try several model types, architectures and hyperparameters and return the best model. Runs the search when evaluated and returns Task<QuantumResult<AutoMLResult>>.
Example:
open FSharp.Azure.Quantum.Business.AutoML
let features : float[][] =
[| [| 0.1; 0.2 |]; [| 0.9; 0.8 |]; [| 0.2; 0.1 |]; [| 0.8; 0.9 |]; [| 0.15; 0.25 |]; [| 0.85; 0.75 |] |]
let labels = [| 0.0; 1.0; 0.0; 1.0; 0.0; 1.0 |]
let autoMLResult = autoML {
trainWith features labels
// Search space
tryBinaryClassification true
tryRegression false
tryAnomalyDetection false
tryArchitectures [Quantum; Hybrid]
// Search budget
maxTrials 10
maxTimeMinutes 10
verbose true
}
task {
match! autoMLResult with
| Ok best ->
printfn "Best model: %s (score %.2f)" best.BestModelType best.Score
match! AutoML.predictAsync [| 0.2; 0.2 |] best CancellationToken.None with
| Ok prediction -> printfn "Prediction: %A" prediction
| Error err -> printfn "Prediction failed: %s" err.Message
| Error err -> printfn "AutoML failed: %s" err.Message
}
Custom Operations:
trainWith features labels- Features (float[][]) and labels (float[])tryBinaryClassification- Include binary classification (default: true)tryMultiClass n- Include multi-class classification with n classes (default: detected from the labels)tryAnomalyDetection- Include anomaly detection (default: true)tryRegression- Include regression (default: true)trySimilaritySearch- Include similarity search (default: false)tryArchitectures- Architectures to try (default:[Quantum; Hybrid])maxTrials- Maximum number of trials (default: 20)maxTimeMinutes- Time limit in minutes (default: none)validationSplit- Fraction held out for validation (default: 0.2)backend- Quantum backend (default: LocalBackend)verbose- Verbose logging (default: false)saveModelTo- Path to save the best modelrandomSeed- Random seed for reproducibility (default: none)progressReporter- Progress reporter (default: none)cancellationToken- Cancellation token (default: none)
17. binaryClassification
Module: FSharp.Azure.Quantum.Business.BinaryClassifier
Purpose: Classify items into two categories. Trains when evaluated and returns Task<QuantumResult<Classifier>>.
Example:
open FSharp.Azure.Quantum.Business.BinaryClassifier
let trainFeatures = features
let trainLabels = [| 0; 1; 0; 1; 0; 1 |]
let classifier = binaryClassification {
trainWith trainFeatures trainLabels
architecture Quantum
learningRate 0.01
maxEpochs 100
shots 1000
}
task {
match! classifier with
| Ok model ->
match! BinaryClassifier.predictAsync [| 0.9; 0.9 |] model CancellationToken.None with
| Ok prediction when prediction.IsPositive -> printfn "Positive (confidence %.2f)" prediction.Confidence
| Ok _ -> printfn "Negative"
| Error err -> printfn "Prediction failed: %s" err.Message
| Error err -> printfn "Training failed: %s" err.Message
}
Custom Operations:
trainWith features labels- Features (float[][]) and labels (int[], 0 or 1)-
architecture-Quantum(default)HybridClassical learningRate- Learning rate (default: 0.01)maxEpochs- Maximum training epochs (default: 100)convergenceThreshold- Convergence threshold (default: 0.001)backend- Quantum backend (default: LocalBackend)shots- Measurement shots (default: 1000)verbose- Verbose logging (default: false)saveModelTo- Path to save the trained modelnote- Note stored with the modelprogressReporter- Progress reporter (default: none)cancellationToken- Cancellation token (default: none)
Other functions: BinaryClassifier.evaluateAsync, saveAsync, load.
Use Cases: fraud detection, spam filtering, churn prediction (yes/no), credit approval, pass/fail quality control.
18. predictiveModel
Module: FSharp.Azure.Quantum.Business.PredictiveModel
Purpose: Predict continuous values (regression) or categories (multi-class classification). Trains when evaluated and returns Task<QuantumResult<Model>>.
Example:
open FSharp.Azure.Quantum.Business.PredictiveModel
let customerFeatures = features
let revenueTargets = [| 10.0; 42.0; 12.0; 40.0; 11.0; 39.0 |]
let churnLabels = [| 0.0; 1.0; 0.0; 2.0; 0.0; 3.0 |] // 0=Stay, 1=Churn30, 2=Churn60, 3=Churn90
// Regression: predict revenue
let revenueModel = predictiveModel {
trainWith customerFeatures revenueTargets
problemType Regression
learningRate 0.01
maxEpochs 100
}
// Multi-class: predict churn timing
let churnModel = predictiveModel {
trainWith customerFeatures churnLabels
problemType (MultiClass 4)
architecture Quantum
shots 1000
}
task {
match! churnModel with
| Ok model ->
match! PredictiveModel.predictCategoryAsync [| 0.8; 0.9 |] model None None CancellationToken.None with
| Ok prediction when prediction.Category = 0 -> printfn "Customer will stay"
| Ok prediction -> printfn "Churn risk, category %d" prediction.Category
| Error err -> printfn "Prediction failed: %s" err.Message
| Error err -> printfn "Training failed: %s" err.Message
}
PredictiveModel.predictAsync features model backend shots cancellationToken returns a regression prediction; predictCategoryAsync returns a category. Pass None for the backend and shots to use the model’s own settings.
Custom Operations:
trainWith features targets- Features (float[][]) and targets (float[]; class indices for multi-class)-
problemType-Regression(default)MultiClass n -
architecture-Quantum(default)HybridClassical learningRate- Learning rate (default: 0.01)maxEpochs- Maximum training epochs (default: 100)convergenceThreshold- Convergence threshold (default: 0.001)backend- Quantum backend (default: LocalBackend)shots- Measurement shots (default: 1000)verbose- Verbose logging (default: false)saveModelTo- Path to save the trained modelnote- Note stored with the modelprogressReporter- Progress reporter (default: none)cancellationToken- Cancellation token (default: none)
Use Cases:
- Regression: revenue forecasting, demand prediction, customer lifetime value
- Multi-class: churn timing, customer segmentation, risk levels
19. similaritySearch<’T>
Module: FSharp.Azure.Quantum.Business.SimilaritySearch
Purpose: Index items by feature vectors and find similar items. Builds the index when evaluated and returns Task<QuantumResult<SearchIndex<'T>>>.
Example:
open FSharp.Azure.Quantum.Business.SimilaritySearch
type Product = { Sku: string }
let productCatalog : (Product * float[])[] =
[| { Sku = "A" }, [| 0.9; 0.1 |]
{ Sku = "B" }, [| 0.8; 0.2 |]
{ Sku = "C" }, [| 0.1; 0.9 |] |]
task {
let! finder = similaritySearch<Product> {
indexItems productCatalog
similarityMetric Cosine
threshold 0.7
shots 1000
}
match finder with
| Ok index ->
match! SimilaritySearch.findSimilarAsync { Sku = "query" } [| 0.85; 0.15 |] 2 index CancellationToken.None with
| Ok results ->
for m in results.Matches do
printfn " %s: %.2f similar" m.Item.Sku m.Similarity
| Error err -> printfn "Search failed: %s" err.Message
| Error err -> printfn "Indexing failed: %s" err.Message
}
Custom Operations:
indexItems- Items to index (('T * float[])[])-
similarityMetric-Cosine(default)EuclideanQuantumKernel threshold- Minimum similarity (default: 0.7)backend- Quantum backend (default: LocalBackend)shots- Measurement shots (default: 1000)verbose- Verbose logging (default: false)saveIndexTo- Path to save the indexnote- Note stored with the indexprogressReporter- Progress reporter (default: none)cancellationToken- Cancellation token (default: none)
Other functions: SimilaritySearch.findAllSimilarAsync, findDuplicatesAsync, cluster, save, load.
Use Cases: product recommendations, duplicate detection, content similarity, clustering.
20. optionPricing
Module: FSharp.Azure.Quantum.Business.OptionPricing
Purpose: Price European and Asian options with quantum Monte Carlo (amplitude estimation). Returns Task<QuantumResult<OptionPrice>>.
Example:
open System.Threading
open FSharp.Azure.Quantum.Business.OptionPricing
let pricing = optionPricing {
spotPrice 100.0
strikePrice 105.0
riskFreeRate 0.05
volatility 0.2
expiry 1.0
optionType EuropeanCall
qubits 6
iterations 5
shots 1000
backend localBackend
}
task {
match! pricing with
| Ok price -> printfn "Option price: %.4f (±%.4f)" price.Price price.ConfidenceInterval
| Error err -> printfn "Error: %s" err.Message
}
Custom Operations:
spotPrice- Spot price of the underlying (S₀; default 100.0)strikePrice- Strike price (K; default 100.0)riskFreeRate- Annual risk-free rate (r; default 0.05)volatility- Annual volatility (σ; default 0.2)expiry- Time to expiry in years (T; default 1.0)optionType-EuropeanCall(default),EuropeanPut,AsianCall n,AsianPut nqubits- Qubits for price discretization (2 to 10; default 6)iterations- Grover iterations for amplitude estimation (0 to 100; default 5)shots- Measurement shots (default 1000)backend- Quantum backend (required; without it the result is a validation error)cancellation_token- Cancellation token
Option Types:
EuropeanCall- max(S_T - K, 0)EuropeanPut- max(K - S_T, 0)AsianCall n- average-price call with n monitoring dates (priced with the geometric-average approximation)AsianPut n- average-price put with n monitoring dates (geometric-average approximation)
Notes:
- Uses Möttönen state preparation to encode the price distribution.
- The price is the maximum-likelihood amplitude estimate (
QuantumMonteCarlo.estimateBoundedExpectationAsync) over Grover powers 0, 1, 2, 4, … up toiterations, and the interval is 1.96 × its standard error. On a cloud backend every power is one whole-circuit job and its probability comes from the job’s counts; the method name then says “whole circuits sampled at N shots”. - In theory amplitude estimation needs O(1/ε) oracle queries for accuracy ε, where classical Monte Carlo needs O(1/ε²) samples. The local simulator does not show that advantage; the
Speedupfield of the result is the theoretical factor, not a measured one.
Greeks Calculation:
open System.Threading
// Option sensitivities (Delta, Gamma, Vega, Theta, Rho)
task {
match! OptionPricing.greeksEuropeanCallAsync 100.0 105.0 0.05 0.2 1.0 localBackend CancellationToken.None with
| Ok greeks -> printfn "Delta %.4f, Gamma %.4f, Vega %.4f" greeks.Delta greeks.Gamma greeks.Vega
| Error err -> printfn "Error: %s" err.Message
}
21. quantumRiskEngine
Module: FSharp.Azure.Quantum.Business (the builder is auto-opened)
Purpose: Portfolio risk metrics. Runs when evaluated and returns Task<QuantumResult<RiskReport>>.
Example:
let riskReport = quantumRiskEngine {
load_market_data "returns.csv"
set_confidence_level 0.99
calculate_metric ValueAtRisk
calculate_metric ConditionalVaR
use_amplitude_estimation true
backend localBackend
}
task {
match! riskReport with
| Ok report -> printfn "VaR: %A, CVaR: %A" report.VaR report.CVaR
| Error err -> printfn "Error: %s" err.Message
}
Custom Operations:
load_market_data- Path to a file of returns. Without it the engine uses generated sample returnsset_confidence_level- Confidence level (default 0.95)set_simulation_paths- Number of simulation paths (default 10000)use_amplitude_estimation- Use quantum amplitude estimation (default false); each metric is estimated withQuantumMonteCarlo.estimateBoundedExpectationAsync, as whole-circuit jobs on a cloud backenduse_error_mitigation- Enable error mitigation (default false)-
calculate_metric- Add a metric:ValueAtRiskConditionalVaRExpectedShortfallVolatility cancellation_token- Cancellation tokenqubits- Qubits for amplitude estimation (default 5)iterations- Grover iterations (default 2)shots- Measurement shots (default 100)backend- Quantum backend (default: LocalBackend)
22. drugDiscovery
Module: FSharp.Azure.Quantum.Business (the builder is auto-opened)
Purpose: Virtual screening of candidate molecules. Runs when evaluated and returns Task<QuantumResult<ScreeningResult>>.
Example:
let screening = drugDiscovery {
load_candidates_from_file "candidates.sdf"
use_method QuantumKernelSVM
use_feature_map ZZFeatureMap
set_batch_size 10
shots 100
}
task {
match! screening with
| Ok result -> printfn "%s (%d molecules)" result.Message result.MoleculesProcessed
| Error err -> printfn "Error: %s" err.Message
}
Custom Operations:
target_protein_from_pdb- Target protein from a PDB fileload_candidates_from_file- Candidate molecules from a fileload_candidates_from_provider/load_candidates_from_provider_async- Candidates from a dataset provider-
use_method-QuantumKernelSVM(default)VQCClassifierQAOADiverseSelection -
use_feature_map-ZZFeatureMap(default)PauliFeatureMapZFeatureMap set_batch_size- Batch size (default 10)shots- Measurement shots (default 100 for the classifiers, 1000 final shots forQAOADiverseSelection)backend- Quantum backend (required)vqc_layers- Layers forVQCClassifier(default 2)vqc_max_epochs- Epochs forVQCClassifier(default 50)selection_budget- Budget forQAOADiverseSelection(default 10.0): the largest number of molecules selected, each costing 1; at or above the batch size it does not binddiversity_weight- Diversity weight forQAOADiverseSelection(default 0.5)
23. topological
Module: FSharp.Azure.Quantum.Topological (topological is auto-opened; the operations are in TopologicalBuilder)
Purpose: Compose topological programs from anyon operations. topological backend { ... } builds a program; TopologicalBuilder.execute backend program runs it and returns Task<Result<_, QuantumError>>.
Example:
open FSharp.Azure.Quantum.Topological
let isingBackend = TopologicalUnifiedBackendFactory.createIsing 10
let program = topological isingBackend {
do! TopologicalBuilder.initialize AnyonSpecies.AnyonType.Ising 4
do! TopologicalBuilder.braid 0
do! TopologicalBuilder.braid 2
let! outcome = TopologicalBuilder.measure 0
return outcome
}
task {
match! TopologicalBuilder.execute isingBackend program with
| Ok particle -> printfn "Measured: %A" particle
| Error err -> printfn "Error: %s" err.Message
}
Builder functions (use with do! for operations and let! for values):
TopologicalBuilder.initialize anyonType count- Initialize anyonsTopologicalBuilder.braid index- Braid the anyons atindexandindex + 1TopologicalBuilder.measure index- Measure the fusion outcome atindex(use withlet!)TopologicalBuilder.braidSequence indices- Apply several braidsTopologicalBuilder.getState- Current quantum state (use withlet!)TopologicalBuilder.getResults- Measurement results so far (use withlet!)TopologicalBuilder.getLog- Execution log (use withlet!)TopologicalBuilder.getContext- Full context, for visualization (use withlet!)
Anyon types: AnyonSpecies.AnyonType.Ising (Majorana-based; braiding alone gives Clifford gates only) and AnyonSpecies.AnyonType.Fibonacci (braiding is universal).
Execution functions:
TopologicalBuilder.execute backend program- Run and return the resultTopologicalBuilder.executeWithContext backend program- Run and return the result with the final context
24. quantumChemistry
Module: FSharp.Azure.Quantum.QuantumChemistry.QuantumChemistryBuilder
Purpose: Ground state energy calculations with VQE, or with quantum phase estimation (groundStateMethod GroundStateMethod.QPE). The CE returns a ChemistryProblem and throws if molecule (or a molecule_from_* operation) or basis is missing, or ansatz is missing for VQE. solveAsync problem cancellationToken returns Task<Result<ChemistryResult, QuantumError>>.
Example:
open System.Threading
open FSharp.Azure.Quantum.QuantumChemistry.QuantumChemistryBuilder
// H2 at 0.74 Å bond length
let h2Problem = quantumChemistry {
molecule (h2 0.74)
basis "sto-3g"
ansatz UCCSD
}
task {
match! solveAsync h2Problem CancellationToken.None with
| Ok result -> printfn "Ground state energy: %.6f Ha" result.GroundStateEnergy
| Error err -> printfn "Error: %s" err.Message
}
The same molecule by quantum phase estimation (12 qubits, about 7 s on the local simulator):
open System.Threading
open FSharp.Azure.Quantum.QuantumChemistry
let h2Qpe = quantumChemistry {
molecule (h2 0.7414)
basis "sto-3g"
groundStateMethod GroundStateMethod.QPE
}
task {
match! solveAsync h2Qpe CancellationToken.None with
| Ok result ->
printfn "QPE energy: %.6f Ha (%A)" result.GroundStateEnergy result.Source
result.Notes |> List.iter (printfn " %s")
| Error err -> printfn "Error: %s" err.Message
}
Custom Operations:
molecule mol- Molecule instancemolecule_from_xyz path- Load the molecule from an XYZ file (read insolveAsync)molecule_from_fcidump path- Run VQE on an FCIDump file’s integrals (read insolveAsync; the molecule is a placeholder, since the file has no geometry)molecule_from_provider provider name- Load the molecule from a dataset providermolecule_from_name name- Load the molecule from the built-in molecule librarybasis basisSet- Basis set name (required)ansatz ansatzType-UCCSD,HEAorADAPT(required)optimizer name- Optimizer name (default “COBYLA”)maxIterations n- Maximum VQE iterations (default: 100)initialParameters params- Initial UCCSD amplitudes for a warm start (the count must match the ansatz)integralProvider provider- Molecular integrals for VQE (a PySCF/Psi4 wrapper,FciDumpIntegrals.fromFile, …)groundStateMethod method-GroundStateMethod.QPEruns quantum phase estimation of the Trotterised time evolution (QPE.runWithAsync QPE.defaultSettingsin the problem’s basis; noansatzneeded);VQE,Automaticor no method runs UCCSD-VQE
Current behaviour of solveAsync: it runs UCCSD-VQE on the local simulator, or quantum phase estimation with groundStateMethod GroundStateMethod.QPE (see Bring Your Own Hamiltonian for its design and accuracy). The integrals come from integralProvider, else from the molecule_from_fcidump file, else from VQE.runAsync’s own selection. That selection is integrals the library computes for molecules of H and He atoms, an Error for H2O and LiH, and the empirical prototype Hamiltonian otherwise. basis chooses the basis of the computed integrals. STO-3G and 6-31G are supported; any other basis is an Error. Integrals from a provider or an FCIDUMP file carry their own basis. The result’s Source says which integrals were used. The ansatz value and the optimizer name are stored in the problem (ansatz is required), but solveAsync does not use them yet: with integrals it runs UCCSD with its own BFGS optimizer. maxIterations and initialParameters are used. optimizer copies the iteration count at the point where it appears, so put maxIterations before optimizer.
Pre-built molecules:
let hydrogen = h2 0.74 // H2, bond length 0.74 Å
let water = h2o 0.96 104.5 // H2O, O-H 0.96 Å, angle 104.5°
let lithiumHydride = lih 1.6 // LiH, bond length 1.6 Å
Loading from files and the library:
let fromXyz = quantumChemistry {
molecule_from_xyz "caffeine.xyz"
basis "sto-3g"
ansatz UCCSD
}
let fromFciDump = quantumChemistry {
molecule_from_fcidump "h2o.fcidump"
basis "6-31g"
ansatz HEA
}
let fromLibrary = quantumChemistry {
molecule_from_name "benzene"
basis "sto-3g"
ansatz UCCSD
}
Result fields:
GroundStateEnergy- Ground state energy in HartreesOptimalParameters- Optimal VQE parameters foundIterations- Number of VQE iterations performedConvergence- Whether VQE converged within toleranceBondLengths- Bond lengths (e.g. “H-H” -> 0.74)DipoleMoment- Dipole moment, if computedSource- What produced the energy (EnergySource:ProviderIntegrals,ComputedSto3gIntegrals,Computed631gIntegrals,EmpiricalHamiltonian,QpeTrotterEvolution, …)Estimation- How the energy was estimated (EnergyEstimation); for QPE,PhaseEstimationwith the evolution time, shift, Trotter order and steps, counting qubits, bin width and every peak of the outcome distributionNotes- Caveats on the energy; for QPE, how strongly the Hartree-Fock state overlaps the reported eigenvalue and any other peaks
25. coverageOptimizer
Module: FSharp.Azure.Quantum.Business.CoverageOptimizer
Purpose: Set coverage: select the cheapest options that together cover every required element (shifts, facilities, service packages). Solves when evaluated and returns Task<QuantumResult<CoverageResult>>.
Example:
open FSharp.Azure.Quantum.Business.CoverageOptimizer
let coverage = coverageOptimizer {
universeSize 3
option "MorningShift" [0; 1] 25.0 // Covers slots 0,1 at cost 25
option "AfternoonShift" [1; 2] 20.0 // Covers slots 1,2 at cost 20
option "FullDay" [0; 1; 2] 40.0 // Covers all at cost 40
backend localBackend
}
task {
match! coverage with
| Ok r ->
printfn "Selected %d options, total cost: %.2f" r.SelectedOptions.Length r.TotalCost
printfn "Coverage: %d/%d elements" r.ElementsCovered r.TotalElements
| Error err -> printfn "Coverage optimization failed: %s" err.Message
}
Custom Operations:
element- Add an element index (grows the universe size if needed)universeSize- Set the number of elements directlyoption id coveredElements cost- Add an option (string,int list,float)backend- Quantum backend (default: LocalBackend)shots- Measurement shots (default: 1000)
Notes:
- Uses QAOA on a QUBO formulation of set cover.
- Element indices are 0-based and must be in [0, universeSize); costs must be non-negative.
26. resourcePairing
Module: FSharp.Azure.Quantum.Business.ResourcePairing
Purpose: 1:1 pairing of participants that maximizes total compatibility. Solves when evaluated and returns Task<QuantumResult<PairingResult>>.
Example:
open FSharp.Azure.Quantum.Business.ResourcePairing
let pairing = resourcePairing {
participant "Alice"
participant "Bob"
participant "Carol"
compatibility "Alice" "Bob" 0.9
compatibility "Alice" "Carol" 0.5
compatibility "Bob" "Carol" 0.7
backend localBackend
}
task {
match! pairing with
| Ok r ->
printfn "Found %d pairings, total score: %.2f" r.Pairings.Length r.TotalScore
for p in r.Pairings do
printfn " %s <-> %s (%.2f)" p.Participant1 p.Participant2 p.Weight
| Error err -> printfn "Resource pairing failed: %s" err.Message
}
Custom Operations:
participant- Add a participant by IDparticipants- Add several participants (string list)compatibility p1 p2 weight- Compatibility score between two participantsbackend- Quantum backend (default: LocalBackend)shots- Measurement shots (default: 1000)
Notes:
- Uses QAOA on a QUBO formulation of maximum weight matching.
- Needs at least 2 participants; weights must be non-negative; every participant in a compatibility must be declared.
27. packingOptimizer
Module: FSharp.Azure.Quantum.Business.PackingOptimizer
Purpose: Bin packing: assign items to bins so that as few bins as possible are used. Solves when evaluated and returns Task<QuantumResult<PackingResult>>.
Example:
open FSharp.Azure.Quantum.Business.PackingOptimizer
let packing = packingOptimizer {
containerCapacity 100.0
item "Crate-A" 45.0
item "Crate-B" 35.0
item "Crate-C" 25.0
item "Crate-D" 50.0
backend localBackend
}
task {
match! packing with
| Ok r ->
printfn "Packed %d items into %d bins" r.ItemsAssigned r.BinsUsed
for a in r.Assignments do
printfn " %s (size %.1f) -> Bin %d" a.Item.Id a.Item.Size a.BinIndex
| Error err -> printfn "Packing optimization failed: %s" err.Message
}
Custom Operations:
item id size- Add an itemcontainerCapacity- Capacity of every binbackend- Quantum backend (default: LocalBackend)shots- Measurement shots (default: 1000)
Notes:
- Uses QAOA on a QUBO formulation of bin packing: n·B item bits, B bin bits and K slack bits per bin (B = first-fit-decreasing bin count; the slack encodes “at most the capacity” and is absent when every used bin must be full). The example above takes 18 qubits.
- Item sizes must be positive and no larger than the bin capacity; at least one item is required. Sizes and capacity need a common decimal form of at most 6 places (they are rescaled to integers).
WasRepairedon the result istruewhen no measured sample was a valid packing and classical constraint repair produced the assignments;Samplingcounts the valid samples and the samples equal to the returned packing.
28. socialNetwork
Module: FSharp.Azure.Quantum.Business.SocialNetworkAnalyzer
Purpose: Find communities, a minimum monitor set, or pairings in a network of people. Solves when evaluated and returns Task<QuantumResult<SocialNetworkResult>>.
Example:
open FSharp.Azure.Quantum.Business.SocialNetworkAnalyzer
let analysis = socialNetwork {
people ["Alice"; "Bob"; "Carol"; "Dave"]
connections [ "Alice", "Bob"; "Bob", "Carol"; "Alice", "Carol"; "Carol", "Dave" ]
findLargestCommunity
}
task {
match! analysis with
| Ok result -> printfn "%s" result.Message
| Error err -> printfn "Error: %s" err.Message
}
Custom Operations:
person/people- Add one person / several peopleconnection p1 p2/connections pairs- Add connectionsfindCommunities size- Find communities of the given sizefindLargestCommunity- Find the largest communityfindMonitorSet- Smallest set of people covering all connectionsfindPairings- Pair people along connectionsbackend- Quantum backend (default: LocalBackend)useGrover/useQaoa- Force the algorithmshots- Measurement shots
Common Patterns
For Loops in CEs
Custom operations cannot see a for loop variable, so a loop body must produce a value of the builder’s state type with yield!. Custom operations must also come before the first yield!, for or if in the expression (otherwise error FS3086). The circuit and graph coloring builders support this:
// Circuit: Hadamard on every qubit
let superposition = circuit {
qubits 5
for q in [0..4] do
yield! singleGate (Gate.H q)
}
// Graph coloring: add nodes from data
let fromData = graphColoring {
colors ["Red"; "Green"; "Blue"]
for (id, conflicts) in [ "A", ["B"]; "B", ["A"; "C"]; "C", ["B"] ] do
yield! singleNode (coloredNode { nodeId id; conflictsWith conflicts })
}
The other builders take lists instead of loops: satisfies can be used several times in constraintSolver, and list-valued operations such as nodes, tasks, participants or people add many items at once.
Backend Configuration
Every quantum builder defaults to the local simulator when backend is not set (except optionPricing, which requires it):
// Default: LocalBackend (simulation)
let onSimulator = periodFinder {
number 15
precision 8
}
// Explicit backend: any IQuantumBackend, for example a cloud backend
// created with CloudBackends.CloudBackendFactory (see Backend Switching)
let onBackend (qpu: IQuantumBackend) = periodFinder {
number 15
precision 8
backend qpu
}
Default Shots and Thresholds
| Builder | shots default |
Other defaults |
|---|---|---|
constraintSolver, patternMatcher |
1000 | Grover iterations calculated |
phaseEstimator |
1024 on LocalBackend, 2048 on other backends | |
quantumTreeSearch |
50 on LocalBackend, 250 on other backends | solutionThreshold 5%; successThreshold 50% local, 60% other |
quantumArithmetic |
100 | |
periodFinder, linearSystemSolver |
not used | |
ML builders, optionPricing, coverageOptimizer, resourcePairing, packingOptimizer, constraintScheduler |
1000 | |
quantumRiskEngine, drugDiscovery |
100 |
Chaining Results: quantumResult and quantumResultTask
quantumResult { } (in FSharp.Azure.Quantum.Core) chains steps that return QuantumResult<'T>: each let! continues with the Ok value and the first Error ends the computation. quantumResultTask { } is its asynchronous twin and yields a Task<QuantumResult<'T>>:
let!,do!andreturn!take aTask<QuantumResult<'T>>(the...Asyncfunctions and the run-on-evaluation builders above,optionPricingincluded), anAsync<QuantumResult<'T>>, a plainQuantumResult<'T>(the validated problem builders), or aTask<'T>/Async<'T>, whose value is bound asOk.- The first
Errorshort-circuits the rest of the block. - An exception faults the task unless a
try ... withinside the block catches it; the handler returns an error withreturn! Error ....
open System.Threading.Tasks
let bestPrediction (ct: CancellationToken) : Task<QuantumResult<AutoML.Prediction>> =
quantumResultTask {
let! best = autoML {
trainWith features labels
maxTrials 5
cancellationToken ct
}
return! AutoML.predictAsync [| 0.2; 0.2 |] best ct
}
Inside the ML builders, cancellationToken is the name of a custom operation, so the token parameter above is called ct. See the QuantumResult Builder Guide for more.
Progress Reporting and Cancellation
The ML builders (autoML, binaryClassification, predictiveModel, anomalyDetection, similaritySearch) accept a progress reporter and a cancellation token. constraintSolver and quantumTreeSearch accept a reporter through onProgress.
open System.Threading
open FSharp.Azure.Quantum.Core.Progress
// Example 1: Console progress reporter
let consoleReporter = createConsoleReporter (Some true) None
let result1 = autoML {
trainWith features labels
maxTrials 20
progressReporter consoleReporter
}
// Example 2: Event-based progress with cancellation
let cts = new CancellationTokenSource()
let reporter = createEventReporter ()
reporter.SetCancellationToken(cts.Token)
reporter.ProgressChanged.Add(fun event ->
match event with
| TrialCompleted(id, score, elapsed) ->
printfn $"Trial {id}: {score * 100.0:F1}%% in {elapsed:F1}s"
if score > 0.95 then cts.Cancel() // Early exit
| _ -> ())
let result2 = autoML {
trainWith features labels
maxTrials 50
progressReporter (reporter :> IProgressReporter)
cancellationToken cts.Token
}
// Example 3: Timeout-based cancellation
let ctsTimeout = new CancellationTokenSource()
ctsTimeout.CancelAfter(TimeSpan.FromMinutes 5.0)
let result3 = binaryClassification {
trainWith trainFeatures trainLabels
maxEpochs 1000
cancellationToken ctsTimeout.Token
}
Progress Event Types:
TrialStarted(trialId, totalTrials, modelType)- AutoML trial startingTrialCompleted(trialId, score, elapsedSeconds)- AutoML trial completedTrialFailed(trialId, error)- AutoML trial failedProgressUpdate(percentComplete, message)- General progress updatePhaseChanged(phaseName, message)- Algorithm phase changed (messageis astring option)IterationUpdate(current, total, currentBest)- Iteration progress (currentBestis afloat option)BackendExecutionStarted(backendName, numShots)/BackendExecutionCompleted(backendName, elapsedSeconds)- Backend calls
Built-in Reporters:
createConsoleReporter verbose cancellationToken- Console output (both arguments are options)createEventReporter ()- RaisesProgressChangedevents, for UI integrationcreateNullReporter ()- Does nothingcreateAggregatingReporter reporters- Forwards to several reporters
Use Cases: monitoring long AutoML searches, progress bars in a UI, logging, timeouts, stopping early once a result is good enough.
IntelliSense Tips
If IntelliSense Doesn’t Show Operations
1. Type the CE name and open the braces first:
let problem = periodFinder {
// Now press Ctrl+Space to see operations
number 21
}
2. Use the CE instance name, not the builder type:
- ✅
periodFinder { }- Correct - ❌
PeriodFinderBuilder { }- Wrong
3. For generic CEs, give the type parameter:
let search = patternMatcher<Config> {
// The type parameter helps IntelliSense
searchSpace allConfigs
matchPattern (fun cfg -> cfg.Cost < 50.0)
}
4. Use this reference table when IntelliSense fails.