-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathiron_learn_integration.rs
More file actions
783 lines (666 loc) · 26 KB
/
iron_learn_integration.rs
File metadata and controls
783 lines (666 loc) · 26 KB
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
//! Iron Learn integration for enhanced GPU-accelerated machine learning
//!
//! This module provides integration with the iron_learn library for:
//! - GPU-accelerated tensor operations
//! - Linear and logistic regression with CUDA support
//! - Complex number arithmetic for signal processing
//! - Type-safe machine learning operations
use serde::{Deserialize, Serialize};
use std::ops::{Add, Mul, Sub};
/// Represents a multi-dimensional array of f64 values.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Tensor {
pub shape: Vec<usize>,
pub data: Vec<f64>,
}
impl Tensor {
/// Creates a new Tensor with the given shape and data.
pub fn new(shape: Vec<usize>, data: Vec<f64>) -> Result<Self, String> {
if shape.iter().product::<usize>() != data.len() {
return Err("Data length does not match tensor shape".to_string());
}
Ok(Tensor { shape, data })
}
/// Returns the data of the tensor.
pub fn get_data(&self) -> Vec<f64> {
self.data.clone()
}
/// Performs element-wise addition with another tensor.
pub fn add(&self, other: &Tensor) -> Result<Tensor, String> {
if self.shape != other.shape {
return Err("Tensor shapes do not match for addition".to_string());
}
let data: Vec<f64> = self.data.iter().zip(&other.data).map(|(a, b)| a + b).collect();
Ok(Tensor { shape: self.shape.clone(), data })
}
/// Performs element-wise subtraction with another tensor.
pub fn sub(&self, other: &Tensor) -> Result<Tensor, String> {
if self.shape != other.shape {
return Err("Tensor shapes do not match for subtraction".to_string());
}
let data: Vec<f64> = self.data.iter().zip(&other.data).map(|(a, b)| a - b).collect();
Ok(Tensor { shape: self.shape.clone(), data })
}
/// Performs element-wise multiplication with another tensor.
pub fn mul(&self, other: &Tensor) -> Result<Tensor, String> {
if self.shape != other.shape {
return Err("Tensor shapes do not match for multiplication".to_string());
}
let data: Vec<f64> = self.data.iter().zip(&other.data).map(|(a, b)| a * b).collect();
Ok(Tensor { shape: self.shape.clone(), data })
}
/// Performs scalar multiplication.
pub fn scalar_mul(&self, scalar: f64) -> Tensor {
let data: Vec<f64> = self.data.iter().map(|&x| x * scalar).collect();
Tensor { shape: self.shape.clone(), data }
}
/// Computes the dot product of two 1D tensors.
pub fn dot(&self, other: &Tensor) -> Result<f64, String> {
if self.shape.len() != 1 || other.shape.len() != 1 || self.shape[0] != other.shape[0] {
return Err("Tensors must be 1D and have the same length for dot product".to_string());
}
Ok(self.data.iter().zip(&other.data).map(|(a, b)| a * b).sum())
}
/// Computes the matrix multiplication of two 2D tensors.
pub fn matmul(&self, other: &Tensor) -> Result<Tensor, String> {
if self.shape.len() != 2 || other.shape.len() != 2 {
return Err("Tensors must be 2D for matrix multiplication".to_string());
}
if self.shape[1] != other.shape[0] {
return Err("Inner dimensions must match for matrix multiplication".to_string());
}
let m = self.shape[0];
let k = self.shape[1];
let n = other.shape[1];
let mut result_data = vec![0.0; m * n];
for i in 0..m {
for j in 0..n {
for l in 0..k {
result_data[i * n + j] += self.data[i * k + l] * other.data[l * n + j];
}
}
}
Tensor::new(vec![m, n], result_data)
}
/// Transposes a 2D tensor.
pub fn transpose(&self) -> Result<Tensor, String> {
if self.shape.len() != 2 {
return Err("Tensor must be 2D for transpose".to_string());
}
let m = self.shape[0];
let n = self.shape[1];
let mut transposed_data = vec![0.0; n * m];
for i in 0..m {
for j in 0..n {
transposed_data[j * m + i] = self.data[i * n + j];
}
}
Tensor::new(vec![n, m], transposed_data)
}
/// Applies the sigmoid function element-wise.
pub fn sigmoid(&self) -> Tensor {
let data: Vec<f64> = self.data.iter().map(|&x| 1.0 / (1.0 + (-x).exp())).collect();
Tensor { shape: self.shape.clone(), data }
}
/// Computes the mean squared error between two tensors.
pub fn mse(&self, other: &Tensor) -> Result<f64, String> {
if self.shape != other.shape {
return Err("Tensor shapes do not match for MSE calculation".to_string());
}
let sum_sq_diff: f64 = self.data.iter().zip(&other.data).map(|(a, b)| (a - b).powi(2)).sum();
Ok(sum_sq_diff / self.data.len() as f64)
}
}
/// Represents a complex number.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Complex {
pub re: f64,
pub im: f64,
}
impl Complex {
pub fn new(re: f64, im: f64) -> Self {
Complex { re, im }
}
pub fn conj(&self) -> Self {
Complex::new(self.re, -self.im)
}
pub fn norm_sq(&self) -> f64 {
self.re * self.re + self.im * self.im
}
}
impl Add for Complex {
type Output = Self;
fn add(self, other: Self) -> Self {
Complex::new(self.re + other.re, self.im + other.im)
}
}
impl Sub for Complex {
type Output = Self;
fn sub(self, other: Self) -> Self {
Complex::new(self.re - other.re, self.im - other.im)
}
}
impl Mul for Complex {
type Output = Self;
fn mul(self, other: Self) -> Self {
Complex::new(
self.re * other.re - self.im * other.im,
self.re * other.im + self.im * other.re,
)
}
}
/// Performs linear regression.
pub fn linear_regression(
x: &Tensor,
y: &Tensor,
weights: &Tensor,
learning_rate: f64,
) -> Result<Tensor, String> {
let predictions = predict_linear(x, weights)?;
let errors = y.sub(&predictions)?;
let gradient = x.transpose()?.matmul(&errors)?.scalar_mul(2.0 / x.shape[0] as f64);
weights.add(&gradient.scalar_mul(learning_rate))
}
/// Predicts values using a linear model.
pub fn predict_linear(x: &Tensor, weights: &Tensor) -> Result<Tensor, String> {
x.matmul(weights)
}
/// Performs logistic regression.
pub fn logistic_regression(
x: &Tensor,
y: &Tensor,
weights: &Tensor,
learning_rate: f64,
) -> Result<Tensor, String> {
let predictions = predict_logistic(x, weights)?;
let errors = y.sub(&predictions)?;
let gradient = x.transpose()?.matmul(&errors)?.scalar_mul(1.0 / x.shape[0] as f64);
weights.add(&gradient.scalar_mul(learning_rate))
}
/// Predicts values using a logistic model.
pub fn predict_logistic(x: &Tensor, weights: &Tensor) -> Result<Tensor, String> {
Ok(x.matmul(weights)?.sigmoid())
}
/// Placeholder for running logistic regression on CUDA.
pub fn run_logistics_cuda(
_x: &Tensor,
_y: &Tensor,
_weights: &Tensor,
_learning_rate: f64,
) -> Result<Tensor, String> {
Err("CUDA not yet implemented for logistic regression".to_string())
}
use std::collections::HashMap;
/// Configuration for Iron Learn ML operations
#[derive(Serialize, Deserialize, Clone)]
pub struct IronLearnConfig {
pub learning_rate: f64,
pub epochs: usize,
pub use_gpu: bool,
pub regularization: f64,
pub batch_size: usize,
}
impl Default for IronLearnConfig {
fn default() -> Self {
Self {
learning_rate: 0.01,
epochs: 1000,
use_gpu: true,
regularization: 0.001,
batch_size: 32,
}
}
}
/// Iron Learn enhanced ML processor
pub struct IronLearnProcessor {
config: IronLearnConfig,
models: HashMap<String, IronLearnModel>,
training_history: Vec<TrainingMetrics>,
}
/// Iron Learn model wrapper
#[derive(Serialize, Deserialize, Clone)]
pub struct IronLearnModel {
pub model_type: String, // "linear", "logistic", "neural"
pub weights: Vec<f64>,
pub input_shape: Vec<usize>,
pub output_shape: Vec<usize>,
pub feature_names: Vec<String>,
pub training_metrics: TrainingMetrics,
}
/// Training metrics and performance data
#[derive(Serialize, Deserialize, Clone)]
pub struct TrainingMetrics {
pub epochs_completed: usize,
pub final_loss: f64,
pub accuracy: f64,
pub precision: f64,
pub recall: f64,
pub f1_score: f64,
pub training_time_ms: u64,
}
/// Complex signal data for biometric processing
#[derive(Serialize, Deserialize)]
pub struct ComplexSignal {
pub real: Vec<f64>,
pub imaginary: Vec<f64>,
pub sampling_rate: f64,
pub signal_type: String, // "eeg", "emg", "ecg"
}
impl IronLearnProcessor {
/// Create a new Iron Learn processor
pub fn new(config: IronLearnConfig) -> Self {
Self {
config,
models: HashMap::new(),
training_history: Vec::new(),
}
}
/// Train a linear regression model on biometric data
#[cfg(feature = "ai-ml")]
pub fn train_linear_model(
&mut self,
model_name: &str,
features: &[Vec<f64>],
targets: &[f64],
feature_names: Vec<String>,
) -> Result<IronLearnModel, Box<dyn std::error::Error>> {
// Validate input dimensions
if features.is_empty() || targets.is_empty() {
return Err("Empty training data".into());
}
let n_samples = features.len();
let n_features = features[0].len();
if targets.len() != n_samples {
return Err("Mismatched samples and targets".into());
}
// Flatten features for tensor creation
let mut flattened_features = Vec::new();
for sample in features {
if sample.len() != n_features {
return Err("Inconsistent feature dimensions".into());
}
flattened_features.extend_from_slice(sample);
}
// Create tensors
let x_tensor = Tensor::new(vec![n_samples, n_features], flattened_features)?;
let y_tensor = Tensor::new(vec![n_samples, 1], targets.to_vec())?;
// Initialize weights with zeros
let mut weights = Tensor::new(vec![n_features + 1, 1], vec![0.0; n_features + 1])?;
let start_time = std::time::Instant::now();
// Train using linear regression
for epoch in 0..self.config.epochs {
weights = linear_regression(&x_tensor, &y_tensor, &weights, self.config.learning_rate)?;
if epoch % 100 == 0 {
// Calculate current loss for monitoring
let predictions = predict_linear(&x_tensor, &weights)?;
let loss = self.calculate_mse_loss(&predictions, targets);
web_sys::console::log_1(&format!("Epoch {}: Loss = {:.6}", epoch, loss).into());
}
}
let training_time = start_time.elapsed().as_millis() as u64;
// Extract trained weights
let trained_weights = weights.get_data();
// Calculate final metrics
let final_predictions = predict_linear(&x_tensor, &weights)?;
let final_loss = self.calculate_mse_loss(&final_predictions, targets);
let accuracy = self.calculate_r2_score(&final_predictions, targets);
let metrics = TrainingMetrics {
epochs_completed: self.config.epochs,
final_loss,
accuracy,
precision: 0.0, // Not applicable for regression
recall: 0.0,
f1_score: 0.0,
training_time_ms: training_time,
};
let model = IronLearnModel {
model_type: "linear".to_string(),
weights: trained_weights,
input_shape: vec![n_features],
output_shape: vec![1],
feature_names,
training_metrics: metrics.clone(),
};
self.models.insert(model_name.to_string(), model.clone());
self.training_history.push(metrics);
Ok(model)
}
/// Train a logistic regression model for classification
#[cfg(feature = "ai-ml")]
pub fn train_logistic_model(
&mut self,
model_name: &str,
features: &[Vec<f64>],
labels: &[f64],
feature_names: Vec<String>,
) -> Result<IronLearnModel, Box<dyn std::error::Error>> {
// Validate input dimensions
if features.is_empty() || labels.is_empty() {
return Err("Empty training data".into());
}
let n_samples = features.len();
let n_features = features[0].len();
if labels.len() != n_samples {
return Err("Mismatched samples and labels".into());
}
// Validate binary labels
for &label in labels {
if label != 0.0 && label != 1.0 {
return Err("Logistic regression requires binary labels (0 or 1)".into());
}
}
// Flatten features for tensor creation
let mut flattened_features = Vec::new();
for sample in features {
if sample.len() != n_features {
return Err("Inconsistent feature dimensions".into());
}
flattened_features.extend_from_slice(sample);
}
// Create tensors
let x_tensor = Tensor::new(vec![n_samples, n_features], flattened_features)?;
let y_tensor = Tensor::new(vec![n_samples, 1], labels.to_vec())?;
// Initialize weights with small random values
let mut weights = Tensor::new(vec![n_features + 1, 1], self.initialize_random_weights(n_features + 1))?;
let start_time = std::time::Instant::now();
// Train using logistic regression
for epoch in 0..self.config.epochs {
weights = logistic_regression(&x_tensor, &y_tensor, &weights, self.config.learning_rate)?;
if epoch % 100 == 0 {
// Calculate current metrics for monitoring
let predictions = predict_logistic(&x_tensor, &weights)?;
let accuracy = self.calculate_binary_accuracy(&predictions, labels);
web_sys::console::log_1(&format!("Epoch {}: Accuracy = {:.4}", epoch, accuracy).into());
}
}
let training_time = start_time.elapsed().as_millis() as u64;
// Extract trained weights
let trained_weights = weights.get_data();
// Calculate final metrics
let final_predictions = predict_logistic(&x_tensor, &weights)?;
let final_loss = self.calculate_log_loss(&final_predictions, labels);
let accuracy = self.calculate_binary_accuracy(&final_predictions, labels);
let (precision, recall, f1) = self.calculate_classification_metrics(&final_predictions, labels);
let metrics = TrainingMetrics {
epochs_completed: self.config.epochs,
final_loss,
accuracy,
precision,
recall,
f1_score: f1,
training_time_ms: training_time,
};
let model = IronLearnModel {
model_type: "logistic".to_string(),
weights: trained_weights,
input_shape: vec![n_features],
output_shape: vec![1],
feature_names,
training_metrics: metrics.clone(),
};
self.models.insert(model_name.to_string(), model.clone());
self.training_history.push(metrics);
Ok(model)
}
/// Process complex biometric signals using complex number arithmetic
#[cfg(feature = "ai-ml")]
pub fn process_complex_signal(
&self,
signal: ComplexSignal,
) -> Result<ComplexAnalysis, Box<dyn std::error::Error>> {
// Convert to complex numbers
let complex_data: Vec<Complex> = signal.real
.iter()
.zip(signal.imaginary.iter())
.map(|(&r, &i)| Complex::new(r, i))
.collect();
// Perform FFT-like analysis (simplified)
let frequencies = self.extract_frequencies(&complex_data, signal.sampling_rate)?;
let power_spectrum = self.calculate_power_spectrum(&frequencies)?;
// Find dominant frequency
let (dominant_freq, max_power) = power_spectrum
.iter()
.enumerate()
.max_by(|(_, &power1), (_, &power2)| power1.partial_cmp(&power2).unwrap())
.map(|(idx, &power)| (idx as f64 * signal.sampling_rate / complex_data.len() as f64, power))
.unwrap_or((0.0, 0.0));
Ok(ComplexAnalysis {
dominant_frequency: dominant_freq,
max_power,
average_power: power_spectrum.iter().sum::<f64>() / power_spectrum.len() as f64,
signal_type: signal.signal_type,
frequency_resolution: signal.sampling_rate / complex_data.len() as f64,
})
}
/// Predict using a trained model
#[cfg(feature = "ai-ml")]
pub fn predict(&self, model_name: &str, features: &[f64]) -> Result<f64, Box<dyn std::error::Error>> {
let model = self.models.get(model_name).ok_or("Model not found")?;
if features.len() != model.input_shape[0] {
return Err(format!("Expected {} features, got {}", model.input_shape[0], features.len()).into());
}
// Create feature tensor
let x_tensor = Tensor::new(vec![1, features.len()], features.to_vec())?;
// Create weight tensor from stored weights
let weights_tensor = Tensor::new(vec![model.weights.len(), 1], model.weights.clone())?;
match model.model_type.as_str() {
"linear" => {
let prediction = predict_linear(&x_tensor, &weights_tensor)?;
Ok(prediction.get_data()[0])
}
"logistic" => {
let prediction = predict_logistic(&x_tensor, &weights_tensor)?;
Ok(prediction.get_data()[0])
}
_ => Err("Unsupported model type".into()),
}
}
/// Get model performance metrics
pub fn get_model_metrics(&self, model_name: &str) -> Option<&TrainingMetrics> {
self.models.get(model_name).map(|model| &model.training_metrics)
}
/// Get all trained models
pub fn get_models(&self) -> &HashMap<String, IronLearnModel> {
&self.models
}
/// Clear all models and history
pub fn clear_models(&mut self) {
self.models.clear();
self.training_history.clear();
}
// Helper methods
fn calculate_mse_loss(&self, predictions: &Tensor, targets: &[f64]) -> f64 {
let pred_data = predictions.get_data();
let mut sum_squared_error = 0.0;
for (i, &target) in targets.iter().enumerate() {
if i < pred_data.len() {
let error = pred_data[i] - target;
sum_squared_error += error * error;
}
}
sum_squared_error / targets.len() as f64
}
fn calculate_log_loss(&self, predictions: &Tensor, targets: &[f64]) -> f64 {
let pred_data = predictions.get_data();
let mut log_loss = 0.0;
for (i, &target) in targets.iter().enumerate() {
if i < pred_data.len() {
let pred = pred_data[i].max(1e-15).min(1.0 - 1e-15); // Clip to avoid log(0)
log_loss -= target * pred.ln() + (1.0 - target) * (1.0 - pred).ln();
}
}
log_loss / targets.len() as f64
}
fn calculate_r2_score(&self, predictions: &Tensor, targets: &[f64]) -> f64 {
let pred_data = predictions.get_data();
let mean_target = targets.iter().sum::<f64>() / targets.len() as f64;
let mut total_sum_squares = 0.0;
let mut residual_sum_squares = 0.0;
for (i, &target) in targets.iter().enumerate() {
if i < pred_data.len() {
let target_deviation = target - mean_target;
total_sum_squares += target_deviation * target_deviation;
let residual = target - pred_data[i];
residual_sum_squares += residual * residual;
}
}
1.0 - (residual_sum_squares / total_sum_squares)
}
fn calculate_binary_accuracy(&self, predictions: &Tensor, targets: &[f64]) -> f64 {
let pred_data = predictions.get_data();
let mut correct = 0;
for (i, &target) in targets.iter().enumerate() {
if i < pred_data.len() {
let pred = if pred_data[i] >= 0.5 { 1.0 } else { 0.0 };
if (pred - target).abs() < 0.001 {
correct += 1;
}
}
}
correct as f64 / targets.len() as f64
}
fn calculate_classification_metrics(&self, predictions: &Tensor, targets: &[f64]) -> (f64, f64, f64) {
let pred_data = predictions.get_data();
let mut true_positives = 0;
let mut false_positives = 0;
let mut false_negatives = 0;
for (i, &target) in targets.iter().enumerate() {
if i < pred_data.len() {
let pred = if pred_data[i] >= 0.5 { 1.0 } else { 0.0 };
if pred == 1.0 && target == 1.0 {
true_positives += 1;
} else if pred == 1.0 && target == 0.0 {
false_positives += 1;
} else if pred == 0.0 && target == 1.0 {
false_negatives += 1;
}
}
}
let precision = if true_positives + false_positives > 0 {
true_positives as f64 / (true_positives + false_positives) as f64
} else {
0.0
};
let recall = if true_positives + false_negatives > 0 {
true_positives as f64 / (true_positives + false_negatives) as f64
} else {
0.0
};
let f1 = if precision + recall > 0.0 {
2.0 * precision * recall / (precision + recall)
} else {
0.0
};
(precision, recall, f1)
}
fn initialize_random_weights(&self, size: usize) -> Vec<f64> {
let mut weights = Vec::with_capacity(size);
for _ in 0..size {
weights.push((js_sys::Math::random() as f64 - 0.5) * 0.1);
}
weights
}
fn extract_frequencies(&self, complex_data: &[Complex], sampling_rate: f64) -> Result<Vec<Complex>, Box<dyn std::error::Error>> {
// Simplified frequency extraction - would use proper FFT in production
let mut frequencies = Vec::new();
let n = complex_data.len();
for k in 0..n {
let mut sum = Complex::new(0.0, 0.0);
for (t, &sample) in complex_data.iter().enumerate() {
let angle = -2.0 * std::f64::consts::PI * k as f64 * t as f64 / n as f64;
let twiddle = Complex::new(angle.cos(), angle.sin());
sum = sum + sample * twiddle;
}
frequencies.push(sum);
}
Ok(frequencies)
}
fn calculate_power_spectrum(&self, frequencies: &[Complex]) -> Result<Vec<f64>, Box<dyn std::error::Error>> {
Ok(frequencies.iter().map(|&freq| {
let real = freq.re;
let imag = freq.im;
real * real + imag * imag
}).collect())
}
}
/// Complex signal analysis results
#[derive(Serialize, Deserialize)]
pub struct ComplexAnalysis {
pub dominant_frequency: f64,
pub max_power: f64,
pub average_power: f64,
pub signal_type: String,
pub frequency_resolution: f64,
}
/// Integration with enhanced WebGPU engine
impl IronLearnProcessor {
/// Create processor with biometric-specific configuration
pub fn new_biometric() -> Self {
let config = IronLearnConfig {
learning_rate: 0.001,
epochs: 500,
use_gpu: true,
regularization: 0.0001,
batch_size: 16,
};
Self::new(config)
}
/// Train emotion classification model from biometric data
pub fn train_emotion_classifier(
&mut self,
model_name: &str,
eeg_features: &[Vec<f64>],
emotion_labels: &[String],
) -> Result<IronLearnModel, Box<dyn std::error::Error>> {
// Convert emotion labels to binary format
let mut binary_labels = Vec::new();
for emotion in emotion_labels {
// Simple binary classification: relaxed vs stressed
let label = match emotion.as_str() {
"relaxed" | "calm" | "peaceful" => 0.0,
"stressed" | "anxious" | "tense" => 1.0,
_ => 0.5, // neutral
};
binary_labels.push(label);
}
let feature_names = vec![
"alpha_power".to_string(),
"beta_power".to_string(),
"theta_power".to_string(),
"gamma_power".to_string(),
"dominant_frequency".to_string(),
"spectral_entropy".to_string(),
];
self.train_logistic_model(model_name, eeg_features, &binary_labels, feature_names)
}
}
#[cfg(test)]
mod tests {
use super::*;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn test_iron_learn_config() {
let config = IronLearnConfig::default();
assert_eq!(config.learning_rate, 0.01);
assert_eq!(config.epochs, 1000);
assert!(config.use_gpu);
}
#[wasm_bindgen_test]
fn test_iron_learn_processor_creation() {
let processor = IronLearnProcessor::new(IronLearnConfig::default());
assert!(processor.models.is_empty());
assert!(processor.training_history.is_empty());
}
#[wasm_bindgen_test]
fn test_complex_signal_creation() {
let signal = ComplexSignal {
real: vec![1.0, 2.0, 3.0],
imaginary: vec![0.1, 0.2, 0.3],
sampling_rate: 256.0,
signal_type: "eeg".to_string(),
};
assert_eq!(signal.real.len(), 3);
assert_eq!(signal.sampling_rate, 256.0);
assert_eq!(signal.signal_type, "eeg");
}
}