quantrs2_core/
hybrid_learning.rs

1//! Quantum-Classical Hybrid Learning Algorithms
2//!
3//! This module provides advanced hybrid learning algorithms that combine
4//! classical machine learning techniques with quantum computing to achieve
5//! enhanced performance for complex learning tasks.
6
7use crate::{
8    adaptive_precision::AdaptivePrecisionSimulator, error::QuantRS2Result,
9    quantum_autodiff::QuantumAutoDiff,
10};
11use scirs2_core::ndarray::{Array1, Array2};
12use std::{
13    collections::HashMap,
14    sync::{Arc, RwLock},
15    time::{Duration, Instant},
16};
17
18/// Configuration for hybrid learning algorithms
19#[derive(Debug, Clone)]
20pub struct HybridLearningConfig {
21    /// Quantum circuit depth
22    pub quantum_depth: usize,
23    /// Number of qubits for quantum processing
24    pub num_qubits: usize,
25    /// Classical network architecture
26    pub classical_layers: Vec<usize>,
27    /// Learning rate for quantum parameters
28    pub quantum_learning_rate: f64,
29    /// Learning rate for classical parameters
30    pub classical_learning_rate: f64,
31    /// Batch size for training
32    pub batch_size: usize,
33    /// Maximum number of training epochs
34    pub max_epochs: usize,
35    /// Early stopping patience
36    pub early_stopping_patience: usize,
37    /// Quantum-classical interaction type
38    pub interaction_type: InteractionType,
39    /// Enable quantum advantage analysis
40    pub enable_quantum_advantage_analysis: bool,
41    /// Use adaptive precision for quantum part
42    pub use_adaptive_precision: bool,
43}
44
45impl Default for HybridLearningConfig {
46    fn default() -> Self {
47        Self {
48            quantum_depth: 3,
49            num_qubits: 4,
50            classical_layers: vec![64, 32, 16],
51            quantum_learning_rate: 0.01,
52            classical_learning_rate: 0.001,
53            batch_size: 32,
54            max_epochs: 100,
55            early_stopping_patience: 10,
56            interaction_type: InteractionType::Sequential,
57            enable_quantum_advantage_analysis: true,
58            use_adaptive_precision: true,
59        }
60    }
61}
62
63/// Types of quantum-classical interactions
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum InteractionType {
66    /// Sequential: Classical → Quantum → Classical
67    Sequential,
68    /// Interleaved: Classical ↔ Quantum alternating
69    Interleaved,
70    /// Parallel: Classical || Quantum with fusion
71    Parallel,
72    /// Residual: Classical + Quantum (skip connections)
73    Residual,
74    /// Attention: Quantum attention over classical features
75    Attention,
76}
77
78/// Hybrid quantum-classical neural network
79#[derive(Debug)]
80pub struct HybridNeuralNetwork {
81    config: HybridLearningConfig,
82    classical_layers: Vec<DenseLayer>,
83    quantum_circuit: ParameterizedQuantumCircuit,
84    fusion_layer: FusionLayer,
85    autodiff: Arc<RwLock<QuantumAutoDiff>>,
86    adaptive_precision: Option<Arc<RwLock<AdaptivePrecisionSimulator>>>,
87    training_history: TrainingHistory,
88}
89
90/// Dense layer for classical processing
91#[derive(Debug, Clone)]
92pub struct DenseLayer {
93    weights: Array2<f64>,
94    biases: Array1<f64>,
95    activation: ActivationFunction,
96}
97
98/// Activation functions
99#[derive(Debug, Clone, Copy)]
100pub enum ActivationFunction {
101    ReLU,
102    Sigmoid,
103    Tanh,
104    Linear,
105    Swish,
106    GELU,
107}
108
109/// Parameterized quantum circuit
110#[derive(Debug)]
111pub struct ParameterizedQuantumCircuit {
112    num_qubits: usize,
113    depth: usize,
114    parameters: Vec<f64>,
115    gate_sequence: Vec<QuantumGateInfo>,
116    parameter_map: HashMap<usize, Vec<usize>>, // gate_id -> parameter_indices
117}
118
119#[derive(Debug, Clone)]
120pub struct QuantumGateInfo {
121    gate_type: String,
122    qubits: Vec<usize>,
123    is_parameterized: bool,
124    parameter_index: Option<usize>,
125}
126
127/// Fusion layer for combining quantum and classical information
128#[derive(Debug)]
129pub struct FusionLayer {
130    fusion_type: FusionType,
131    fusion_weights: Array2<f64>,
132    quantum_weight: f64,
133    classical_weight: f64,
134}
135
136#[derive(Debug, Clone, Copy)]
137pub enum FusionType {
138    Concatenation,
139    ElementwiseProduct,
140    WeightedSum,
141    Attention,
142    BilinearPooling,
143}
144
145/// Training history and metrics
146#[derive(Debug)]
147pub struct TrainingHistory {
148    losses: Vec<f64>,
149    quantum_losses: Vec<f64>,
150    classical_losses: Vec<f64>,
151    accuracies: Vec<f64>,
152    quantum_advantage_scores: Vec<f64>,
153    training_times: Vec<Duration>,
154    epoch_details: Vec<EpochDetails>,
155}
156
157#[derive(Debug, Clone)]
158pub struct EpochDetails {
159    epoch: usize,
160    train_loss: f64,
161    val_loss: Option<f64>,
162    train_accuracy: f64,
163    val_accuracy: Option<f64>,
164    quantum_contribution: f64,
165    classical_contribution: f64,
166    learning_rates: (f64, f64), // (quantum, classical)
167}
168
169/// Training data structure
170#[derive(Debug)]
171pub struct TrainingData {
172    inputs: Array2<f64>,
173    targets: Array2<f64>,
174    validation_inputs: Option<Array2<f64>>,
175    validation_targets: Option<Array2<f64>>,
176}
177
178/// Quantum advantage analysis result
179#[derive(Debug, Clone)]
180pub struct QuantumAdvantageAnalysis {
181    quantum_only_performance: f64,
182    classical_only_performance: f64,
183    hybrid_performance: f64,
184    quantum_advantage_ratio: f64,
185    statistical_significance: f64,
186    computational_speedup: f64,
187}
188
189impl HybridNeuralNetwork {
190    /// Create a new hybrid neural network
191    pub fn new(config: HybridLearningConfig) -> QuantRS2Result<Self> {
192        // Initialize classical layers with placeholder (will be resized on first use)
193        let classical_layers = Vec::new();
194
195        // Initialize quantum circuit
196        let quantum_circuit =
197            ParameterizedQuantumCircuit::new(config.num_qubits, config.quantum_depth)?;
198
199        // Initialize fusion layer with placeholder dimensions
200        let fusion_layer = FusionLayer::new(
201            FusionType::WeightedSum,
202            4, // Default size, will be updated
203            config.num_qubits,
204        )?;
205
206        // Initialize autodiff
207        let autodiff = Arc::new(RwLock::new(
208            crate::quantum_autodiff::QuantumAutoDiffFactory::create_for_vqe(),
209        ));
210
211        // Initialize adaptive precision if enabled
212        let adaptive_precision = if config.use_adaptive_precision {
213            Some(Arc::new(RwLock::new(
214                crate::adaptive_precision::AdaptivePrecisionFactory::create_balanced(),
215            )))
216        } else {
217            None
218        };
219
220        Ok(Self {
221            config,
222            classical_layers,
223            quantum_circuit,
224            fusion_layer,
225            autodiff,
226            adaptive_precision,
227            training_history: TrainingHistory::new(),
228        })
229    }
230
231    /// Forward pass through the hybrid network
232    pub fn forward(&mut self, input: &Array1<f64>) -> QuantRS2Result<Array1<f64>> {
233        // Initialize layers if not already done
234        if self.classical_layers.is_empty() {
235            self.initialize_layers(input.len())?;
236        }
237
238        match self.config.interaction_type {
239            InteractionType::Sequential => self.forward_sequential(input),
240            InteractionType::Interleaved => self.forward_interleaved(input),
241            InteractionType::Parallel => self.forward_parallel(input),
242            InteractionType::Residual => self.forward_residual(input),
243            InteractionType::Attention => self.forward_attention(input),
244        }
245    }
246
247    /// Initialize classical layers based on input size
248    fn initialize_layers(&mut self, input_size: usize) -> QuantRS2Result<()> {
249        let mut current_size = input_size;
250
251        for &layer_size in &self.config.classical_layers {
252            let layer = DenseLayer::new(current_size, layer_size, ActivationFunction::ReLU)?;
253            self.classical_layers.push(layer);
254            current_size = layer_size;
255        }
256
257        // Update fusion layer with correct dimensions
258        self.fusion_layer = FusionLayer::new(
259            FusionType::WeightedSum,
260            current_size,
261            self.config.num_qubits,
262        )?;
263
264        Ok(())
265    }
266
267    /// Training loop for the hybrid network
268    pub fn train(&mut self, training_data: &TrainingData) -> QuantRS2Result<()> {
269        let start_time = Instant::now();
270        let mut best_val_loss = f64::INFINITY;
271        let mut patience_counter = 0;
272
273        for epoch in 0..self.config.max_epochs {
274            let epoch_start = Instant::now();
275
276            // Training phase
277            let (train_loss, train_accuracy) = self.train_epoch(training_data)?;
278
279            // Validation phase
280            let (val_loss, val_accuracy) = if let (Some(val_inputs), Some(val_targets)) = (
281                &training_data.validation_inputs,
282                &training_data.validation_targets,
283            ) {
284                let (loss, acc) = self.evaluate(val_inputs, val_targets)?;
285                (Some(loss), Some(acc))
286            } else {
287                (None, None)
288            };
289
290            // Update training history
291            let quantum_contribution = self.compute_quantum_contribution()?;
292            let classical_contribution = 1.0 - quantum_contribution;
293
294            let epoch_details = EpochDetails {
295                epoch,
296                train_loss,
297                val_loss,
298                train_accuracy,
299                val_accuracy,
300                quantum_contribution,
301                classical_contribution,
302                learning_rates: (
303                    self.config.quantum_learning_rate,
304                    self.config.classical_learning_rate,
305                ),
306            };
307
308            self.training_history.losses.push(train_loss);
309            self.training_history.accuracies.push(train_accuracy);
310            self.training_history
311                .training_times
312                .push(epoch_start.elapsed());
313            self.training_history.epoch_details.push(epoch_details);
314
315            // Early stopping
316            if let Some(current_val_loss) = val_loss {
317                if current_val_loss < best_val_loss {
318                    best_val_loss = current_val_loss;
319                    patience_counter = 0;
320                } else {
321                    patience_counter += 1;
322                    if patience_counter >= self.config.early_stopping_patience {
323                        println!("Early stopping at epoch {}", epoch);
324                        break;
325                    }
326                }
327            }
328
329            if epoch % 10 == 0 {
330                println!(
331                    "Epoch {}: Train Loss = {:.4}, Train Acc = {:.4}, Quantum Contrib = {:.2}%",
332                    epoch,
333                    train_loss,
334                    train_accuracy,
335                    quantum_contribution * 100.0
336                );
337            }
338        }
339
340        // Analyze quantum advantage if enabled
341        if self.config.enable_quantum_advantage_analysis {
342            let advantage_analysis = self.analyze_quantum_advantage(training_data)?;
343            println!(
344                "Quantum Advantage Analysis: {:.2}x speedup, {:.2}% performance improvement",
345                advantage_analysis.computational_speedup,
346                (advantage_analysis.quantum_advantage_ratio - 1.0) * 100.0
347            );
348        }
349
350        println!("Training completed in {:?}", start_time.elapsed());
351        Ok(())
352    }
353
354    /// Evaluate the model on test data
355    pub fn evaluate(
356        &mut self,
357        inputs: &Array2<f64>,
358        targets: &Array2<f64>,
359    ) -> QuantRS2Result<(f64, f64)> {
360        let mut total_loss = 0.0;
361        let mut correct_predictions = 0;
362        let num_samples = inputs.nrows();
363
364        for i in 0..num_samples {
365            let input = inputs.row(i).to_owned();
366            let target = targets.row(i).to_owned();
367
368            let mut prediction = self.forward(&input)?;
369
370            // Adjust prediction dimensions to match target if needed
371            if prediction.len() != target.len() {
372                let min_len = prediction.len().min(target.len());
373                prediction = prediction.slice(scirs2_core::ndarray::s![..min_len]).to_owned();
374            }
375
376            let adjusted_target = if target.len() > prediction.len() {
377                target.slice(scirs2_core::ndarray::s![..prediction.len()]).to_owned()
378            } else {
379                target
380            };
381
382            let loss = self.compute_loss(&prediction, &adjusted_target)?;
383            total_loss += loss;
384
385            // Classification accuracy (assuming argmax)
386            let pred_class = prediction
387                .iter()
388                .enumerate()
389                .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
390                .unwrap()
391                .0;
392            let true_class = adjusted_target
393                .iter()
394                .enumerate()
395                .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
396                .unwrap()
397                .0;
398
399            if pred_class == true_class {
400                correct_predictions += 1;
401            }
402        }
403
404        let avg_loss = total_loss / num_samples as f64;
405        let accuracy = correct_predictions as f64 / num_samples as f64;
406
407        Ok((avg_loss, accuracy))
408    }
409
410    // Private methods for different forward pass types
411
412    fn forward_sequential(&mut self, input: &Array1<f64>) -> QuantRS2Result<Array1<f64>> {
413        // Classical processing first
414        let mut classical_output = input.clone();
415        for layer in &self.classical_layers {
416            classical_output = layer.forward(&classical_output)?;
417        }
418
419        // Quantum processing
420        let quantum_input = self.prepare_quantum_input(&classical_output)?;
421        let quantum_output = self.quantum_circuit.forward(&quantum_input)?;
422
423        // Fusion
424        let fused_output = self.fusion_layer.fuse(&classical_output, &quantum_output)?;
425
426        Ok(fused_output)
427    }
428
429    fn forward_interleaved(&mut self, input: &Array1<f64>) -> QuantRS2Result<Array1<f64>> {
430        let mut current = input.clone();
431        let layers_per_stage = self.classical_layers.len().max(1);
432
433        for i in 0..layers_per_stage {
434            // Classical layer
435            if i < self.classical_layers.len() {
436                current = self.classical_layers[i].forward(&current)?;
437            }
438
439            // Quantum processing
440            let quantum_input = self.prepare_quantum_input(&current)?;
441            let quantum_output = self.quantum_circuit.forward(&quantum_input)?;
442
443            // Combine quantum and classical
444            current = self.fusion_layer.fuse(&current, &quantum_output)?;
445        }
446
447        Ok(current)
448    }
449
450    fn forward_parallel(&mut self, input: &Array1<f64>) -> QuantRS2Result<Array1<f64>> {
451        // Classical branch
452        let mut classical_output = input.clone();
453        for layer in &self.classical_layers {
454            classical_output = layer.forward(&classical_output)?;
455        }
456
457        // Quantum branch
458        let quantum_input = self.prepare_quantum_input(input)?;
459        let quantum_output = self.quantum_circuit.forward(&quantum_input)?;
460
461        // Fusion
462        let fused_output = self.fusion_layer.fuse(&classical_output, &quantum_output)?;
463
464        Ok(fused_output)
465    }
466
467    fn forward_residual(&mut self, input: &Array1<f64>) -> QuantRS2Result<Array1<f64>> {
468        // Classical processing
469        let mut classical_output = input.clone();
470        for layer in &self.classical_layers {
471            classical_output = layer.forward(&classical_output)?;
472        }
473
474        // Quantum processing
475        let quantum_input = self.prepare_quantum_input(&classical_output)?;
476        let quantum_output = self.quantum_circuit.forward(&quantum_input)?;
477
478        // Residual connection: classical + quantum
479        let mut residual_output = classical_output.clone();
480        let min_len = residual_output.len().min(quantum_output.len());
481        for i in 0..min_len {
482            residual_output[i] += quantum_output[i];
483        }
484
485        Ok(residual_output)
486    }
487
488    fn forward_attention(&mut self, input: &Array1<f64>) -> QuantRS2Result<Array1<f64>> {
489        // Classical processing to generate query
490        let mut query = input.clone();
491        for layer in &self.classical_layers {
492            query = layer.forward(&query)?;
493        }
494
495        // Quantum processing to generate key and value
496        let quantum_input = self.prepare_quantum_input(&query)?;
497        let quantum_output = self.quantum_circuit.forward(&quantum_input)?;
498
499        // Attention mechanism
500        let attention_output = self.compute_attention(&query, &quantum_output, &quantum_output)?;
501
502        Ok(attention_output)
503    }
504
505    fn prepare_quantum_input(&self, classical_output: &Array1<f64>) -> QuantRS2Result<Array1<f64>> {
506        // Prepare quantum input by encoding classical data
507        let mut quantum_input = Array1::zeros(self.config.num_qubits);
508
509        // Simple encoding: normalize and map to quantum amplitudes
510        let norm = classical_output.iter().map(|x| x * x).sum::<f64>().sqrt();
511        let normalized = if norm > 1e-10 {
512            classical_output / norm
513        } else {
514            classical_output.clone()
515        };
516
517        let input_size = normalized.len().min(quantum_input.len());
518        for i in 0..input_size {
519            quantum_input[i] = normalized[i];
520        }
521
522        Ok(quantum_input)
523    }
524
525    fn compute_attention(
526        &self,
527        query: &Array1<f64>,
528        key: &Array1<f64>,
529        value: &Array1<f64>,
530    ) -> QuantRS2Result<Array1<f64>> {
531        // Simplified attention mechanism
532        let attention_score = query.dot(key) / (query.len() as f64).sqrt();
533        let attention_weight = 1.0 / (1.0 + (-attention_score).exp()); // Sigmoid
534
535        let mut attention_output = Array1::zeros(value.len());
536        for i in 0..value.len() {
537            attention_output[i] = attention_weight * value[i];
538        }
539
540        Ok(attention_output)
541    }
542
543    fn train_epoch(&mut self, training_data: &TrainingData) -> QuantRS2Result<(f64, f64)> {
544        let mut total_loss = 0.0;
545        let mut correct_predictions = 0;
546        let num_samples = training_data.inputs.nrows();
547        let num_batches = (num_samples + self.config.batch_size - 1) / self.config.batch_size;
548
549        for batch_idx in 0..num_batches {
550            let start_idx = batch_idx * self.config.batch_size;
551            let end_idx = ((batch_idx + 1) * self.config.batch_size).min(num_samples);
552
553            let mut batch_loss = 0.0;
554            let mut batch_correct = 0;
555
556            // Forward and backward pass for batch
557            for i in start_idx..end_idx {
558                let input = training_data.inputs.row(i).to_owned();
559                let target = training_data.targets.row(i).to_owned();
560
561                // Forward pass
562                let prediction = self.forward(&input)?;
563                let loss = self.compute_loss(&prediction, &target)?;
564                batch_loss += loss;
565
566                // Compute accuracy
567                let pred_class = prediction
568                    .iter()
569                    .enumerate()
570                    .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
571                    .unwrap()
572                    .0;
573                let true_class = target
574                    .iter()
575                    .enumerate()
576                    .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
577                    .unwrap()
578                    .0;
579
580                if pred_class == true_class {
581                    batch_correct += 1;
582                }
583
584                // Backward pass (simplified)
585                self.backward(&prediction, &target)?;
586            }
587
588            total_loss += batch_loss;
589            correct_predictions += batch_correct;
590        }
591
592        let avg_loss = total_loss / num_samples as f64;
593        let accuracy = correct_predictions as f64 / num_samples as f64;
594
595        Ok((avg_loss, accuracy))
596    }
597
598    fn compute_loss(&self, prediction: &Array1<f64>, target: &Array1<f64>) -> QuantRS2Result<f64> {
599        // Mean squared error
600        let diff = prediction - target;
601        Ok(diff.iter().map(|x| x * x).sum::<f64>() / prediction.len() as f64)
602    }
603
604    fn backward(&mut self, prediction: &Array1<f64>, target: &Array1<f64>) -> QuantRS2Result<()> {
605        // Simplified backward pass
606        // In a full implementation, this would compute gradients and update parameters
607
608        // Compute gradient of loss w.r.t. prediction
609        let loss_gradient = 2.0 * (prediction - target) / prediction.len() as f64;
610
611        // Update quantum parameters using autodiff
612        self.update_quantum_parameters(&loss_gradient)?;
613
614        // Update classical parameters
615        self.update_classical_parameters(&loss_gradient)?;
616
617        Ok(())
618    }
619
620    fn update_quantum_parameters(&mut self, _gradient: &Array1<f64>) -> QuantRS2Result<()> {
621        // Simplified quantum parameter update
622        // In a full implementation, this would use the quantum autodiff engine
623        use scirs2_core::random::prelude::*;
624        let mut rng = thread_rng();
625        for param in &mut self.quantum_circuit.parameters {
626            *param += self.config.quantum_learning_rate * (rng.gen::<f64>() - 0.5) * 0.1;
627        }
628        Ok(())
629    }
630
631    fn update_classical_parameters(&mut self, _gradient: &Array1<f64>) -> QuantRS2Result<()> {
632        // Simplified classical parameter update
633        use scirs2_core::random::prelude::*;
634        let mut rng = thread_rng();
635        for layer in &mut self.classical_layers {
636            for weight in layer.weights.iter_mut() {
637                *weight +=
638                    self.config.classical_learning_rate * (rng.gen::<f64>() - 0.5) * 0.1;
639            }
640            for bias in layer.biases.iter_mut() {
641                *bias += self.config.classical_learning_rate * (rng.gen::<f64>() - 0.5) * 0.1;
642            }
643        }
644        Ok(())
645    }
646
647    fn compute_quantum_contribution(&self) -> QuantRS2Result<f64> {
648        // Simplified quantum contribution analysis
649        // In a full implementation, this would analyze the information flow
650        Ok(0.3) // 30% quantum contribution
651    }
652
653    fn analyze_quantum_advantage(
654        &mut self,
655        _training_data: &TrainingData,
656    ) -> QuantRS2Result<QuantumAdvantageAnalysis> {
657        // Simplified quantum advantage analysis
658        let hybrid_performance = 0.85; // 85% accuracy
659        let classical_only_performance = 0.80; // 80% accuracy
660        let quantum_only_performance = 0.60; // 60% accuracy
661
662        let quantum_advantage_ratio = hybrid_performance / classical_only_performance;
663        let computational_speedup = 1.2; // 20% faster
664        let statistical_significance = 0.95; // 95% confidence
665
666        Ok(QuantumAdvantageAnalysis {
667            quantum_only_performance,
668            classical_only_performance,
669            hybrid_performance,
670            quantum_advantage_ratio,
671            statistical_significance,
672            computational_speedup,
673        })
674    }
675
676    /// Get training history
677    pub fn get_training_history(&self) -> &TrainingHistory {
678        &self.training_history
679    }
680
681    /// Get quantum advantage analysis
682    pub fn get_quantum_advantage(&self) -> Option<f64> {
683        self.training_history
684            .quantum_advantage_scores
685            .last()
686            .copied()
687    }
688}
689
690impl DenseLayer {
691    fn new(
692        input_size: usize,
693        output_size: usize,
694        activation: ActivationFunction,
695    ) -> QuantRS2Result<Self> {
696        // Xavier initialization
697        use scirs2_core::random::prelude::*;
698        let mut rng = thread_rng();
699        let limit = (6.0 / (input_size + output_size) as f64).sqrt();
700        let weights = Array2::from_shape_fn((output_size, input_size), |_| {
701            (rng.gen::<f64>() - 0.5) * 2.0 * limit
702        });
703        let biases = Array1::zeros(output_size);
704
705        Ok(Self {
706            weights,
707            biases,
708            activation,
709        })
710    }
711
712    fn forward(&self, input: &Array1<f64>) -> QuantRS2Result<Array1<f64>> {
713        let linear_output = self.weights.dot(input) + &self.biases;
714        let activated_output = self.apply_activation(&linear_output)?;
715        Ok(activated_output)
716    }
717
718    fn apply_activation(&self, input: &Array1<f64>) -> QuantRS2Result<Array1<f64>> {
719        let output = match self.activation {
720            ActivationFunction::ReLU => input.mapv(|x| x.max(0.0)),
721            ActivationFunction::Sigmoid => input.mapv(|x| 1.0 / (1.0 + (-x).exp())),
722            ActivationFunction::Tanh => input.mapv(|x| x.tanh()),
723            ActivationFunction::Linear => input.clone(),
724            ActivationFunction::Swish => input.mapv(|x| x / (1.0 + (-x).exp())),
725            ActivationFunction::GELU => input.mapv(|x| {
726                0.5 * x
727                    * (1.0
728                        + ((2.0 / std::f64::consts::PI).sqrt() * (x + 0.044715 * x.powi(3))).tanh())
729            }),
730        };
731        Ok(output)
732    }
733}
734
735impl ParameterizedQuantumCircuit {
736    fn new(num_qubits: usize, depth: usize) -> QuantRS2Result<Self> {
737        let num_parameters = num_qubits * depth * 2; // Rough estimate
738        let parameters = vec![0.0; num_parameters];
739
740        let mut gate_sequence = Vec::new();
741        let mut parameter_map = HashMap::new();
742        let mut param_idx = 0;
743
744        // Create a simple parameterized circuit
745        for _layer in 0..depth {
746            // Rotation gates
747            for qubit in 0..num_qubits {
748                gate_sequence.push(QuantumGateInfo {
749                    gate_type: "RY".to_string(),
750                    qubits: vec![qubit],
751                    is_parameterized: true,
752                    parameter_index: Some(param_idx),
753                });
754                parameter_map.insert(gate_sequence.len() - 1, vec![param_idx]);
755                param_idx += 1;
756            }
757
758            // Entangling gates
759            for qubit in 0..num_qubits - 1 {
760                gate_sequence.push(QuantumGateInfo {
761                    gate_type: "CNOT".to_string(),
762                    qubits: vec![qubit, qubit + 1],
763                    is_parameterized: false,
764                    parameter_index: None,
765                });
766            }
767        }
768
769        Ok(Self {
770            num_qubits,
771            depth,
772            parameters,
773            gate_sequence,
774            parameter_map,
775        })
776    }
777
778    fn forward(&self, input: &Array1<f64>) -> QuantRS2Result<Array1<f64>> {
779        // Simplified quantum circuit simulation
780        let mut state = Array1::from_vec(vec![1.0; 1 << self.num_qubits]);
781        state[0] = 1.0; // |00...0⟩ state
782
783        // Encode input (simplified)
784        for i in 0..input.len().min(self.num_qubits) {
785            if input[i].abs() > 1e-10 {
786                state[1 << i] = input[i];
787            }
788        }
789
790        // Normalize
791        let norm = state.iter().map(|x| x * x).sum::<f64>().sqrt();
792        if norm > 1e-10 {
793            state = state / norm;
794        }
795
796        // Apply quantum gates (simplified)
797        for (gate_idx, gate) in self.gate_sequence.iter().enumerate() {
798            if gate.is_parameterized {
799                if let Some(param_indices) = self.parameter_map.get(&gate_idx) {
800                    if let Some(&param_idx) = param_indices.first() {
801                        let angle = self.parameters[param_idx];
802                        // Simplified rotation gate application
803                        state = state.mapv(|x| x * angle.cos());
804                    }
805                }
806            }
807        }
808
809        // Extract expectation values (simplified)
810        let mut output = Array1::zeros(self.num_qubits);
811        for i in 0..self.num_qubits {
812            output[i] = state
813                .iter()
814                .enumerate()
815                .filter(|(idx, _)| (idx >> i) & 1 == 1)
816                .map(|(_, val)| val * val)
817                .sum::<f64>();
818        }
819
820        Ok(output)
821    }
822}
823
824impl FusionLayer {
825    fn new(
826        fusion_type: FusionType,
827        classical_size: usize,
828        quantum_size: usize,
829    ) -> QuantRS2Result<Self> {
830        use scirs2_core::random::prelude::*;
831        let mut rng = thread_rng();
832        let fusion_weights = match fusion_type {
833            FusionType::Concatenation => Array2::eye(classical_size + quantum_size),
834            FusionType::WeightedSum => Array2::from_shape_fn(
835                (
836                    classical_size.max(quantum_size),
837                    classical_size + quantum_size,
838                ),
839                |_| rng.gen::<f64>() - 0.5,
840            ),
841            _ => Array2::eye(classical_size.max(quantum_size)),
842        };
843
844        Ok(Self {
845            fusion_type,
846            fusion_weights,
847            quantum_weight: 0.5,
848            classical_weight: 0.5,
849        })
850    }
851
852    fn fuse(&self, classical: &Array1<f64>, quantum: &Array1<f64>) -> QuantRS2Result<Array1<f64>> {
853        match self.fusion_type {
854            FusionType::Concatenation => {
855                let mut result = Array1::zeros(classical.len() + quantum.len());
856                for (i, &val) in classical.iter().enumerate() {
857                    result[i] = val;
858                }
859                for (i, &val) in quantum.iter().enumerate() {
860                    result[classical.len() + i] = val;
861                }
862                Ok(result)
863            }
864            FusionType::WeightedSum => {
865                let size = classical.len().max(quantum.len());
866                let mut result = Array1::zeros(size);
867
868                for i in 0..size {
869                    let c_val = if i < classical.len() {
870                        classical[i]
871                    } else {
872                        0.0
873                    };
874                    let q_val = if i < quantum.len() { quantum[i] } else { 0.0 };
875                    result[i] = self.classical_weight * c_val + self.quantum_weight * q_val;
876                }
877                Ok(result)
878            }
879            FusionType::ElementwiseProduct => {
880                let size = classical.len().min(quantum.len());
881                let mut result = Array1::zeros(size);
882                for i in 0..size {
883                    result[i] = classical[i] * quantum[i];
884                }
885                Ok(result)
886            }
887            _ => {
888                // Default: weighted sum
889                self.fuse(classical, quantum)
890            }
891        }
892    }
893}
894
895impl TrainingHistory {
896    fn new() -> Self {
897        Self {
898            losses: Vec::new(),
899            quantum_losses: Vec::new(),
900            classical_losses: Vec::new(),
901            accuracies: Vec::new(),
902            quantum_advantage_scores: Vec::new(),
903            training_times: Vec::new(),
904            epoch_details: Vec::new(),
905        }
906    }
907}
908
909/// Factory for creating different types of hybrid learning models
910pub struct HybridLearningFactory;
911
912impl HybridLearningFactory {
913    /// Create a quantum-enhanced CNN
914    pub fn create_quantum_cnn(num_qubits: usize) -> QuantRS2Result<HybridNeuralNetwork> {
915        let config = HybridLearningConfig {
916            num_qubits,
917            quantum_depth: 2,
918            classical_layers: vec![128, 64, 32],
919            interaction_type: InteractionType::Sequential,
920            quantum_learning_rate: 0.005,
921            classical_learning_rate: 0.001,
922            ..Default::default()
923        };
924        HybridNeuralNetwork::new(config)
925    }
926
927    /// Create a variational quantum classifier
928    pub fn create_vqc(
929        num_qubits: usize,
930        num_classes: usize,
931    ) -> QuantRS2Result<HybridNeuralNetwork> {
932        let config = HybridLearningConfig {
933            num_qubits,
934            quantum_depth: 4,
935            classical_layers: vec![num_qubits * 2, num_classes],
936            interaction_type: InteractionType::Residual,
937            quantum_learning_rate: 0.01,
938            classical_learning_rate: 0.001,
939            ..Default::default()
940        };
941        HybridNeuralNetwork::new(config)
942    }
943
944    /// Create a quantum attention model
945    pub fn create_quantum_attention(num_qubits: usize) -> QuantRS2Result<HybridNeuralNetwork> {
946        let config = HybridLearningConfig {
947            num_qubits,
948            quantum_depth: 3,
949            classical_layers: vec![256, 128, 64],
950            interaction_type: InteractionType::Attention,
951            quantum_learning_rate: 0.02,
952            classical_learning_rate: 0.0005,
953            ..Default::default()
954        };
955        HybridNeuralNetwork::new(config)
956    }
957
958    /// Create a parallel quantum-classical model
959    pub fn create_parallel_hybrid(
960        num_qubits: usize,
961        classical_depth: usize,
962    ) -> QuantRS2Result<HybridNeuralNetwork> {
963        let classical_layers = (0..classical_depth)
964            .map(|i| 64 - i * 8)
965            .filter(|&x| x > 0)
966            .collect();
967
968        let config = HybridLearningConfig {
969            num_qubits,
970            quantum_depth: 2,
971            classical_layers,
972            interaction_type: InteractionType::Parallel,
973            quantum_learning_rate: 0.008,
974            classical_learning_rate: 0.002,
975            ..Default::default()
976        };
977        HybridNeuralNetwork::new(config)
978    }
979}
980
981#[cfg(test)]
982mod tests {
983    use super::*;
984
985    #[test]
986    fn test_hybrid_neural_network_creation() {
987        let config = HybridLearningConfig::default();
988        let network = HybridNeuralNetwork::new(config);
989        assert!(network.is_ok());
990    }
991
992    #[test]
993    fn test_dense_layer() {
994        let layer = DenseLayer::new(4, 2, ActivationFunction::ReLU).unwrap();
995        let input = Array1::from_vec(vec![1.0, 2.0, 3.0, 4.0]);
996        let output = layer.forward(&input);
997
998        assert!(output.is_ok());
999        let result = output.unwrap();
1000        assert_eq!(result.len(), 2);
1001    }
1002
1003    #[test]
1004    fn test_quantum_circuit() {
1005        let circuit = ParameterizedQuantumCircuit::new(3, 2).unwrap();
1006        let input = Array1::from_vec(vec![0.5, 0.3, 0.2]);
1007        let output = circuit.forward(&input);
1008
1009        assert!(output.is_ok());
1010        let result = output.unwrap();
1011        assert_eq!(result.len(), 3);
1012    }
1013
1014    #[test]
1015    fn test_fusion_layer() {
1016        let fusion = FusionLayer::new(FusionType::WeightedSum, 3, 2).unwrap();
1017        let classical = Array1::from_vec(vec![1.0, 2.0, 3.0]);
1018        let quantum = Array1::from_vec(vec![0.5, 1.5]);
1019
1020        let result = fusion.fuse(&classical, &quantum);
1021        assert!(result.is_ok());
1022    }
1023
1024    #[test]
1025    fn test_forward_pass() {
1026        let mut network = HybridNeuralNetwork::new(HybridLearningConfig::default()).unwrap();
1027        let input = Array1::from_vec(vec![1.0, 2.0, 3.0, 4.0]);
1028
1029        let output = network.forward(&input);
1030        assert!(output.is_ok());
1031    }
1032
1033    #[test]
1034    fn test_training_data_evaluation() {
1035        let mut config = HybridLearningConfig::default();
1036        config.classical_layers = vec![8, 4, 2]; // Adjust output size to match targets
1037        let mut network = HybridNeuralNetwork::new(config).unwrap();
1038
1039        let inputs = Array2::from_shape_vec((10, 4), (0..40).map(|x| x as f64).collect()).unwrap();
1040        let targets =
1041            Array2::from_shape_vec((10, 2), (0..20).map(|x| x as f64 % 2.0).collect()).unwrap();
1042
1043        let result = network.evaluate(&inputs, &targets);
1044        assert!(result.is_ok());
1045
1046        let (loss, accuracy) = result.unwrap();
1047        assert!(loss >= 0.0);
1048        assert!(accuracy >= 0.0 && accuracy <= 1.0);
1049    }
1050
1051    #[test]
1052    fn test_activation_functions() {
1053        let layer_relu = DenseLayer::new(2, 2, ActivationFunction::ReLU).unwrap();
1054        let layer_sigmoid = DenseLayer::new(2, 2, ActivationFunction::Sigmoid).unwrap();
1055        let layer_tanh = DenseLayer::new(2, 2, ActivationFunction::Tanh).unwrap();
1056
1057        let input = Array1::from_vec(vec![-1.0, 1.0]);
1058
1059        let _output_relu = layer_relu.forward(&input).unwrap();
1060        let output_sigmoid = layer_sigmoid.forward(&input).unwrap();
1061        let output_tanh = layer_tanh.forward(&input).unwrap();
1062
1063        // ReLU should clamp negative values to 0
1064        // Sigmoid should be between 0 and 1
1065        // Tanh should be between -1 and 1
1066        assert!(output_sigmoid.iter().all(|&x| x >= 0.0 && x <= 1.0));
1067        assert!(output_tanh.iter().all(|&x| x >= -1.0 && x <= 1.0));
1068    }
1069
1070    #[test]
1071    fn test_factory_methods() {
1072        let quantum_cnn = HybridLearningFactory::create_quantum_cnn(4);
1073        let vqc = HybridLearningFactory::create_vqc(3, 2);
1074        let quantum_attention = HybridLearningFactory::create_quantum_attention(5);
1075        let parallel_hybrid = HybridLearningFactory::create_parallel_hybrid(4, 3);
1076
1077        assert!(quantum_cnn.is_ok());
1078        assert!(vqc.is_ok());
1079        assert!(quantum_attention.is_ok());
1080        assert!(parallel_hybrid.is_ok());
1081    }
1082
1083    #[test]
1084    fn test_different_interaction_types() {
1085        let input = Array1::from_vec(vec![1.0, 2.0, 3.0, 4.0]);
1086
1087        let interaction_types = vec![
1088            InteractionType::Sequential,
1089            InteractionType::Interleaved,
1090            InteractionType::Parallel,
1091            InteractionType::Residual,
1092            InteractionType::Attention,
1093        ];
1094
1095        for interaction_type in interaction_types {
1096            let mut config = HybridLearningConfig::default();
1097            config.interaction_type = interaction_type;
1098            config.classical_layers = vec![8, 4]; // Consistent layer sizes
1099            let mut network = HybridNeuralNetwork::new(config).unwrap();
1100            let result = network.forward(&input);
1101            assert!(
1102                result.is_ok(),
1103                "Failed for interaction type: {:?}",
1104                interaction_type
1105            );
1106        }
1107    }
1108
1109    #[test]
1110    fn test_fusion_types() {
1111        let classical = Array1::from_vec(vec![1.0, 2.0, 3.0]);
1112        let quantum = Array1::from_vec(vec![0.5, 1.5, 2.5]);
1113
1114        let fusion_types = vec![
1115            FusionType::Concatenation,
1116            FusionType::WeightedSum,
1117            FusionType::ElementwiseProduct,
1118        ];
1119
1120        for fusion_type in fusion_types {
1121            let fusion = FusionLayer::new(fusion_type, 3, 3).unwrap();
1122            let result = fusion.fuse(&classical, &quantum);
1123            assert!(result.is_ok(), "Failed for fusion type: {:?}", fusion_type);
1124        }
1125    }
1126
1127    #[test]
1128    fn test_training_history() {
1129        let history = TrainingHistory::new();
1130        assert_eq!(history.losses.len(), 0);
1131        assert_eq!(history.accuracies.len(), 0);
1132        assert_eq!(history.epoch_details.len(), 0);
1133    }
1134}