Files
rustytorch/crates/models/rtx-timeseries/examples/dyn_trait_demo.rs
T
2026-03-04 00:08:42 +00:00

60 lines
2.0 KiB
Rust

//! Demonstration of dyn-safe TimeSeriesModel trait usage
use rtx_tensor::{Device, Tensor};
use rtx_timeseries::models::{ARIMAModel, TimeSeriesModel};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize device
let device = Device::cpu();
// Create sample data
let data = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0], &[5], &device)?;
let timestamps = Tensor::arange(0, 5, &device)?;
// Create ARIMA model and use it as a trait object - THIS NOW WORKS!
let arima = ARIMAModel::new((1, 1, 1), None);
let mut model: Box<dyn TimeSeriesModel> = Box::new(arima);
println!("✅ Successfully created trait object Box<dyn TimeSeriesModel>");
// Use trait object methods
println!("Model type: {}", model.model_type());
println!("Model fitted: {:?}", model.is_fitted());
// Try async methods through trait object
if let Err(e) = model.fit(&data, &timestamps).await {
println!("Fit result: {}", e);
}
// Clone the trait object
if let Ok(cloned) = model.clone_boxed() {
println!("✅ Successfully cloned trait object");
println!("Cloned model type: {}", cloned.model_type());
}
// Create a vector of different models as trait objects
let models: Vec<Box<dyn TimeSeriesModel>> = vec![
Box::new(ARIMAModel::new((1, 1, 1), None)),
Box::new(ARIMAModel::new((2, 1, 2), None)),
// Additional models can be added as they get updated
];
println!(
"✅ Successfully created vector of {} trait objects",
models.len()
);
for (i, model) in models.iter().enumerate() {
println!("Model {}: {}", i, model.model_type());
}
println!("\n🎉 All trait object operations successful!");
println!("The TimeSeriesModel trait is now dyn-safe and can be used with:");
println!(" - Box<dyn TimeSeriesModel>");
println!(" - Vec<Box<dyn TimeSeriesModel>>");
println!(" - Dynamic dispatch with async methods");
Ok(())
}