Skip to the content.

Business Problem Builders

High-level APIs for common business applications powered by quantum algorithms and quantum machine learning.

Overview

Business Problem Builders provide domain-specific APIs that hide quantum complexity while delivering quantum-enhanced solutions for real-world business problems. These builders leverage:

Target Audience: Business analysts, data scientists, application developers who want quantum benefits without quantum expertise.

Available Builders

1. AutoML - Automated Machine Learning

2. Binary Classification - Fraud Detection, Spam Filtering

3. Anomaly Detection - Security Threats, Quality Control

4. Predictive Modeling - Churn Prediction, Demand Forecasting

6. Quantum Drug Discovery - Virtual Screening, Compound Selection

7. Social Network Analyzer - Community Detection, Influence Maximization

8. Constraint Scheduler - Constraint-Based Scheduling Optimization

9. Coverage Optimizer - Set Coverage Optimization

10. Resource Pairing - Resource Pairing/Matching Optimization

11. Packing Optimizer - Bin Packing Optimization


AutoML - Automated Machine Learning

What is AutoML?

AutoML automatically selects the best machine learning approach for your data:

What AutoML Does:

  1. Analyzes your dataset characteristics
  2. Tries multiple approaches (binary classification, regression, anomaly detection)
  3. Tests quantum and classical architectures
  4. Tunes hyperparameters automatically
  5. Returns best model with performance metrics

When to Use:

API Reference

open FSharp.Azure.Quantum.Business
open FSharp.Azure.Quantum.Business.AutoML

// Minimal usage - "zero config ML"
let result = autoML {
    trainWith features labels
}

match result with
| Ok automlResult ->
    printfn "Best Model: %s" automlResult.BestModelType
    printfn "Architecture: %A" automlResult.BestArchitecture
    printfn "Validation Score: %.2f%%" (automlResult.Score * 100.0)
    printfn "Training Time: %.1fs" automlResult.TotalSearchTime.TotalSeconds
    
    // Use best model for predictions
    let prediction = AutoML.predict automlResult.BestModel newData
    
| Error err -> eprintfn "AutoML failed: %A" err

Configuration Options

// Advanced configuration
let result = autoML {
    trainWith trainFeatures trainLabels
    
    // Search space
    tryArchitectures [Quantum; Classical; Hybrid]
    tryTaskTypes [BinaryClassification; MultiClass; Regression; AnomalyDetection]
    
    // Resource limits
    maxTrials 50
    maxTime (TimeSpan.FromMinutes 10.0)
    
    // Validation
    validationSplit 0.2
    metric Accuracy  // or Precision, Recall, F1Score, RMSE
    
    // Optimization
    enableEarlyStop true
    patience 5
}

AutoML Search Process

1. Data Analysis

2. Architecture Search

3. Hyperparameter Tuning

4. Validation

Working Example

See complete example: examples/AutoML/QuickPrototyping.fsx


Binary Classification

What is Binary Classification?

Classify data into two categories (e.g., fraud/legitimate, spam/ham, churn/retain).

Business Applications:

API Reference

open FSharp.Azure.Quantum.Business.BinaryClassifier

// Minimal configuration - smart defaults
let result = binaryClassification {
    trainWith trainFeatures trainLabels
}

match result with
| Ok classifier ->
    printfn "Training accuracy: %.2f%%" (classifier.Metadata.TrainingAccuracy * 100.0)
    
    // Classify new data
    let newTransaction = [| 600.0; 14.5; 7.0; 80.0; 12.0 |]
    
    match BinaryClassifier.predict classifier newTransaction with
    | Ok prediction ->
        printfn "Class: %d (confidence: %.2f%%)" 
            prediction.Class 
            (prediction.Confidence * 100.0)
    | Error err -> eprintfn "Error: %s" err.Message
    
| Error err -> eprintfn "Training failed: %s" err.Message

Configuration Options

// Advanced configuration
let result = binaryClassification {
    trainWith trainFeatures trainLabels
    
    // Architecture selection
    architecture Quantum  // or Classical, Hybrid, AutoSelect
    
    // Quantum-specific (when architecture = Quantum)
    featureMap (ZZFeatureMap 2)
    variationalForm (RealAmplitudes 2)
    
    // Training configuration
    learningRate 0.1
    maxEpochs 50
    convergenceThreshold 0.001
    shots 1000
    
    // Optimizer
    optimizer Adam  // or SGD
    
    // Validation
    validationSplit 0.2
    
    // Class imbalance handling
    classWeights [| 1.0; 3.0 |]  // Penalize misclassifying class 1 more
}

Example: Fraud Detection

// Feature engineering for credit card transactions
// Features: [amount, time_of_day, merchant_category, distance_from_home, frequency]

let normalTransactions = [|
    [| 50.0; 12.0; 2.0; 5.0; 3.0 |]   // Small, daytime, grocery, nearby
    [| 75.0; 18.0; 3.0; 8.0; 2.0 |]   // Medium, evening, gas, nearby
    // ... 40 normal transactions
|]

let fraudulentTransactions = [|
    [| 800.0; 3.0; 7.0; 150.0; 15.0 |]  // Large, late night, unusual, far away
    [| 600.0; 2.0; 9.0; 200.0; 20.0 |]  // Large, very late, unusual, very far
    // ... 10 fraudulent transactions
|]

let trainX = Array.append normalTransactions fraudulentTransactions
let trainY = Array.append (Array.create 40 0) (Array.create 10 1)

// Train fraud detector
let result = binaryClassification {
    trainWith trainX trainY
    architecture Quantum
    classWeights [| 1.0; 5.0 |]  // False negatives (missing fraud) are costly!
}

match result with
| Ok model ->
    // Deploy model for real-time fraud scoring
    let scoreTransaction transaction =
        match BinaryClassifier.predict model transaction with
        | Ok pred when pred.Class = 1 && pred.Confidence > 0.8 ->
            "BLOCK - High fraud risk"
        | Ok pred when pred.Class = 1 && pred.Confidence > 0.5 ->
            "REVIEW - Medium fraud risk"
        | Ok pred -> 
            "APPROVE - Low fraud risk"
        | Error _ -> 
            "ERROR - Manual review required"
    
    // Score new transaction
    let newTx = [| 650.0; 2.5; 8.0; 180.0; 18.0 |]
    printfn "%s" (scoreTransaction newTx)
    
| Error err -> eprintfn "Training failed: %s" err.Message

Working Example

See complete example: examples/BinaryClassification/FraudDetection.fsx


Anomaly Detection

What is Anomaly Detection?

Identify unusual patterns that don’t conform to expected behavior.

Business Applications:

API Reference

open FSharp.Azure.Quantum.Business.AnomalyDetector

// Train on normal data only
let result = anomalyDetection {
    trainWith normalData  // Only normal samples, no labels
    
    // Sensitivity (how strict is "anomaly"?)
    threshold 0.05  // 5% most unusual are anomalies
    
    // Feature engineering
    features ["cpu_usage"; "memory"; "network_io"; "disk_io"]
    
    // Detection method
    method QuantumKernel  // or Classical, Hybrid
}

match result with
| Ok detector ->
    // Check new data point
    let newSample = [| 95.0; 8000.0; 15000.0; 200.0 |]  // High CPU usage
    
    match AnomalyDetector.detect detector newSample with
    | Ok result ->
        if result.IsAnomaly then
            printfn "ANOMALY DETECTED"
            printfn "  Anomaly score: %.4f" result.AnomalyScore
            printfn "  Distance from normal: %.2f sigma" result.DeviationSigma
        else
            printfn "Normal behavior (score: %.4f)" result.AnomalyScore
    | Error err -> eprintfn "Detection error: %s" err.Message
    
| Error err -> eprintfn "Training failed: %s" err.Message

Configuration Options

let result = anomalyDetection {
    trainWith normalData
    
    // Detection threshold
    threshold 0.05           // Top 5% unusual = anomaly
    contamination 0.02       // Expected % of anomalies in training data
    
    // Method selection
    method QuantumKernel     // Quantum feature space for similarity
    
    // Quantum configuration
    featureMap (ZZFeatureMap 2)
    shots 1000
    
    // Sensitivity tuning
    sensitivity High         // Low, Medium, High, VeryHigh
}

Example: Network Intrusion Detection

// Monitor server metrics for unusual activity
let normalServerMetrics = [|
    [| 45.0; 4000.0; 5000.0; 100.0 |]   // Normal: CPU, Memory, Network, Disk
    [| 50.0; 4200.0; 5500.0; 110.0 |]
    [| 42.0; 3900.0; 4800.0; 95.0 |]
    // ... 100 normal operation samples
|]

let result = anomalyDetection {
    trainWith normalServerMetrics
    features ["cpu_percent"; "memory_mb"; "network_kb_s"; "disk_io_ops"]
    threshold 0.05  // Top 5% unusual
    method QuantumKernel
}

match result with
| Ok detector ->
    // Real-time monitoring
    let monitorMetrics currentMetrics =
        match AnomalyDetector.detect detector currentMetrics with
        | Ok result when result.IsAnomaly && result.AnomalyScore > 0.9 ->
            // Critical anomaly
            sendAlert "CRITICAL: Possible intrusion detected"
        | Ok result when result.IsAnomaly ->
            // Minor anomaly
            logWarning $"Unusual activity (score: {result.AnomalyScore})"
        | Ok _ ->
            // Normal
            ()
        | Error err ->
            logError err.Message
    
    // Check current server state
    let current = [| 98.0; 7800.0; 25000.0; 500.0 |]  // Suspicious!
    monitorMetrics current
    
| Error err -> eprintfn "Setup failed: %s" err.Message

Working Example

See complete example: examples/AnomalyDetection/


Predictive Modeling

What is Predictive Modeling?

Forecast future outcomes based on historical patterns.

Business Applications:

API Reference

open FSharp.Azure.Quantum.Business.PredictiveModel

// Train predictive model
let result = predictiveModel {
    trainWith historicalData historicalOutcomes
    
    // Model type
    modelType Regression  // or Classification
    
    // Features
    features ["tenure_months"; "monthly_spend"; "support_calls"; "satisfaction"]
    target "will_churn"
    
    // Architecture
    architecture Hybrid  // Quantum features + classical regression
}

match result with
| Ok model ->
    printfn "Model R² score: %.2f" model.Metrics.RSquared
    printfn "Mean error: %.2f" model.Metrics.MAE
    
    // Predict for new customer
    let newCustomer = [| 6.0; 45.0; 3.0; 6.5 |]
    
    match PredictiveModel.predict model newCustomer with
    | Ok prediction ->
        printfn "Churn probability: %.2f%%" (prediction.Value * 100.0)
        printfn "Confidence interval: [%.2f, %.2f]" 
            prediction.LowerBound 
            prediction.UpperBound
    | Error err -> eprintfn "Error: %s" err.Message
    
| Error err -> eprintfn "Training failed: %s" err.Message

Configuration Options

let result = predictiveModel {
    trainWith trainX trainY
    
    // Model configuration
    modelType Regression
    architecture Quantum
    
    // Feature engineering
    features featureNames
    target targetName
    normalizeFeatures true
    
    // Training
    learningRate 0.1
    maxEpochs 100
    validationSplit 0.2
    
    // Regularization (prevent overfitting)
    l2Penalty 0.01
    dropoutRate 0.1
}

Example: Customer Churn Prediction

// Historical customer data
// Features: [tenure_months, monthly_spend, support_calls, usage_hours, satisfaction]
let customerHistory = [|
    [| 24.0; 75.0; 1.0; 20.0; 8.5 |]; 0.0  // Stayed
    [| 6.0; 45.0; 5.0; 5.0; 3.0 |]; 1.0    // Churned
    [| 36.0; 120.0; 0.0; 30.0; 9.0 |]; 0.0 // Stayed
    // ... 1000 historical customers
|]

let trainX = customerHistory |> Array.map fst
let trainY = customerHistory |> Array.map snd

let result = predictiveModel {
    trainWith trainX trainY
    
    features [
        "tenure_months"
        "monthly_spend"
        "support_calls"
        "usage_hours"
        "satisfaction_score"
    ]
    target "will_churn"
    
    modelType BinaryClassification
    architecture Quantum
    
    // Business constraint: False negatives costly (missed churn)
    classWeights [| 1.0; 3.0 |]
}

match result with
| Ok model ->
    // Churn risk scoring for current customers
    let scoreChurnRisk customer =
        match PredictiveModel.predict model customer with
        | Ok pred when pred.Value > 0.7 ->
            "HIGH RISK - Immediate retention campaign"
        | Ok pred when pred.Value > 0.4 ->
            "MEDIUM RISK - Monitor and engage"
        | Ok pred ->
            "LOW RISK - Routine engagement"
        | Error _ ->
            "ERROR - Manual review"
    
    // Score at-risk customer
    let atRiskCustomer = [| 8.0; 40.0; 4.0; 8.0; 4.5 |]
    printfn "%s" (scoreChurnRisk atRiskCustomer)
    
| Error err -> eprintfn "Model training failed: %s" err.Message

Working Example

See complete example: examples/PredictiveModeling/CustomerChurnPrediction.fsx


Find items similar to a query item based on features.

Business Applications:

API Reference

open FSharp.Azure.Quantum.Business.SimilaritySearch

// Build similarity index
let result = similaritySearch {
    indexItems catalogItems
    
    // Features to compare
    features ["category"; "price"; "rating"; "description_embedding"]
    
    // Similarity metric
    similarityMetric QuantumKernel  // or Cosine, Euclidean
    
    // Index optimization
    buildIndex true  // Pre-compute for fast queries
}

match result with
| Ok searchIndex ->
    // Find similar products
    let queryItem = [| 2.0; 49.99; 4.5; embeddingVector |]
    
    match SimilaritySearch.findSimilar searchIndex queryItem 5 with  // Top 5
    | Ok results ->
        printfn "Similar items:"
        results |> Array.iter (fun r ->
            printfn "  - Item %d (similarity: %.2f%%)" r.ItemId (r.Score * 100.0)
        )
    | Error err -> eprintfn "Search error: %s" err.Message
    
| Error err -> eprintfn "Index build failed: %s" err.Message

Configuration Options

let result = similaritySearch {
    indexItems items
    
    // Similarity method
    similarityMetric QuantumKernel  // Quantum feature space
    
    // Quantum kernel configuration
    featureMap (ZZFeatureMap 2)
    shots 1000
    
    // Index optimization
    buildIndex true
    indexMethod ApproximateNearestNeighbor  // Fast for large catalogs
    
    // Pre-filtering
    filterByCategory true
    categoryFeatureIndex 0
}

Example: Product Recommendations

// Product catalog features
// [category_id, price, rating, popularity, feature_vec...]
let catalog = [|
    [| 1.0; 29.99; 4.5; 850.0; 0.1; 0.8; 0.3 |]  // Electronics
    [| 1.0; 49.99; 4.8; 1200.0; 0.2; 0.9; 0.4 |] // Electronics
    [| 2.0; 15.99; 4.2; 300.0; 0.7; 0.2; 0.1 |]  // Books
    // ... 10,000 products
|]

let result = similaritySearch {
    indexItems catalog
    features ["category"; "price"; "rating"; "popularity"; "f1"; "f2"; "f3"]
    similarityMetric QuantumKernel
    buildIndex true
}

match result with
| Ok index ->
    // User viewed a product - find similar items
    let viewedProduct = catalog.[42]
    
    match SimilaritySearch.findSimilar index viewedProduct 10 with
    | Ok recommendations ->
        printfn "Customers who viewed this also liked:"
        recommendations 
        |> Array.take 5  // Top 5
        |> Array.iter (fun r ->
            printfn "  - Product %d (%.0f%% match)" r.ItemId (r.Score * 100.0)
        )
    | Error err -> eprintfn "Recommendation error: %s" err.Message
    
| Error err -> eprintfn "Index failed: %s" err.Message

Working Example

See complete example: examples/SimilaritySearch/


Quantum Drug Discovery

What is Quantum Drug Discovery?

Virtual screening of molecular candidates using quantum machine learning and optimization algorithms.

Business Applications:

Available Screening Methods

Method Description Use Case
QuantumKernelSVM Quantum kernel-based SVM classification Binary activity classification
VQCClassifier Variational Quantum Classifier Multi-label molecular classification
QAOADiverseSelection QAOA-based diverse subset selection Select diverse, high-value compounds within budget

API Reference

open FSharp.Azure.Quantum.Business
open FSharp.Azure.Quantum.Business.QuantumDrugDiscoveryDSL

// Method 1: Quantum Kernel SVM (default)
let result = drugDiscovery {
    load_candidates_from_file "candidates.sdf"
    use_method QuantumKernelSVM
    use_feature_map ZZFeatureMap
    set_batch_size 20
    shots 1000
    backend localBackend
}

match result with
| Ok screening ->
    printfn "Method: %A" screening.Method
    printfn "Molecules Processed: %d" screening.MoleculesProcessed
    printfn "Result: %s" screening.Message
| Error err -> eprintfn "Screening failed: %s" err.Message

Configuration Options

// Full configuration example
let result = drugDiscovery {
    // Data source (choose one)
    load_candidates_from_file "molecules.sdf"
    // OR: load_candidates_from_provider sdfProvider
    // OR: target_protein_from_pdb "target.pdb"
    
    // Screening method
    use_method VQCClassifier  // or QuantumKernelSVM, QAOADiverseSelection
    
    // Feature encoding
    use_feature_map ZZFeatureMap  // or PauliFeatureMap, ZFeatureMap
    
    // General settings
    set_batch_size 20         // Molecules per batch
    shots 1000                // Quantum measurement shots
    backend localBackend      // Quantum backend
    
    // VQC-specific settings (for VQCClassifier)
    vqc_layers 3              // Number of ansatz layers (default: 2)
    vqc_max_epochs 100        // Max training epochs (default: 50)
    
    // QAOA-specific settings (for QAOADiverseSelection)
    selection_budget 5.0      // Budget constraint (default: 10.0)
    diversity_weight 0.7      // Diversity bonus weight (default: 0.5)
}

Method 1: Quantum Kernel SVM

Classify molecules using quantum feature maps and support vector machines.

// Train a quantum kernel SVM for activity prediction
let result = drugDiscovery {
    load_candidates_from_file "labeled_compounds.csv"  // Requires activity labels
    use_method QuantumKernelSVM
    use_feature_map ZZFeatureMap
    set_batch_size 50
    shots 1000
    backend (LocalBackend() :> IQuantumBackend)
}

match result with
| Ok r -> 
    printfn "Support vectors found: %s" r.Message
    // Model can classify new candidates
| Error e -> eprintfn "Error: %s" e.Message

When to use:

Method 2: VQC Classifier

Train a Variational Quantum Classifier for molecular activity prediction.

// Train VQC for multi-class molecular classification
let result = drugDiscovery {
    load_candidates_from_file "compounds.sdf"
    use_method VQCClassifier
    use_feature_map ZZFeatureMap
    
    // VQC-specific configuration
    vqc_layers 3              // More layers = more expressivity
    vqc_max_epochs 100        // Training iterations
    
    set_batch_size 30
    shots 500
    backend localBackend
}

match result with
| Ok r ->
    printfn "Training complete!"
    printfn "%s" r.Message  // Shows accuracy, convergence
| Error e -> eprintfn "Training failed: %s" e.Message

When to use:

Method 3: QAOA Diverse Selection

Select a diverse subset of high-value compounds within a budget using QAOA optimization.

// Select diverse compounds for screening library
let result = drugDiscovery {
    load_candidates_from_file "compound_library.sdf"
    use_method QAOADiverseSelection
    
    // QAOA-specific configuration
    selection_budget 10.0     // Max total cost of selected compounds
    diversity_weight 0.6      // Balance value vs diversity (0-1)
    
    set_batch_size 50         // Evaluate top 50 candidates
    shots 2000                // More shots for better optimization
    backend localBackend
}

match result with
| Ok r ->
    printfn "Selection complete!"
    printfn "%s" r.Message  // Shows selected compounds, total value, diversity
| Error e -> eprintfn "Selection failed: %s" e.Message

When to use:

Example: Complete Virtual Screening Pipeline

open FSharp.Azure.Quantum.Business
open FSharp.Azure.Quantum.Core.BackendAbstraction
open FSharp.Azure.Quantum.Backends.LocalBackend

// Create backend
let backend = LocalBackend() :> IQuantumBackend

// Step 1: Initial classification with VQC
let classificationResult = drugDiscovery {
    load_candidates_from_file "hit_compounds.sdf"
    use_method VQCClassifier
    vqc_layers 2
    vqc_max_epochs 50
    set_batch_size 100
    backend backend
}

// Step 2: Select diverse subset from classified hits
let selectionResult = drugDiscovery {
    load_candidates_from_file "classified_hits.sdf"
    use_method QAOADiverseSelection
    selection_budget 20.0       // Select compounds worth total "cost" of 20
    diversity_weight 0.5        // Equal weight to value and diversity
    set_batch_size 50
    backend backend
}

match classificationResult, selectionResult with
| Ok cls, Ok sel ->
    printfn "Classification: %d molecules processed" cls.MoleculesProcessed
    printfn "Selection: %s" sel.Message
| Error e, _ -> eprintfn "Classification failed: %s" e.Message
| _, Error e -> eprintfn "Selection failed: %s" e.Message

Supported File Formats

Format Extension Provider
SDF/MOL .sdf, .mol SdfFileDatasetProvider
PDB .pdb PdbLigandDatasetProvider
SMILES .smi, .txt MolecularData.loadFromSmilesList
CSV .csv MolecularData.loadFromCsv
FCIDump .fcidump FciDumpFileDatasetProvider

Working Example

See complete example: examples/DrugDiscovery/


Social Network Analyzer

What is Social Network Analysis?

Analyze the structure and dynamics of social networks to detect communities, identify influential nodes, and optimize information flow.

Business Applications:

API Reference

open FSharp.Azure.Quantum.Business.SocialNetworkAnalyzer

// Minimal configuration - community detection
let result = socialNetworkAnalysis {
    loadGraph edges  // Array of (sourceNode, targetNode, weight) tuples
    
    // Analysis type
    analysisType CommunityDetection  // or InfluenceMaximization, InformationDiffusion
    
    // Algorithm
    method QuantumWalk  // or QAOA, Classical
}

match result with
| Ok analysis ->
    printfn "Communities found: %d" analysis.CommunityCount
    printfn "Modularity score: %.4f" analysis.Modularity
    
    // Inspect detected communities
    analysis.Communities |> Array.iteri (fun i community ->
        printfn "Community %d: %d members" i community.Members.Length
    )
    
| Error err -> eprintfn "Analysis failed: %s" err.Message

Configuration Options

let result = socialNetworkAnalysis {
    loadGraph edges
    
    // Analysis type
    analysisType InfluenceMaximization
    
    // Method selection
    method QAOA  // Quantum Approximate Optimization Algorithm
    
    // QAOA configuration
    qaoaLayers 3            // Number of QAOA layers (default: 2)
    shots 2000              // Quantum measurement shots
    backend localBackend    // Quantum backend
    
    // Influence maximization parameters
    seedSetSize 10          // Number of influencers to find
    diffusionModel IndependentCascade  // or LinearThreshold
    propagationProbability 0.1         // Edge activation probability
    
    // Graph preprocessing
    directed false          // Undirected graph
    weighted true           // Use edge weights
    normalizeWeights true   // Normalize edge weights to [0,1]
}

Example: Influence Maximization for Marketing

// Social network edges: (from_user, to_user, interaction_strength)
let socialEdges = [|
    (0, 1, 0.8); (0, 2, 0.6); (1, 3, 0.9)
    (2, 4, 0.7); (3, 5, 0.5); (4, 5, 0.4)
    (5, 6, 0.8); (6, 7, 0.3); (7, 8, 0.6)
    // ... 10,000 edges from customer interaction data
|]

let result = socialNetworkAnalysis {
    loadGraph socialEdges
    analysisType InfluenceMaximization
    method QAOA
    qaoaLayers 2
    seedSetSize 5           // Find top 5 influencers
    diffusionModel IndependentCascade
    propagationProbability 0.15
    shots 1000
    backend localBackend
}

match result with
| Ok analysis ->
    printfn "Top influencers for campaign:"
    analysis.InfluentialNodes |> Array.iteri (fun rank node ->
        printfn "  %d. User %d (reach: %.0f%% of network)" 
            (rank + 1) node.Id (node.ExpectedReach * 100.0)
    )
    printfn "Total expected reach: %.0f%% of network" 
        (analysis.TotalExpectedReach * 100.0)
    
| Error err -> eprintfn "Analysis failed: %s" err.Message

Working Example

See complete example: examples/SocialNetworkAnalysis/


Constraint Scheduler

What is Constraint Scheduling?

Optimize scheduling of tasks, resources, and events subject to hard and soft constraints such as time windows, dependencies, capacity limits, and preferences.

Business Applications:

API Reference

open FSharp.Azure.Quantum.Business.ConstraintScheduler

// Minimal configuration - schedule tasks with constraints
let result = constraintSchedule {
    tasks taskList           // Array of tasks with durations
    resources resourceList   // Available resources (people, machines, rooms)
    
    // Constraints
    timeHorizon (TimeSpan.FromHours 8.0)  // Scheduling window
    
    // Optimization objective
    objective MinimizeMakespan  // or MinimizeLateness, MaximizeUtilization
    
    // Solver
    method QAOA  // or QuantumAnnealing, Classical
}

match result with
| Ok schedule ->
    printfn "Makespan: %A" schedule.Makespan
    printfn "Resource utilization: %.1f%%" (schedule.Utilization * 100.0)
    
    // Inspect assignments
    schedule.Assignments |> Array.iter (fun a ->
        printfn "Task '%s' -> Resource '%s' at %A" 
            a.TaskName a.ResourceName a.StartTime
    )
    
| Error err -> eprintfn "Scheduling failed: %s" err.Message

Configuration Options

let result = constraintSchedule {
    tasks taskList
    resources resourceList
    
    // Time configuration
    timeHorizon (TimeSpan.FromHours 8.0)
    timeSlotDuration (TimeSpan.FromMinutes 30.0)  // Granularity
    
    // Hard constraints (must satisfy)
    precedenceConstraints [| (task1, task2); (task2, task3) |]  // task1 before task2
    unavailability [| (resource1, timeSlot3); (resource2, timeSlot1) |]
    maxConcurrentTasks 3           // Per-resource concurrency limit
    
    // Soft constraints (preferences, penalized if violated)
    preferredAssignments [| (task1, resource2, 0.8) |]  // weight 0.8
    minimizeGaps true              // Reduce idle time between tasks
    balanceLoad true               // Even distribution across resources
    
    // Solver configuration
    method QAOA
    qaoaLayers 4
    shots 2000
    backend localBackend
    
    // Optimization objective
    objective MinimizeMakespan
    constraintPenalty 10.0         // Penalty weight for soft constraint violations
}

Example: Employee Shift Scheduling

// Define shifts and employees
let shifts = [|
    { Name = "Morning"; Duration = TimeSpan.FromHours 8.0; RequiredSkill = "Cashier" }
    { Name = "Afternoon"; Duration = TimeSpan.FromHours 8.0; RequiredSkill = "Cashier" }
    { Name = "Night"; Duration = TimeSpan.FromHours 8.0; RequiredSkill = "Security" }
    { Name = "Stocking"; Duration = TimeSpan.FromHours 4.0; RequiredSkill = "General" }
    // ... 20 shifts per week
|]

let employees = [|
    { Name = "Alice"; Skills = [| "Cashier"; "General" |]; MaxHoursPerWeek = 40.0 }
    { Name = "Bob"; Skills = [| "Security"; "General" |]; MaxHoursPerWeek = 32.0 }
    { Name = "Carol"; Skills = [| "Cashier"; "Security"; "General" |]; MaxHoursPerWeek = 40.0 }
    // ... 8 employees
|]

let result = constraintSchedule {
    tasks shifts
    resources employees
    
    timeHorizon (TimeSpan.FromDays 7.0)
    timeSlotDuration (TimeSpan.FromHours 4.0)
    
    // Hard constraints
    maxConcurrentTasks 1               // One shift at a time per person
    
    // Soft constraints
    balanceLoad true                   // Fair distribution of shifts
    minimizeGaps true                  // Minimize fragmented schedules
    
    objective MaximizeUtilization
    method QAOA
    qaoaLayers 3
    shots 1500
    backend localBackend
}

match result with
| Ok schedule ->
    printfn "Weekly Schedule (utilization: %.1f%%):" (schedule.Utilization * 100.0)
    schedule.Assignments 
    |> Array.groupBy (fun a -> a.ResourceName)
    |> Array.iter (fun (employee, assignments) ->
        let totalHours = assignments |> Array.sumBy (fun a -> a.Duration.TotalHours)
        printfn "  %s (%.0f hrs):" employee totalHours
        assignments |> Array.iter (fun a ->
            printfn "    %s at %A" a.TaskName a.StartTime
        )
    )
    
| Error err -> eprintfn "Scheduling failed: %s" err.Message

Working Example

See complete example: examples/ConstraintScheduling/


Coverage Optimizer

What is Set Coverage Optimization?

Find the minimum-cost collection of options that covers all required elements. This is a fundamental combinatorial optimization problem with broad applications in facility placement, service deployment, and resource allocation.

Business Applications:

API Reference

The coverageOptimizer computation expression builder is in FSharp.Azure.Quantum.Business.CoverageOptimizer.

CE Operations:

Operation Parameters Description
element elementIndex: int Add an element to the universe (expands universe size if needed)
universeSize size: int Set the universe size directly
option id: string, coveredElements: int list, cost: float Add a coverage option with its cost
backend backend: IQuantumBackend Set the quantum backend (required)
shots shots: int Number of measurement shots (default: 1000)

Result type — CoverageResult:

Field Type Description
SelectedOptions CoverageOption list Coverage options selected by the optimizer
TotalCost float Total cost of selected options
ElementsCovered int Number of distinct elements covered
TotalElements int Total elements that need coverage
IsComplete bool Whether all elements are covered
Message string Human-readable execution summary

Minimal example:

open FSharp.Azure.Quantum.Business.CoverageOptimizer

let result = coverageOptimizer {
    element 0   // Time slot 0
    element 1   // Time slot 1
    element 2   // Time slot 2

    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 quantumBackend
}

Working Example

See the complete runnable script with CLI options, JSON/CSV output, and detailed reporting: examples/CoverageOptimizer/CoverageOptimizer_Example.fsx


Resource Pairing

What is Resource Pairing?

Optimally match participants into pairs based on compatibility scores to maximize total matching quality. This solves maximum weight matching problems common in workforce management, mentoring programs, and logistics.

Business Applications:

API Reference

The resourcePairing computation expression builder is in FSharp.Azure.Quantum.Business.ResourcePairing.

CE Operations:

Operation Parameters Description
participant id: string Add a single participant
participants ids: string list Add multiple participants at once
compatibility p1: string, p2: string, weight: float Set compatibility score between two participants (higher = better)
backend backend: IQuantumBackend Set the quantum backend (required)
shots shots: int Number of measurement shots (default: 1000)

Result type — PairingResult:

Field Type Description
Pairings Pairing list Optimal pairings found (each has Participant1, Participant2, Weight)
TotalScore float Total compatibility score across all pairings
ParticipantsPaired int Number of participants that were paired
TotalParticipants int Total number of participants
IsValid bool Whether matching is valid (no participant in multiple pairs)
Message string Human-readable execution summary

Minimal example:

open FSharp.Azure.Quantum.Business.ResourcePairing

let result = resourcePairing {
    participant "Alice"
    participant "Bob"
    participant "Carol"

    compatibility "Alice" "Bob" 0.9    // High compatibility
    compatibility "Alice" "Carol" 0.5  // Medium compatibility
    compatibility "Bob" "Carol" 0.7    // Good compatibility

    backend quantumBackend
}

Working Example

See the complete runnable script with CLI options, JSON/CSV output, and detailed reporting: examples/ResourcePairing/ResourcePairing_Example.fsx


Packing Optimizer

What is Bin Packing Optimization?

Optimally pack items of varying sizes into containers (bins) to minimize the number of containers used. This is a classic combinatorial optimization problem with significant cost implications in logistics and infrastructure.

Business Applications:

API Reference

The packingOptimizer computation expression builder is in FSharp.Azure.Quantum.Business.PackingOptimizer.

CE Operations:

Operation Parameters Description
item id: string, size: float Add an item to pack with its size/weight
containerCapacity capacity: float Set the bin/container capacity (all bins have the same capacity)
backend backend: IQuantumBackend Set the quantum backend (required)
shots shots: int Number of measurement shots (default: 1000)

Result type — PackingResult:

Field Type Description
Assignments BinAssignment list Item-to-bin assignments (each has Item: PackingItem, BinIndex: int)
BinsUsed int Number of bins used
IsValid bool Whether all items are assigned and no bin exceeds capacity
TotalItems int Total items in the problem
ItemsAssigned int Items successfully assigned
Message string Human-readable execution summary

Minimal example:

open FSharp.Azure.Quantum.Business.PackingOptimizer

let result = 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 quantumBackend
}

Working Example

See the complete runnable script with CLI options, JSON/CSV output, and detailed reporting: examples/PackingOptimizer/PackingOptimizer_Example.fsx


Architecture Selection Guide

When to Use Each Architecture

Quantum:

Classical:

Hybrid:

AutoSelect:

Performance Comparison

Architecture Training Time Inference Time Accuracy (Typical) Resource Usage
Quantum Minutes-Hours Seconds 85-95% High (quantum backend)
Classical Seconds-Minutes Milliseconds 80-90% Low (CPU only)
Hybrid Minutes Hundreds of ms 83-93% Medium

Troubleshooting

Common Issues

1. Poor Accuracy (<60%)

Symptoms: Model performs poorly on both train and test sets

Solutions:

2. Overfitting (High Train, Low Test Accuracy)

Symptoms: Train accuracy >90%, test accuracy <70%

Solutions:

3. Slow Training

Symptoms: Training takes hours

Solutions:

4. Class Imbalance (Fraud Detection)

Symptoms: Model always predicts majority class

Solutions:

See Also


Last Updated: December 2025