use scirs2_core::ndarray::{Array1, Array2};
use sklears_core::error::SklearsError;
use sklears_core::traits::{Fit, Predict};
use std::marker::PhantomData;
pub trait EstimatorState {}
#[derive(Debug, Clone, Copy)]
pub struct Untrained;
impl EstimatorState for Untrained {}
#[derive(Debug, Clone, Copy)]
pub struct Trained;
impl EstimatorState for Trained {}
pub trait TaskType {}
#[derive(Debug, Clone, Copy)]
pub struct Classification;
impl TaskType for Classification {}
#[derive(Debug, Clone, Copy)]
pub struct Regression;
impl TaskType for Regression {}
pub trait StrategyValid<T: TaskType> {}
impl StrategyValid<Classification> for crate::ClassifierStrategy {}
impl StrategyValid<Regression> for crate::RegressorStrategy {}
#[derive(Debug, Clone)]
pub struct TypeSafeDummyEstimator<State, Task, Strategy>
where
State: EstimatorState,
Task: TaskType,
Strategy: StrategyValid<Task>,
{
strategy: Strategy,
random_state: Option<u64>,
_state: PhantomData<State>,
_task: PhantomData<Task>,
}
#[derive(Debug, Clone)]
#[allow(dead_code)] pub struct TypeSafeFittedClassifier<Strategy>
where
Strategy: StrategyValid<Classification>,
{
strategy: Strategy,
fitted_data: ClassificationFittedData,
random_state: Option<u64>,
}
#[derive(Debug, Clone)]
#[allow(dead_code)] pub struct TypeSafeFittedRegressor<Strategy>
where
Strategy: StrategyValid<Regression>,
{
strategy: Strategy,
fitted_data: RegressionFittedData,
random_state: Option<u64>,
}
#[derive(Debug, Clone)]
pub struct ClassificationFittedData {
pub class_counts: std::collections::HashMap<i32, usize>,
pub class_priors: std::collections::HashMap<i32, f64>,
pub most_frequent_class: i32,
pub n_samples: usize,
pub n_features: usize,
}
#[derive(Debug, Clone)]
pub struct RegressionFittedData {
pub target_mean: f64,
pub target_median: f64,
pub target_std: f64,
pub target_min: f64,
pub target_max: f64,
pub n_samples: usize,
pub n_features: usize,
}
pub trait EstimatorConfig {
type TaskType: TaskType;
type Strategy: StrategyValid<Self::TaskType>;
fn validate() -> Result<(), &'static str>;
fn create_strategy() -> Self::Strategy;
}
#[derive(Debug)]
pub struct ClassificationConfig<S: StrategyValid<Classification>> {
_strategy: PhantomData<S>,
}
#[derive(Debug)]
pub struct RegressionConfig<S: StrategyValid<Regression>> {
_strategy: PhantomData<S>,
}
impl<S: StrategyValid<Classification>> EstimatorConfig for ClassificationConfig<S> {
type TaskType = Classification;
type Strategy = S;
fn validate() -> Result<(), &'static str> {
Ok(())
}
fn create_strategy() -> Self::Strategy {
panic!("Strategy creation must be implemented per type")
}
}
impl<S: StrategyValid<Regression>> EstimatorConfig for RegressionConfig<S> {
type TaskType = Regression;
type Strategy = S;
fn validate() -> Result<(), &'static str> {
Ok(())
}
fn create_strategy() -> Self::Strategy {
panic!("Strategy creation must be implemented per type")
}
}
#[derive(Debug)]
#[allow(dead_code)] pub struct TypeSafeEstimatorBuilder<Task, Strategy>
where
Task: TaskType,
Strategy: StrategyValid<Task>,
{
strategy: Strategy,
random_state: Option<u64>,
_task: PhantomData<Task>,
}
impl<Strategy> TypeSafeDummyEstimator<Untrained, Classification, Strategy>
where
Strategy: StrategyValid<Classification> + Clone,
{
pub fn new(strategy: Strategy) -> Self {
Self {
strategy,
random_state: None,
_state: PhantomData,
_task: PhantomData,
}
}
pub fn with_random_state(mut self, seed: u64) -> Self {
self.random_state = Some(seed);
self
}
pub fn build(self) -> Result<Self, &'static str> {
self.validate_configuration()?;
Ok(self)
}
fn validate_configuration(&self) -> Result<(), &'static str> {
Ok(())
}
}
impl<Strategy> TypeSafeDummyEstimator<Untrained, Regression, Strategy>
where
Strategy: StrategyValid<Regression> + Clone,
{
pub fn new(strategy: Strategy) -> Self {
Self {
strategy,
random_state: None,
_state: PhantomData,
_task: PhantomData,
}
}
pub fn with_random_state(mut self, seed: u64) -> Self {
self.random_state = Some(seed);
self
}
pub fn build(self) -> Result<Self, &'static str> {
self.validate_configuration()?;
Ok(self)
}
fn validate_configuration(&self) -> Result<(), &'static str> {
Ok(())
}
}
impl<Strategy> Fit<Array2<f64>, Array1<i32>, TypeSafeFittedClassifier<Strategy>>
for TypeSafeDummyEstimator<Untrained, Classification, Strategy>
where
Strategy: StrategyValid<Classification> + Clone + Into<crate::ClassifierStrategy> + Send + Sync,
{
type Fitted = TypeSafeFittedClassifier<Strategy>;
fn fit(
self,
x: &Array2<f64>,
y: &Array1<i32>,
) -> Result<TypeSafeFittedClassifier<Strategy>, SklearsError> {
if x.nrows() != y.len() {
return Err(SklearsError::ShapeMismatch {
expected: format!("{} samples", x.nrows()),
actual: format!("{} labels", y.len()),
});
}
let mut class_counts = std::collections::HashMap::new();
for &class in y.iter() {
*class_counts.entry(class).or_insert(0) += 1;
}
let mut class_priors = std::collections::HashMap::new();
let total_samples = y.len() as f64;
for (&class, &count) in &class_counts {
class_priors.insert(class, count as f64 / total_samples);
}
let most_frequent_class = class_counts
.iter()
.max_by_key(|(_, &count)| count)
.map(|(&class, _)| class)
.unwrap_or(0);
let fitted_data = ClassificationFittedData {
class_counts,
class_priors,
most_frequent_class,
n_samples: x.nrows(),
n_features: x.ncols(),
};
Ok(TypeSafeFittedClassifier {
strategy: self.strategy.clone(),
fitted_data,
random_state: self.random_state,
})
}
}
impl<Strategy> Fit<Array2<f64>, Array1<f64>, TypeSafeFittedRegressor<Strategy>>
for TypeSafeDummyEstimator<Untrained, Regression, Strategy>
where
Strategy: StrategyValid<Regression> + Clone + Into<crate::RegressorStrategy> + Send + Sync,
{
type Fitted = TypeSafeFittedRegressor<Strategy>;
fn fit(
self,
x: &Array2<f64>,
y: &Array1<f64>,
) -> Result<TypeSafeFittedRegressor<Strategy>, SklearsError> {
if x.nrows() != y.len() {
return Err(SklearsError::ShapeMismatch {
expected: format!("{} samples", x.nrows()),
actual: format!("{} labels", y.len()),
});
}
let target_mean = y.mean().unwrap_or(0.0);
let target_std = y.std(0.0);
let target_min = y.iter().fold(f64::INFINITY, |a, &b| a.min(b));
let target_max = y.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b));
let mut sorted_targets = y.to_vec();
sorted_targets.sort_by(|a, b| a.partial_cmp(b).expect("operation should succeed"));
let target_median = if sorted_targets.len().is_multiple_of(2) {
let mid = sorted_targets.len() / 2;
(sorted_targets[mid - 1] + sorted_targets[mid]) / 2.0
} else {
sorted_targets[sorted_targets.len() / 2]
};
let fitted_data = RegressionFittedData {
target_mean,
target_median,
target_std,
target_min,
target_max,
n_samples: x.nrows(),
n_features: x.ncols(),
};
Ok(TypeSafeFittedRegressor {
strategy: self.strategy.clone(),
fitted_data,
random_state: self.random_state,
})
}
}
impl<Strategy> Predict<Array2<f64>, Array1<i32>> for TypeSafeFittedClassifier<Strategy>
where
Strategy: StrategyValid<Classification> + Clone + Into<crate::ClassifierStrategy>,
{
fn predict(&self, x: &Array2<f64>) -> Result<Array1<i32>, SklearsError> {
let legacy_strategy: crate::ClassifierStrategy = self.strategy.clone().into();
let legacy_classifier = crate::DummyClassifier::new(legacy_strategy);
let fake_x = Array2::zeros((self.fitted_data.n_samples, self.fitted_data.n_features));
let fake_y: Array1<i32> = Array1::from_iter(
self.fitted_data
.class_counts
.iter()
.flat_map(|(&class, &count)| std::iter::repeat_n(class, count)),
);
let fitted_legacy = legacy_classifier.fit(&fake_x, &fake_y)?;
fitted_legacy.predict(x)
}
}
impl<Strategy> Predict<Array2<f64>, Array1<f64>> for TypeSafeFittedRegressor<Strategy>
where
Strategy: StrategyValid<Regression> + Clone + Into<crate::RegressorStrategy>,
{
fn predict(&self, x: &Array2<f64>) -> Result<Array1<f64>, SklearsError> {
let legacy_strategy: crate::RegressorStrategy = self.strategy.clone().into();
let legacy_regressor = crate::DummyRegressor::new(legacy_strategy);
let fake_x = Array2::zeros((self.fitted_data.n_samples, self.fitted_data.n_features));
let fake_y = Array1::from_elem(self.fitted_data.n_samples, self.fitted_data.target_mean);
let fitted_legacy = legacy_regressor.fit(&fake_x, &fake_y)?;
fitted_legacy.predict(x)
}
}
#[macro_export]
macro_rules! validate_strategy_at_compile_time {
($strategy:ty, $task:ty) => {
const _: fn() = || {
fn assert_strategy_valid<S: StrategyValid<T>, T: TaskType>() {}
assert_strategy_valid::<$strategy, $task>();
};
};
}
#[macro_export]
macro_rules! type_safe_estimator {
(classification, $strategy:expr) => {{
TypeSafeDummyEstimator::<Untrained, Classification, _>::new($strategy)
}};
(regression, $strategy:expr) => {{
TypeSafeDummyEstimator::<Untrained, Regression, _>::new($strategy)
}};
}
pub struct ValidatedStrategy<S, T>
where
S: StrategyValid<T>,
T: TaskType,
{
strategy: S,
_task: PhantomData<T>,
}
impl<S, T> ValidatedStrategy<S, T>
where
S: StrategyValid<T>,
T: TaskType,
{
pub fn new(strategy: S) -> Self {
Self {
strategy,
_task: PhantomData,
}
}
pub fn into_strategy(self) -> S {
self.strategy
}
pub fn strategy(&self) -> &S {
&self.strategy
}
}
pub trait ParameterValidation {
type Error;
fn validate(&self) -> Result<(), Self::Error>;
}
#[derive(Debug, Clone)]
pub struct TypeSafeParameters<T> {
value: T,
}
impl<T> TypeSafeParameters<T> {
pub fn new(value: T) -> Self {
Self { value }
}
pub fn get(&self) -> &T {
&self.value
}
pub fn into_inner(self) -> T {
self.value
}
}
#[derive(Debug, Clone, Copy)]
pub struct BoundedParameter<T, const MIN: i64, const MAX: i64> {
value: T,
}
impl<T, const MIN: i64, const MAX: i64> BoundedParameter<T, MIN, MAX>
where
T: PartialOrd + Copy + TryFrom<i64>,
{
pub fn new(value: T) -> Result<Self, &'static str> {
let min_val = T::try_from(MIN).map_err(|_| "Invalid minimum bound")?;
let max_val = T::try_from(MAX).map_err(|_| "Invalid maximum bound")?;
if value >= min_val && value <= max_val {
Ok(Self { value })
} else {
Err("Parameter value out of bounds")
}
}
pub fn get(&self) -> T {
self.value
}
}
impl<const MIN: i64, const MAX: i64> BoundedParameter<i32, MIN, MAX> {
pub fn new_i32(value: i32) -> Result<Self, &'static str> {
let value_i64 = value as i64;
if value_i64 >= MIN && value_i64 <= MAX {
Ok(Self { value })
} else {
Err("Parameter value out of bounds")
}
}
}
impl<const MIN: i64, const MAX: i64> BoundedParameter<u64, MIN, MAX> {
pub fn new_u64(value: u64) -> Result<Self, &'static str> {
let value_i64 = value as i64;
if value_i64 >= MIN && value_i64 <= MAX && value <= i64::MAX as u64 {
Ok(Self { value })
} else {
Err("Parameter value out of bounds")
}
}
}
impl<const MIN: i64, const MAX: i64> BoundedParameter<f64, MIN, MAX> {
pub fn new_f64(value: f64) -> Result<Self, &'static str> {
let min_f64 = MIN as f64;
let max_f64 = MAX as f64;
if value >= min_f64 && value <= max_f64 {
Ok(Self { value })
} else {
Err("Parameter value out of bounds")
}
}
pub fn get_f64(&self) -> f64 {
self.value
}
}
pub type Probability = BoundedParameter<f64, 0, 1>;
pub type PositiveInt = BoundedParameter<i32, 1, { i32::MAX as i64 }>;
pub type RandomSeed = BoundedParameter<u64, 0, { i64::MAX }>;
pub type Dimension = BoundedParameter<usize, 1, 10000>;
pub type BatchSize = BoundedParameter<usize, 1, 1000000>;
pub type ConfidenceLevel = BoundedParameter<f64, 0, 1>;
pub type Tolerance = BoundedParameter<f64, 0, { i64::MAX }>;
pub type IterationCount = BoundedParameter<u32, 1, { i32::MAX as i64 }>;
impl<const MIN: i64, const MAX: i64> BoundedParameter<usize, MIN, MAX> {
pub fn new_usize(value: usize) -> Result<Self, &'static str> {
let value_i64 = value as i64;
if value_i64 >= MIN && value_i64 <= MAX && value <= i64::MAX as usize {
Ok(Self { value })
} else {
Err("Parameter value out of bounds")
}
}
pub fn get_usize(&self) -> usize {
self.value
}
}
impl<const MIN: i64, const MAX: i64> BoundedParameter<u32, MIN, MAX> {
pub fn new_u32(value: u32) -> Result<Self, &'static str> {
let value_i64 = value as i64;
if value_i64 >= MIN && value_i64 <= MAX {
Ok(Self { value })
} else {
Err("Parameter value out of bounds")
}
}
pub fn get_u32(&self) -> u32 {
self.value
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConstStrategySelector<const STRATEGY_ID: usize>;
pub trait StrategyFromId<const ID: usize> {
type Strategy;
fn create_strategy() -> Self::Strategy;
}
impl StrategyFromId<0> for ConstStrategySelector<0> {
type Strategy = crate::ClassifierStrategy;
fn create_strategy() -> Self::Strategy {
crate::ClassifierStrategy::MostFrequent
}
}
impl StrategyFromId<1> for ConstStrategySelector<1> {
type Strategy = crate::ClassifierStrategy;
fn create_strategy() -> Self::Strategy {
crate::ClassifierStrategy::Stratified
}
}
impl StrategyFromId<2> for ConstStrategySelector<2> {
type Strategy = crate::ClassifierStrategy;
fn create_strategy() -> Self::Strategy {
crate::ClassifierStrategy::Uniform
}
}
impl StrategyFromId<10> for ConstStrategySelector<10> {
type Strategy = crate::RegressorStrategy;
fn create_strategy() -> Self::Strategy {
crate::RegressorStrategy::Mean
}
}
impl StrategyFromId<11> for ConstStrategySelector<11> {
type Strategy = crate::RegressorStrategy;
fn create_strategy() -> Self::Strategy {
crate::RegressorStrategy::Median
}
}
impl StrategyFromId<12> for ConstStrategySelector<12> {
type Strategy = crate::RegressorStrategy;
fn create_strategy() -> Self::Strategy {
crate::RegressorStrategy::Normal {
mean: None,
std: None,
}
}
}
#[derive(Debug, Clone)]
pub struct ConstGenericEstimator<State, Task, const STRATEGY_ID: usize>
where
State: EstimatorState,
Task: TaskType,
ConstStrategySelector<STRATEGY_ID>: StrategyFromId<STRATEGY_ID>,
{
random_state: Option<u64>,
_state: PhantomData<State>,
_task: PhantomData<Task>,
}
impl<Task, const STRATEGY_ID: usize> Default for ConstGenericEstimator<Untrained, Task, STRATEGY_ID>
where
Task: TaskType,
ConstStrategySelector<STRATEGY_ID>: StrategyFromId<STRATEGY_ID>,
{
fn default() -> Self {
Self::new()
}
}
impl<Task, const STRATEGY_ID: usize> ConstGenericEstimator<Untrained, Task, STRATEGY_ID>
where
Task: TaskType,
ConstStrategySelector<STRATEGY_ID>: StrategyFromId<STRATEGY_ID>,
{
pub fn new() -> Self {
Self {
random_state: None,
_state: PhantomData,
_task: PhantomData,
}
}
pub fn with_random_state(mut self, seed: u64) -> Self {
self.random_state = Some(seed);
self
}
pub fn strategy(
) -> <ConstStrategySelector<STRATEGY_ID> as StrategyFromId<STRATEGY_ID>>::Strategy {
ConstStrategySelector::<STRATEGY_ID>::create_strategy()
}
}
#[derive(Debug, Clone, Copy)]
pub struct ZeroCostWrapper<T> {
inner: T,
}
impl<T> ZeroCostWrapper<T> {
#[inline(always)]
pub const fn new(inner: T) -> Self {
Self { inner }
}
#[inline(always)]
pub fn into_inner(self) -> T {
self.inner
}
#[inline(always)]
pub const fn get(&self) -> &T {
&self.inner
}
#[inline(always)]
pub fn map<U, F>(self, f: F) -> ZeroCostWrapper<U>
where
F: FnOnce(T) -> U,
{
ZeroCostWrapper::new(f(self.inner))
}
}
#[derive(Debug, Clone, Copy)]
pub struct StatisticalPhantom<
const IS_DETERMINISTIC: bool,
const IS_STATELESS: bool,
const REQUIRES_FITTING: bool,
> {
_marker: PhantomData<()>,
}
impl<const IS_DETERMINISTIC: bool, const IS_STATELESS: bool, const REQUIRES_FITTING: bool> Default
for StatisticalPhantom<IS_DETERMINISTIC, IS_STATELESS, REQUIRES_FITTING>
{
fn default() -> Self {
Self::new()
}
}
impl<const IS_DETERMINISTIC: bool, const IS_STATELESS: bool, const REQUIRES_FITTING: bool>
StatisticalPhantom<IS_DETERMINISTIC, IS_STATELESS, REQUIRES_FITTING>
{
pub const fn new() -> Self {
Self {
_marker: PhantomData,
}
}
pub const fn is_deterministic() -> bool {
IS_DETERMINISTIC
}
pub const fn is_stateless() -> bool {
IS_STATELESS
}
pub const fn requires_fitting() -> bool {
REQUIRES_FITTING
}
}
pub type SimpleDeterministicStrategy = StatisticalPhantom<true, true, false>;
pub type StochasticFittedStrategy = StatisticalPhantom<false, false, true>;
pub trait StrategyProperties {
const IS_DETERMINISTIC: bool;
const IS_STATELESS: bool;
const REQUIRES_FITTING: bool;
type Phantom: 'static;
fn phantom() -> Self::Phantom;
}
#[derive(Debug, Clone)]
#[allow(dead_code)] pub struct StatisticallyTypedEstimator<State, Task, Strategy, Properties>
where
State: EstimatorState,
Task: TaskType,
Strategy: StrategyValid<Task> + StrategyProperties<Phantom = Properties>,
Properties: 'static,
{
strategy: Strategy,
random_state: Option<u64>,
_state: PhantomData<State>,
_task: PhantomData<Task>,
_properties: PhantomData<Properties>,
}
impl<Task, Strategy, Properties> StatisticallyTypedEstimator<Untrained, Task, Strategy, Properties>
where
Task: TaskType,
Strategy: StrategyValid<Task> + StrategyProperties<Phantom = Properties> + Clone,
Properties: 'static,
{
pub fn new(strategy: Strategy) -> Self {
Self {
strategy,
random_state: None,
_state: PhantomData,
_task: PhantomData,
_properties: PhantomData,
}
}
pub const fn is_deterministic() -> bool {
Strategy::IS_DETERMINISTIC
}
pub const fn is_stateless() -> bool {
Strategy::IS_STATELESS
}
pub const fn requires_fitting() -> bool {
Strategy::REQUIRES_FITTING
}
}
#[macro_export]
macro_rules! validate_estimator_config {
($estimator_type:ty, $state:ty, $task:ty) => {
const _: () = {
fn _assert_estimator_state<S: EstimatorState>() {}
fn _assert_task_type<T: TaskType>() {}
fn _assert_type_safe_estimator<
E: TypeSafeEstimator<S, T>,
S: EstimatorState,
T: TaskType,
>() {
}
_assert_estimator_state::<$state>();
_assert_task_type::<$task>();
};
};
}
#[macro_export]
macro_rules! assert_strategy_compatible {
($strategy:ty, $task:ty) => {
const _: () = {
fn _assert_compatible<S: StrategyValid<T>, T: TaskType>() {}
_assert_compatible::<$strategy, $task>();
};
};
}
#[derive(Debug, Clone, Copy)]
pub struct CompileTimeFeature<const ENABLED: bool>;
impl<const ENABLED: bool> CompileTimeFeature<ENABLED> {
pub const fn is_enabled() -> bool {
ENABLED
}
#[inline(always)]
pub fn when_enabled<F, R>(f: F) -> Option<R>
where
F: FnOnce() -> R,
{
if ENABLED {
Some(f())
} else {
None
}
}
}
pub trait TypeSafeStatisticalOps<T> {
fn safe_mean(&self) -> Option<T>;
fn safe_variance(&self) -> Option<T>;
fn safe_std(&self) -> Option<T>;
}
impl TypeSafeStatisticalOps<f64> for Array1<f64> {
fn safe_mean(&self) -> Option<f64> {
if self.is_empty() {
None
} else {
Some(self.mean().unwrap_or(0.0))
}
}
fn safe_variance(&self) -> Option<f64> {
if self.len() < 2 {
None
} else {
Some(self.var(1.0)) }
}
fn safe_std(&self) -> Option<f64> {
self.safe_variance().map(|v| v.sqrt())
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct OptimizedLayout<T> {
data: T,
_pad: [u8; 0], }
impl<T> OptimizedLayout<T> {
#[inline(always)]
pub const fn new(data: T) -> Self {
Self { data, _pad: [] }
}
#[inline(always)]
pub fn into_data(self) -> T {
self.data
}
#[inline(always)]
pub const fn data(&self) -> &T {
&self.data
}
}
pub trait TypeSafeEstimator<State: EstimatorState, Task: TaskType> {
type Strategy: StrategyValid<Task>;
fn state(&self) -> State;
fn task_type(&self) -> Task;
fn validate(&self) -> Result<(), &'static str>;
}
impl<State, Task, Strategy> TypeSafeEstimator<State, Task>
for TypeSafeDummyEstimator<State, Task, Strategy>
where
State: EstimatorState + Default,
Task: TaskType + Default,
Strategy: StrategyValid<Task>,
{
type Strategy = Strategy;
fn state(&self) -> State {
State::default()
}
fn task_type(&self) -> Task {
Task::default()
}
fn validate(&self) -> Result<(), &'static str> {
Ok(())
}
}
impl Default for Untrained {
fn default() -> Self {
Untrained
}
}
impl Default for Trained {
fn default() -> Self {
Trained
}
}
impl Default for Classification {
fn default() -> Self {
Classification
}
}
impl Default for Regression {
fn default() -> Self {
Regression
}
}
#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
use super::*;
use crate::{ClassifierStrategy, RegressorStrategy};
use scirs2_core::ndarray::{array, Array2};
#[test]
fn test_type_safe_classifier_creation() {
let strategy = ClassifierStrategy::MostFrequent;
let classifier = TypeSafeDummyEstimator::<Untrained, Classification, _>::new(strategy);
assert!(classifier.validate().is_ok());
}
#[test]
fn test_type_safe_regressor_creation() {
let strategy = RegressorStrategy::Mean;
let regressor = TypeSafeDummyEstimator::<Untrained, Regression, _>::new(strategy);
assert!(regressor.validate().is_ok());
}
#[test]
fn test_bounded_parameters() {
let prob = Probability::new_f64(0.5);
assert!(prob.is_ok());
assert_eq!(prob.expect("operation should succeed").get_f64(), 0.5);
let invalid_prob = Probability::new_f64(1.5);
assert!(invalid_prob.is_err());
let pos_int = PositiveInt::new_i32(42);
assert!(pos_int.is_ok());
assert_eq!(pos_int.expect("index should be valid").get(), 42);
let invalid_int = PositiveInt::new_i32(-1);
assert!(invalid_int.is_err());
}
#[test]
fn test_validated_strategy() {
let strategy = ClassifierStrategy::MostFrequent;
let validated = ValidatedStrategy::<_, Classification>::new(strategy.clone());
assert_eq!(
format!("{:?}", validated.strategy()),
format!("{:?}", strategy)
);
let extracted = validated.into_strategy();
assert_eq!(format!("{:?}", extracted), format!("{:?}", strategy));
}
#[test]
fn test_type_safe_parameters() {
let params = TypeSafeParameters::new(42.0);
assert_eq!(*params.get(), 42.0);
assert_eq!(params.into_inner(), 42.0);
}
#[test]
fn test_estimator_state_transitions() {
let strategy = ClassifierStrategy::MostFrequent;
let untrained = TypeSafeDummyEstimator::<Untrained, Classification, _>::new(strategy);
let x = Array2::from_shape_vec((4, 2), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0])
.expect("shape and data length should match");
let y = array![0, 0, 1, 1];
let fitted = untrained.fit(&x, &y).expect("model fitting should succeed");
let predictions = fitted.predict(&x);
assert!(predictions.is_ok());
assert_eq!(predictions.expect("operation should succeed").len(), 4);
}
#[test]
fn test_const_generic_estimator() {
let _classifier = ConstGenericEstimator::<Untrained, Classification, 0>::new();
let strategy = ConstGenericEstimator::<Untrained, Classification, 0>::strategy();
assert_eq!(format!("{:?}", strategy), "MostFrequent");
let _regressor = ConstGenericEstimator::<Untrained, Regression, 10>::new();
let reg_strategy = ConstGenericEstimator::<Untrained, Regression, 10>::strategy();
assert_eq!(format!("{:?}", reg_strategy), "Mean");
}
#[test]
fn test_zero_cost_wrapper() {
let wrapper = ZeroCostWrapper::new(42);
assert_eq!(*wrapper.get(), 42);
assert_eq!(wrapper.into_inner(), 42);
let mapped = ZeroCostWrapper::new(10).map(|x| x * 2);
assert_eq!(mapped.into_inner(), 20);
}
#[test]
fn test_statistical_phantom() {
let _phantom = SimpleDeterministicStrategy::new();
assert!(SimpleDeterministicStrategy::is_deterministic());
assert!(SimpleDeterministicStrategy::is_stateless());
assert!(!SimpleDeterministicStrategy::requires_fitting());
let _stochastic = StochasticFittedStrategy::new();
assert!(!StochasticFittedStrategy::is_deterministic());
assert!(!StochasticFittedStrategy::is_stateless());
assert!(StochasticFittedStrategy::requires_fitting());
}
#[test]
fn test_compile_time_feature() {
type EnabledFeature = CompileTimeFeature<true>;
assert!(EnabledFeature::is_enabled());
let result = EnabledFeature::when_enabled(|| 42);
assert_eq!(result, Some(42));
type DisabledFeature = CompileTimeFeature<false>;
assert!(!DisabledFeature::is_enabled());
let no_result = DisabledFeature::when_enabled(|| 42);
assert_eq!(no_result, None);
}
#[test]
fn test_type_safe_statistical_ops() {
use scirs2_core::ndarray::array;
let data = array![1.0, 2.0, 3.0, 4.0, 5.0];
assert_eq!(data.safe_mean(), Some(3.0));
assert!(data.safe_variance().is_some());
assert!(data.safe_std().is_some());
let empty: Array1<f64> = array![];
assert_eq!(empty.safe_mean(), None);
assert_eq!(empty.safe_variance(), None);
assert_eq!(empty.safe_std(), None);
let single = array![42.0];
assert_eq!(single.safe_mean(), Some(42.0));
assert_eq!(single.safe_variance(), None); }
#[test]
fn test_optimized_layout() {
let layout = OptimizedLayout::new(42);
assert_eq!(*layout.data(), 42);
assert_eq!(layout.into_data(), 42);
}
}