quantrs2-anneal 0.1.3

Quantum annealing support for the QuantRS2 framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
//! Healthcare Industry Optimization
//!
//! This module provides optimization solutions for the healthcare industry,
//! including resource allocation, patient scheduling, treatment planning,
//! and supply chain optimization for medical facilities.

use super::{
    ApplicationError, ApplicationResult, IndustryConstraint, IndustryObjective, IndustrySolution,
    OptimizationProblem,
};
use crate::ising::IsingModel;
use crate::qubo::{QuboBuilder, QuboFormulation};
use crate::simulator::{AnnealingParams, ClassicalAnnealingSimulator};
use std::collections::HashMap;

use std::fmt::Write;
/// Medical Resource Allocation Problem
#[derive(Debug, Clone)]
pub struct MedicalResourceAllocation {
    /// Number of hospitals/clinics
    pub num_facilities: usize,
    /// Number of medical departments
    pub num_departments: usize,
    /// Number of resource types (staff, equipment, beds)
    pub num_resource_types: usize,
    /// Available resources at each facility
    pub available_resources: Vec<Vec<f64>>,
    /// Resource requirements by department
    pub resource_requirements: Vec<Vec<f64>>,
    /// Patient demand forecasts by facility and department
    pub patient_demands: Vec<Vec<f64>>,
    /// Resource utilization costs
    pub resource_costs: Vec<Vec<f64>>,
    /// Quality of care metrics
    pub quality_targets: Vec<f64>,
    /// Emergency capacity requirements
    pub emergency_reserves: Vec<f64>,
    /// Resource sharing constraints between facilities
    pub sharing_constraints: Vec<IndustryConstraint>,
}

impl MedicalResourceAllocation {
    /// Create a new medical resource allocation problem
    pub fn new(
        num_facilities: usize,
        num_departments: usize,
        num_resource_types: usize,
        available_resources: Vec<Vec<f64>>,
        patient_demands: Vec<Vec<f64>>,
    ) -> ApplicationResult<Self> {
        if available_resources.len() != num_facilities {
            return Err(ApplicationError::InvalidConfiguration(
                "Available resources must match number of facilities".to_string(),
            ));
        }

        if patient_demands.len() != num_facilities {
            return Err(ApplicationError::InvalidConfiguration(
                "Patient demands must match number of facilities".to_string(),
            ));
        }

        Ok(Self {
            num_facilities,
            num_departments,
            num_resource_types,
            available_resources,
            resource_requirements: vec![vec![1.0; num_resource_types]; num_departments],
            patient_demands,
            resource_costs: vec![vec![1.0; num_resource_types]; num_facilities],
            quality_targets: vec![0.95; num_departments],
            emergency_reserves: vec![0.1; num_resource_types], // 10% emergency reserve
            sharing_constraints: Vec::new(),
        })
    }

    /// Set resource requirements for departments
    pub fn set_resource_requirements(
        &mut self,
        requirements: Vec<Vec<f64>>,
    ) -> ApplicationResult<()> {
        if requirements.len() != self.num_departments {
            return Err(ApplicationError::InvalidConfiguration(
                "Resource requirements must match number of departments".to_string(),
            ));
        }

        self.resource_requirements = requirements;
        Ok(())
    }

    /// Calculate resource utilization rate
    #[must_use]
    pub fn calculate_utilization(&self, allocation: &MedicalResourceSolution) -> Vec<f64> {
        let mut utilization = vec![0.0; self.num_resource_types];

        for facility in 0..self.num_facilities {
            for dept in 0..self.num_departments {
                for resource in 0..self.num_resource_types {
                    let allocated = allocation.allocations[facility][dept][resource];
                    let available = self.available_resources[facility][resource];

                    if available > 0.0 {
                        utilization[resource] += allocated / available;
                    }
                }
            }
        }

        // Average utilization across facilities
        for util in &mut utilization {
            *util /= self.num_facilities as f64;
        }

        utilization
    }

    /// Calculate patient satisfaction score
    #[must_use]
    pub fn calculate_patient_satisfaction(&self, allocation: &MedicalResourceSolution) -> f64 {
        let mut total_satisfaction = 0.0;
        let mut total_patients = 0.0;

        for facility in 0..self.num_facilities {
            for dept in 0..self.num_departments {
                let demand = self.patient_demands[facility][dept];
                let capacity = self.calculate_department_capacity(facility, dept, allocation);

                let service_ratio = if demand > 0.0 {
                    (capacity / demand).min(1.0)
                } else {
                    1.0
                };

                total_satisfaction += service_ratio * demand;
                total_patients += demand;
            }
        }

        if total_patients > 0.0 {
            total_satisfaction / total_patients
        } else {
            1.0
        }
    }

    /// Calculate department capacity based on resource allocation
    fn calculate_department_capacity(
        &self,
        facility: usize,
        dept: usize,
        allocation: &MedicalResourceSolution,
    ) -> f64 {
        let mut capacity = f64::INFINITY;

        for resource in 0..self.num_resource_types {
            let allocated = allocation.allocations[facility][dept][resource];
            let required = self.resource_requirements[dept][resource];

            if required > 0.0 {
                capacity = capacity.min(allocated / required);
            }
        }

        if capacity == f64::INFINITY {
            0.0
        } else {
            capacity
        }
    }
}

impl OptimizationProblem for MedicalResourceAllocation {
    type Solution = MedicalResourceSolution;
    type ObjectiveValue = f64;

    fn description(&self) -> String {
        format!(
            "Medical resource allocation for {} facilities, {} departments, {} resource types",
            self.num_facilities, self.num_departments, self.num_resource_types
        )
    }

    fn size_metrics(&self) -> HashMap<String, usize> {
        let mut metrics = HashMap::new();
        metrics.insert("num_facilities".to_string(), self.num_facilities);
        metrics.insert("num_departments".to_string(), self.num_departments);
        metrics.insert("num_resource_types".to_string(), self.num_resource_types);
        metrics.insert(
            "num_constraints".to_string(),
            self.sharing_constraints.len(),
        );
        metrics
    }

    fn validate(&self) -> ApplicationResult<()> {
        if self.num_facilities == 0 {
            return Err(ApplicationError::DataValidationError(
                "At least one facility required".to_string(),
            ));
        }

        if self.num_departments == 0 {
            return Err(ApplicationError::DataValidationError(
                "At least one department required".to_string(),
            ));
        }

        if self.num_resource_types == 0 {
            return Err(ApplicationError::DataValidationError(
                "At least one resource type required".to_string(),
            ));
        }

        // Check positive resource availability
        for facility in &self.available_resources {
            for &resource in facility {
                if resource < 0.0 {
                    return Err(ApplicationError::DataValidationError(
                        "Available resources must be non-negative".to_string(),
                    ));
                }
            }
        }

        // Check positive patient demands
        for facility in &self.patient_demands {
            for &demand in facility {
                if demand < 0.0 {
                    return Err(ApplicationError::DataValidationError(
                        "Patient demands must be non-negative".to_string(),
                    ));
                }
            }
        }

        Ok(())
    }

    fn to_qubo(&self) -> ApplicationResult<(crate::ising::QuboModel, HashMap<String, usize>)> {
        let mut builder = QuboBuilder::new();
        let precision = 20; // Discretization precision

        // Binary variables: x[f][d][r][l] = 1 if facility f allocates level l of resource r to department d
        let mut var_counter = 0;
        let mut var_map = HashMap::new();
        let mut string_var_map = HashMap::new();

        for facility in 0..self.num_facilities {
            for dept in 0..self.num_departments {
                for resource in 0..self.num_resource_types {
                    for level in 0..precision {
                        let var_name = format!("x_{facility}_{dept}_{resource}_{level}");
                        var_map.insert((facility, dept, resource, level), var_counter);
                        string_var_map.insert(var_name, var_counter);
                        var_counter += 1;
                    }
                }
            }
        }

        // Objective: maximize patient satisfaction - cost penalty
        for facility in 0..self.num_facilities {
            for dept in 0..self.num_departments {
                let demand = self.patient_demands[facility][dept];

                for resource in 0..self.num_resource_types {
                    for level in 0..precision {
                        let allocation = f64::from(level) / f64::from(precision);
                        let var_idx = var_map[&(facility, dept, resource, level)];

                        // Service benefit (maximize patient care)
                        let required = self.resource_requirements[dept][resource];
                        let capacity_contribution = if required > 0.0 {
                            allocation / required
                        } else {
                            0.0
                        };
                        let service_benefit = -demand * capacity_contribution * 100.0; // Negative for maximization
                        builder.add_bias(var_idx, service_benefit);

                        // Cost penalty
                        let cost = allocation
                            * self.available_resources[facility][resource]
                            * self.resource_costs[facility][resource];
                        builder.add_bias(var_idx, cost);
                    }
                }
            }
        }

        // Constraint: each resource-department pair gets exactly one allocation level
        let constraint_penalty = 10_000.0;
        for facility in 0..self.num_facilities {
            for dept in 0..self.num_departments {
                for resource in 0..self.num_resource_types {
                    let mut constraint_vars = Vec::new();

                    for level in 0..precision {
                        constraint_vars.push(var_map[&(facility, dept, resource, level)]);
                    }

                    // Penalty for not selecting exactly one level
                    for &var1 in &constraint_vars {
                        builder.add_bias(var1, -constraint_penalty);
                        for &var2 in &constraint_vars {
                            if var1 != var2 {
                                builder.add_coupling(var1, var2, constraint_penalty);
                            }
                        }
                    }
                }
            }
        }

        // Constraint: don't exceed available resources
        for facility in 0..self.num_facilities {
            for resource in 0..self.num_resource_types {
                let available = self.available_resources[facility][resource]
                    * (1.0 - self.emergency_reserves[resource]); // Reserve for emergencies

                for level1 in 0..precision {
                    for dept1 in 0..self.num_departments {
                        for level2 in 0..precision {
                            for dept2 in (dept1 + 1)..self.num_departments {
                                let alloc1 = f64::from(level1) / f64::from(precision) * available;
                                let alloc2 = f64::from(level2) / f64::from(precision) * available;

                                if alloc1 + alloc2 > available {
                                    let var1 = var_map[&(facility, dept1, resource, level1)];
                                    let var2 = var_map[&(facility, dept2, resource, level2)];
                                    builder.add_coupling(var1, var2, constraint_penalty);
                                }
                            }
                        }
                    }
                }
            }
        }

        Ok((builder.build(), string_var_map))
    }

    fn evaluate_solution(
        &self,
        solution: &Self::Solution,
    ) -> ApplicationResult<Self::ObjectiveValue> {
        let satisfaction = self.calculate_patient_satisfaction(solution);
        let total_cost = solution.total_cost;

        // Objective: maximize satisfaction while minimizing cost
        Ok(satisfaction.mul_add(1000.0, -total_cost))
    }

    fn is_feasible(&self, solution: &Self::Solution) -> bool {
        // Check resource constraints
        for facility in 0..self.num_facilities {
            for resource in 0..self.num_resource_types {
                let total_allocated: f64 = (0..self.num_departments)
                    .map(|dept| solution.allocations[facility][dept][resource])
                    .sum();

                let available = self.available_resources[facility][resource]
                    * (1.0 - self.emergency_reserves[resource]);

                if total_allocated > available + 1e-6 {
                    return false;
                }
            }
        }

        // Check minimum quality targets
        let satisfaction = self.calculate_patient_satisfaction(solution);
        if satisfaction < 0.8 {
            // Minimum 80% patient satisfaction
            return false;
        }

        true
    }
}

/// Solution for Medical Resource Allocation
#[derive(Debug, Clone)]
pub struct MedicalResourceSolution {
    /// Resource allocations \[facility\]\[department\]\[resource\]
    pub allocations: Vec<Vec<Vec<f64>>>,
    /// Total allocation cost
    pub total_cost: f64,
    /// Patient satisfaction score
    pub patient_satisfaction: f64,
    /// Resource utilization rates
    pub utilization_rates: Vec<f64>,
    /// Quality metrics
    pub quality_metrics: HealthcareMetrics,
}

/// Healthcare performance metrics
#[derive(Debug, Clone)]
pub struct HealthcareMetrics {
    /// Average patient wait time
    pub avg_wait_time: f64,
    /// Bed occupancy rate
    pub bed_occupancy: f64,
    /// Staff utilization rate
    pub staff_utilization: f64,
    /// Equipment utilization rate
    pub equipment_utilization: f64,
    /// Emergency response time
    pub emergency_response_time: f64,
    /// Quality of care score
    pub quality_score: f64,
}

impl IndustrySolution for MedicalResourceSolution {
    type Problem = MedicalResourceAllocation;

    fn from_binary(problem: &Self::Problem, binary_solution: &[i8]) -> ApplicationResult<Self> {
        let precision = 20;
        let mut allocations =
            vec![
                vec![vec![0.0; problem.num_resource_types]; problem.num_departments];
                problem.num_facilities
            ];
        let mut var_idx = 0;

        // Decode allocations from binary solution
        for facility in 0..problem.num_facilities {
            for dept in 0..problem.num_departments {
                for resource in 0..problem.num_resource_types {
                    for level in 0..precision {
                        if var_idx < binary_solution.len() && binary_solution[var_idx] == 1 {
                            let allocation_fraction = f64::from(level) / f64::from(precision);
                            let available = problem.available_resources[facility][resource]
                                * (1.0 - problem.emergency_reserves[resource]);
                            allocations[facility][dept][resource] = allocation_fraction * available;
                            break;
                        }
                        var_idx += 1;
                    }
                }
            }
        }

        // Calculate total cost
        let mut total_cost = 0.0;
        for facility in 0..problem.num_facilities {
            for dept in 0..problem.num_departments {
                for resource in 0..problem.num_resource_types {
                    total_cost += allocations[facility][dept][resource]
                        * problem.resource_costs[facility][resource];
                }
            }
        }

        let solution = Self {
            allocations,
            total_cost,
            patient_satisfaction: 0.0,
            utilization_rates: Vec::new(),
            quality_metrics: HealthcareMetrics {
                avg_wait_time: 0.0,
                bed_occupancy: 0.0,
                staff_utilization: 0.0,
                equipment_utilization: 0.0,
                emergency_response_time: 0.0,
                quality_score: 0.0,
            },
        };

        // Calculate metrics
        let patient_satisfaction = problem.calculate_patient_satisfaction(&solution);
        let utilization_rates = problem.calculate_utilization(&solution);

        let quality_metrics = HealthcareMetrics {
            avg_wait_time: 25.0, // Simplified calculation
            bed_occupancy: utilization_rates.get(0).copied().unwrap_or(0.0),
            staff_utilization: utilization_rates.get(1).copied().unwrap_or(0.0),
            equipment_utilization: utilization_rates.get(2).copied().unwrap_or(0.0),
            emergency_response_time: 8.0, // Simplified
            quality_score: patient_satisfaction,
        };

        Ok(Self {
            allocations: solution.allocations,
            total_cost,
            patient_satisfaction,
            utilization_rates,
            quality_metrics,
        })
    }

    fn summary(&self) -> HashMap<String, String> {
        let mut summary = HashMap::new();
        summary.insert(
            "type".to_string(),
            "Medical Resource Allocation".to_string(),
        );
        summary.insert("total_cost".to_string(), format!("${:.2}", self.total_cost));
        summary.insert(
            "patient_satisfaction".to_string(),
            format!("{:.1}%", self.patient_satisfaction * 100.0),
        );
        summary.insert(
            "avg_wait_time".to_string(),
            format!("{:.1} minutes", self.quality_metrics.avg_wait_time),
        );
        summary.insert(
            "bed_occupancy".to_string(),
            format!("{:.1}%", self.quality_metrics.bed_occupancy * 100.0),
        );
        summary.insert(
            "staff_utilization".to_string(),
            format!("{:.1}%", self.quality_metrics.staff_utilization * 100.0),
        );
        summary.insert(
            "quality_score".to_string(),
            format!("{:.3}", self.quality_metrics.quality_score),
        );
        summary
    }

    fn metrics(&self) -> HashMap<String, f64> {
        let mut metrics = HashMap::new();
        metrics.insert("total_cost".to_string(), self.total_cost);
        metrics.insert(
            "patient_satisfaction".to_string(),
            self.patient_satisfaction,
        );
        metrics.insert(
            "avg_wait_time".to_string(),
            self.quality_metrics.avg_wait_time,
        );
        metrics.insert(
            "bed_occupancy".to_string(),
            self.quality_metrics.bed_occupancy,
        );
        metrics.insert(
            "staff_utilization".to_string(),
            self.quality_metrics.staff_utilization,
        );
        metrics.insert(
            "equipment_utilization".to_string(),
            self.quality_metrics.equipment_utilization,
        );
        metrics.insert(
            "emergency_response_time".to_string(),
            self.quality_metrics.emergency_response_time,
        );
        metrics.insert(
            "quality_score".to_string(),
            self.quality_metrics.quality_score,
        );

        for (i, &util) in self.utilization_rates.iter().enumerate() {
            metrics.insert(format!("resource_{i}_utilization"), util);
        }

        metrics
    }

    fn export_format(&self) -> ApplicationResult<String> {
        let mut output = String::new();
        output.push_str("# Medical Resource Allocation Report\n\n");

        output.push_str("## Allocation Summary\n");
        let _ = writeln!(output, "Total Cost: ${:.2}", self.total_cost);
        let _ = write!(
            output,
            "Patient Satisfaction: {:.1}%\n",
            self.patient_satisfaction * 100.0
        );
        let _ = write!(
            output,
            "Quality Score: {:.3}\n",
            self.quality_metrics.quality_score
        );

        output.push_str("\n## Resource Utilization\n");
        let _ = write!(
            output,
            "Bed Occupancy: {:.1}%\n",
            self.quality_metrics.bed_occupancy * 100.0
        );
        let _ = write!(
            output,
            "Staff Utilization: {:.1}%\n",
            self.quality_metrics.staff_utilization * 100.0
        );
        let _ = write!(
            output,
            "Equipment Utilization: {:.1}%\n",
            self.quality_metrics.equipment_utilization * 100.0
        );

        output.push_str("\n## Performance Metrics\n");
        let _ = write!(
            output,
            "Average Wait Time: {:.1} minutes\n",
            self.quality_metrics.avg_wait_time
        );
        let _ = write!(
            output,
            "Emergency Response Time: {:.1} minutes\n",
            self.quality_metrics.emergency_response_time
        );

        output.push_str("\n## Resource Allocations\n");
        for (facility, facility_allocs) in self.allocations.iter().enumerate() {
            let _ = writeln!(output, "### Facility {}", facility + 1);
            for (dept, dept_allocs) in facility_allocs.iter().enumerate() {
                let _ = write!(output, "Department {}: ", dept + 1);
                for (resource, &allocation) in dept_allocs.iter().enumerate() {
                    let _ = write!(output, "R{resource}: {allocation:.1} ");
                }
                output.push_str("\n");
            }
        }

        Ok(output)
    }
}

/// Treatment Planning Optimization Problem
#[derive(Debug, Clone)]
pub struct TreatmentPlanningOptimization {
    /// Number of patients
    pub num_patients: usize,
    /// Number of available treatments
    pub num_treatments: usize,
    /// Treatment efficacy matrix \[patient\]\[treatment\]
    pub treatment_efficacy: Vec<Vec<f64>>,
    /// Treatment costs
    pub treatment_costs: Vec<f64>,
    /// Treatment durations
    pub treatment_durations: Vec<f64>,
    /// Patient priority scores
    pub patient_priorities: Vec<f64>,
    /// Treatment compatibility constraints
    pub compatibility_constraints: Vec<Vec<bool>>,
    /// Resource requirements for treatments
    pub resource_requirements: Vec<HashMap<String, f64>>,
    /// Available resources
    pub available_resources: HashMap<String, f64>,
}

impl TreatmentPlanningOptimization {
    /// Create new treatment planning problem
    pub fn new(
        num_patients: usize,
        num_treatments: usize,
        treatment_efficacy: Vec<Vec<f64>>,
        treatment_costs: Vec<f64>,
    ) -> ApplicationResult<Self> {
        if treatment_efficacy.len() != num_patients {
            return Err(ApplicationError::InvalidConfiguration(
                "Treatment efficacy matrix dimension mismatch".to_string(),
            ));
        }

        Ok(Self {
            num_patients,
            num_treatments,
            treatment_efficacy,
            treatment_costs,
            treatment_durations: vec![1.0; num_treatments],
            patient_priorities: vec![1.0; num_patients],
            compatibility_constraints: vec![vec![true; num_treatments]; num_patients],
            resource_requirements: vec![HashMap::new(); num_treatments],
            available_resources: HashMap::new(),
        })
    }

    /// Calculate total treatment benefit
    #[must_use]
    pub fn calculate_benefit(&self, plan: &TreatmentPlan) -> f64 {
        let mut total_benefit = 0.0;

        for (patient, assignments) in plan.patient_treatments.iter().enumerate() {
            for (treatment, &assigned) in assignments.iter().enumerate() {
                if assigned {
                    let efficacy = self.treatment_efficacy[patient][treatment];
                    let priority = self.patient_priorities[patient];
                    total_benefit += efficacy * priority;
                }
            }
        }

        total_benefit
    }
}

/// Treatment Plan Solution
#[derive(Debug, Clone)]
pub struct TreatmentPlan {
    /// Treatment assignments \[patient\]\[treatment\] = assigned
    pub patient_treatments: Vec<Vec<bool>>,
    /// Total cost
    pub total_cost: f64,
    /// Total benefit
    pub total_benefit: f64,
    /// Resource utilization
    pub resource_utilization: HashMap<String, f64>,
}

/// Binary wrapper for Medical Resource Allocation that works with binary solutions
#[derive(Debug, Clone)]
pub struct BinaryMedicalResourceAllocation {
    inner: MedicalResourceAllocation,
}

impl BinaryMedicalResourceAllocation {
    #[must_use]
    pub const fn new(inner: MedicalResourceAllocation) -> Self {
        Self { inner }
    }
}

impl OptimizationProblem for BinaryMedicalResourceAllocation {
    type Solution = Vec<i8>;
    type ObjectiveValue = f64;

    fn description(&self) -> String {
        self.inner.description()
    }

    fn size_metrics(&self) -> HashMap<String, usize> {
        self.inner.size_metrics()
    }

    fn validate(&self) -> ApplicationResult<()> {
        self.inner.validate()
    }

    fn to_qubo(&self) -> ApplicationResult<(crate::ising::QuboModel, HashMap<String, usize>)> {
        self.inner.to_qubo()
    }

    fn evaluate_solution(
        &self,
        solution: &Self::Solution,
    ) -> ApplicationResult<Self::ObjectiveValue> {
        // Convert binary solution to MedicalResourceSolution for evaluation
        let resource_solution = MedicalResourceSolution::from_binary(&self.inner, solution)?;
        self.inner.evaluate_solution(&resource_solution)
    }

    fn is_feasible(&self, solution: &Self::Solution) -> bool {
        // Convert binary solution to MedicalResourceSolution for feasibility check
        if let Ok(resource_solution) = MedicalResourceSolution::from_binary(&self.inner, solution) {
            self.inner.is_feasible(&resource_solution)
        } else {
            false
        }
    }
}

/// Create benchmark healthcare problems
pub fn create_benchmark_problems(
    size: usize,
) -> ApplicationResult<Vec<Box<dyn OptimizationProblem<Solution = Vec<i8>, ObjectiveValue = f64>>>>
{
    let mut problems = Vec::new();

    // Problem 1: Small hospital resource allocation
    let available_resources = vec![
        vec![50.0, 20.0, 10.0], // Facility 1: beds, staff, equipment
        vec![30.0, 15.0, 8.0],  // Facility 2
    ];
    let patient_demands = vec![
        vec![40.0, 25.0, 15.0], // Facility 1 demands by department
        vec![20.0, 18.0, 12.0], // Facility 2 demands by department
    ];

    let hospital_allocation = MedicalResourceAllocation::new(
        2, // facilities
        3, // departments
        3, // resource types
        available_resources,
        patient_demands,
    )?;

    problems.push(
        Box::new(BinaryMedicalResourceAllocation::new(hospital_allocation))
            as Box<dyn OptimizationProblem<Solution = Vec<i8>, ObjectiveValue = f64>>,
    );

    // Problem 2: Larger healthcare network
    if size >= 4 {
        let large_resources = vec![vec![100.0, 50.0, 25.0, 15.0]; size];
        let large_demands = vec![vec![80.0, 40.0, 30.0, 20.0]; size];

        let large_allocation = MedicalResourceAllocation::new(
            size,
            4, // departments
            4, // resource types
            large_resources,
            large_demands,
        )?;

        problems.push(
            Box::new(BinaryMedicalResourceAllocation::new(large_allocation))
                as Box<dyn OptimizationProblem<Solution = Vec<i8>, ObjectiveValue = f64>>,
        );
    }

    Ok(problems)
}

/// Solve medical resource allocation using quantum annealing
pub fn solve_medical_resource_allocation(
    problem: &MedicalResourceAllocation,
    params: Option<AnnealingParams>,
) -> ApplicationResult<MedicalResourceSolution> {
    // Convert to QUBO
    let (qubo, _var_map) = problem.to_qubo()?;

    // Convert to Ising
    let ising = IsingModel::from_qubo(&qubo);

    // Set up annealing parameters
    let annealing_params = params.unwrap_or_else(|| {
        let mut p = AnnealingParams::default();
        p.num_sweeps = 20_000;
        p.num_repetitions = 30;
        p.initial_temperature = 4.0;
        p.final_temperature = 0.01;
        p
    });

    // Solve with classical annealing
    let simulator = ClassicalAnnealingSimulator::new(annealing_params)
        .map_err(|e| ApplicationError::OptimizationError(e.to_string()))?;

    let result = simulator
        .solve(&ising)
        .map_err(|e| ApplicationError::OptimizationError(e.to_string()))?;

    // Convert solution back to medical resource allocation
    MedicalResourceSolution::from_binary(problem, &result.best_spins)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_medical_resource_allocation_creation() {
        let available_resources = vec![vec![50.0, 20.0, 10.0], vec![30.0, 15.0, 8.0]];
        let patient_demands = vec![vec![40.0, 25.0, 15.0], vec![20.0, 18.0, 12.0]];

        let allocation =
            MedicalResourceAllocation::new(2, 3, 3, available_resources, patient_demands)
                .expect("Failed to create medical resource allocation");
        assert_eq!(allocation.num_facilities, 2);
        assert_eq!(allocation.num_departments, 3);
        assert_eq!(allocation.num_resource_types, 3);
    }

    #[test]
    fn test_patient_satisfaction_calculation() {
        let available_resources = vec![vec![100.0, 50.0]];
        let patient_demands = vec![vec![80.0, 40.0]];

        let problem = MedicalResourceAllocation::new(1, 2, 2, available_resources, patient_demands)
            .expect("Failed to create medical resource allocation");

        let solution = MedicalResourceSolution {
            allocations: vec![vec![vec![80.0, 20.0], vec![20.0, 30.0]]],
            total_cost: 1000.0,
            patient_satisfaction: 0.0,
            utilization_rates: Vec::new(),
            quality_metrics: HealthcareMetrics {
                avg_wait_time: 0.0,
                bed_occupancy: 0.0,
                staff_utilization: 0.0,
                equipment_utilization: 0.0,
                emergency_response_time: 0.0,
                quality_score: 0.0,
            },
        };

        let satisfaction = problem.calculate_patient_satisfaction(&solution);
        assert!(satisfaction >= 0.0 && satisfaction <= 1.0);
    }

    #[test]
    fn test_treatment_planning_creation() {
        let efficacy = vec![vec![0.8, 0.6, 0.9], vec![0.7, 0.9, 0.5]];
        let costs = vec![1000.0, 1500.0, 800.0];

        let planning = TreatmentPlanningOptimization::new(2, 3, efficacy, costs)
            .expect("Failed to create treatment planning optimization");
        assert_eq!(planning.num_patients, 2);
        assert_eq!(planning.num_treatments, 3);
    }

    #[test]
    fn test_benchmark_problems() {
        let problems = create_benchmark_problems(4).expect("Failed to create benchmark problems");
        assert_eq!(problems.len(), 2);

        for problem in &problems {
            assert!(problem.validate().is_ok());
        }
    }
}