80 double stat_variance {};
81 double stat_std_dev {};
89 std::array<int, 6> level_counts {};
101 uint32_t window_size {};
102 uint32_t hop_size {};
128template <ComputeData InputType = std::vector<Kakshya::DataVariant>, ComputeData OutputType = Eigen::VectorXd>
141 : m_window_size(window_size)
142 , m_hop_size(hop_size)
144 validate_window_parameters();
154 auto result = this->analyze_data(data);
155 return safe_any_cast_or_throw<StatisticalAnalysis>(result);
164 return safe_any_cast_or_throw<StatisticalAnalysis>(this->get_current_analysis());
173 return AnalysisType::STATISTICAL;
182 return Reflect::get_enum_names_lowercase<StatisticalMethod>();
190 template <
typename T>
193 return get_methods_for_type_impl(std::type_index(
typeid(T)));
201 template <
typename T>
204 return !get_methods_for_type<T>().empty();
214 this->set_parameter(
"method", method_to_string(method));
223 m_method = string_to_method(method_name);
224 this->set_parameter(
"method", method_name);
242 m_window_size = size;
243 validate_window_parameters();
253 validate_window_parameters();
274 m_classification_enabled = enabled;
290 if (std::abs(value) > m_outlier_threshold)
291 return StatisticalLevel::OUTLIER;
292 if (value <= m_extreme_low_threshold)
293 return StatisticalLevel::EXTREME_LOW;
294 if (value <= m_low_threshold)
295 return StatisticalLevel::LOW;
296 if (value <= m_high_threshold)
297 return StatisticalLevel::NORMAL;
298 if (value <= m_extreme_high_threshold)
299 return StatisticalLevel::HIGH;
300 return StatisticalLevel::EXTREME_HIGH;
310 return Reflect::enum_to_lowercase_string(method);
320 if (str ==
"default")
321 return StatisticalMethod::MEAN;
322 return Reflect::string_to_enum_or_throw_case_insensitive<StatisticalMethod>(str,
"StatisticalMethod");
332 return Reflect::enum_to_lowercase_string(level);
342 return "StatisticalAnalyzer";
352 if (input.
data.empty()) {
353 error<std::runtime_error>(Journal::Component::Yantra, Journal::Context::ComputeMatrix, std::source_location::current(),
"Input is empty");
356 auto [data_span, structure_info] = OperationHelper::extract_structured_double(
359 std::vector<std::span<const double>> channel_spans;
360 for (
const auto& span : data_span)
361 channel_spans.emplace_back(span.data(), span.size());
363 std::vector<std::vector<double>> stat_values;
364 stat_values.reserve(channel_spans.size());
365 for (
const auto& ch_span : channel_spans) {
366 stat_values.push_back(compute_statistical_values(ch_span, m_method));
370 stat_values, channel_spans, structure_info);
372 this->store_current_analysis(analysis_result);
373 return create_pipeline_output(input, analysis_result, structure_info);
374 }
catch (
const std::exception& e) {
375 MF_ERROR(Journal::Component::Yantra, Journal::Context::ComputeMatrix,
"Statistical analysis failed: {}", e.what());
378 error_result.
metadata[
"error"] = std::string(
"Analysis failed: ") + e.what();
389 if (name ==
"method") {
391 auto method_str = safe_any_cast_or_throw<std::string>(value);
392 m_method = string_to_method(method_str);
393 }
catch (
const std::runtime_error&) {
394 auto method_enum = safe_any_cast_or_throw<StatisticalMethod>(value);
395 m_method = method_enum;
397 }
else if (name ==
"window_size") {
398 auto size = safe_any_cast_or_throw<uint32_t>(value);
399 m_window_size = size;
400 validate_window_parameters();
401 }
else if (name ==
"hop_size") {
402 auto size = safe_any_cast_or_throw<uint32_t>(value);
404 validate_window_parameters();
405 }
else if (name ==
"classification_enabled") {
406 auto enabled = safe_any_cast_or_throw<bool>(value);
407 m_classification_enabled = enabled;
408 }
else if (name ==
"percentile") {
409 auto percentile = safe_any_cast_or_throw<double>(value);
410 if (percentile < 0.0 || percentile > 100.0) {
411 throw std::invalid_argument(
"Percentile must be between 0.0 and 100.0, got: " + std::to_string(percentile));
413 m_percentile_value = percentile;
414 }
else if (name ==
"sample_variance") {
415 auto sample = safe_any_cast_or_throw<bool>(value);
416 m_sample_variance = sample;
418 base_type::set_analysis_parameter(name, std::move(value));
420 }
catch (
const std::runtime_error& e) {
421 error_rethrow(Journal::Component::Yantra, Journal::Context::ComputeMatrix, std::source_location::current(),
"Failed to set parameter '{}': {}", name, e.what());
430 if (name ==
"method")
431 return std::any(method_to_string(m_method));
432 if (name ==
"window_size")
433 return std::any(m_window_size);
434 if (name ==
"hop_size")
435 return std::any(m_hop_size);
436 if (name ==
"classification_enabled")
437 return std::any(m_classification_enabled);
438 if (name ==
"percentile")
439 return std::any(m_percentile_value);
440 if (name ==
"sample_variance")
441 return std::any(m_sample_variance);
443 return base_type::get_analysis_parameter(name);
453 return get_available_methods();
460 bool m_classification_enabled {
true };
461 double m_percentile_value { 50.0 };
462 bool m_sample_variance {
true };
464 double m_outlier_threshold { 3.0 };
465 double m_extreme_low_threshold { -2.0 };
466 double m_low_threshold { -1.0 };
467 double m_high_threshold { 1.0 };
468 double m_extreme_high_threshold { 2.0 };
475 if (m_window_size == 0 || m_hop_size == 0) {
476 error<std::invalid_argument>(Journal::Component::Yantra, Journal::Context::ComputeMatrix, std::source_location::current(),
"Window size and hop size must be greater than 0");
478 if (m_hop_size > m_window_size) {
479 error<std::invalid_argument>(Journal::Component::Yantra, Journal::Context::ComputeMatrix, std::source_location::current(),
"Hop size should not exceed window size");
488 const size_t num_windows = calculate_num_windows(data.size());
493 case StatisticalMethod::MEAN:
494 return D::mean(data, num_windows, m_hop_size, m_window_size);
495 case StatisticalMethod::VARIANCE:
496 return D::variance(data, num_windows, m_hop_size, m_window_size, m_sample_variance);
497 case StatisticalMethod::STD_DEV:
498 return D::std_dev(data, num_windows, m_hop_size, m_window_size, m_sample_variance);
499 case StatisticalMethod::SKEWNESS:
500 return D::skewness(data, num_windows, m_hop_size, m_window_size);
501 case StatisticalMethod::KURTOSIS:
502 return D::kurtosis(data, num_windows, m_hop_size, m_window_size);
503 case StatisticalMethod::MEDIAN:
504 return D::median(data, num_windows, m_hop_size, m_window_size);
505 case StatisticalMethod::PERCENTILE:
506 return D::percentile(data, num_windows, m_hop_size, m_window_size, m_percentile_value);
507 case StatisticalMethod::ENTROPY:
508 return D::entropy(data, num_windows, m_hop_size, m_window_size);
509 case StatisticalMethod::MIN:
510 return D::min(data, num_windows, m_hop_size, m_window_size);
511 case StatisticalMethod::MAX:
512 return D::max(data, num_windows, m_hop_size, m_window_size);
513 case StatisticalMethod::RANGE:
514 return D::range(data, num_windows, m_hop_size, m_window_size);
515 case StatisticalMethod::SUM:
516 return D::sum(data, num_windows, m_hop_size, m_window_size);
517 case StatisticalMethod::COUNT:
518 return D::count(data, num_windows, m_hop_size, m_window_size);
519 case StatisticalMethod::RMS:
520 return D::rms(data, num_windows, m_hop_size, m_window_size);
521 case StatisticalMethod::MAD:
522 return D::mad(data, num_windows, m_hop_size, m_window_size);
523 case StatisticalMethod::CV:
524 return D::coefficient_of_variation(data, num_windows, m_hop_size, m_window_size, m_sample_variance);
525 case StatisticalMethod::MODE:
526 return D::mode(data, num_windows, m_hop_size, m_window_size);
527 case StatisticalMethod::ZSCORE:
528 return D::mean_zscore(data, num_windows, m_hop_size, m_window_size, m_sample_variance);
530 return D::mean(data, num_windows, m_hop_size, m_window_size);
539 if (data_size < m_window_size)
541 return (data_size - m_window_size) / m_hop_size + 1;
548 std::vector<std::span<const double>> original_data,
const auto& )
const
557 if (stat_values.empty()) {
563 for (
size_t ch = 0; ch < stat_values.size(); ++ch) {
565 const auto& ch_stats = stat_values[ch];
567 channel_result.statistical_values = ch_stats;
569 if (ch_stats.empty())
572 const auto [min_it, max_it] = std::ranges::minmax_element(ch_stats);
573 channel_result.min_stat = *min_it;
574 channel_result.max_stat = *max_it;
576 const std::span<const double> sp(ch_stats);
577 const auto sz =
static_cast<uint32_t
>(ch_stats.size());
579 const auto single = [&](
auto fn) {
return fn(sp, 1, 0, sz)[0]; };
581 channel_result.mean_stat = single([](
auto&&...
a) {
return D::mean(
a...); });
582 channel_result.stat_variance = single([&](
auto&&...
a) {
return D::variance(
a..., m_sample_variance); });
583 channel_result.stat_std_dev = std::sqrt(channel_result.stat_variance);
584 channel_result.skewness = single([](
auto&&...
a) {
return D::skewness(
a...); });
585 channel_result.kurtosis = single([](
auto&&...
a) {
return D::kurtosis(
a...); });
586 channel_result.median = single([](
auto&&...
a) {
return D::median(
a...); });
588 channel_result.percentiles = {
589 D::percentile(sp, 1, 0, sz, 25.0)[0],
590 channel_result.median,
591 D::percentile(sp, 1, 0, sz, 75.0)[0]
594 const size_t data_size = (ch < original_data.size()) ? original_data[ch].size() : 0;
595 channel_result.window_positions.reserve(ch_stats.size());
596 for (
size_t i = 0; i < ch_stats.size(); ++i) {
597 const size_t start = i * m_hop_size;
598 const size_t end = std::min(start + m_window_size, data_size);
599 channel_result.window_positions.emplace_back(start, end);
602 if (m_classification_enabled) {
603 channel_result.stat_classifications.reserve(ch_stats.size());
604 channel_result.level_counts.fill(0);
606 for (
double value : ch_stats) {
608 channel_result.stat_classifications.push_back(level);
609 channel_result.level_counts[
static_cast<size_t>(level)]++;
622 std::vector<std::vector<double>> channel_stats;
625 channel_stats.push_back(ch.statistical_values);
628 output_type output = this->convert_result(channel_stats, info);
632 output.
metadata[
"source_analyzer"] =
"StatisticalAnalyzer";
639 std::vector<double> channel_means, channel_maxs, channel_mins, channel_variances, channel_stddevs, channel_skewness, channel_kurtosis, channel_medians;
640 std::vector<size_t> channel_window_counts;
643 channel_means.push_back(ch.mean_stat);
644 channel_maxs.push_back(ch.max_stat);
645 channel_mins.push_back(ch.min_stat);
646 channel_variances.push_back(ch.stat_variance);
647 channel_stddevs.push_back(ch.stat_std_dev);
648 channel_skewness.push_back(ch.skewness);
649 channel_kurtosis.push_back(ch.kurtosis);
650 channel_medians.push_back(ch.median);
651 channel_window_counts.push_back(ch.statistical_values.size());
654 output.
metadata[
"mean_per_channel"] = channel_means;
655 output.
metadata[
"max_per_channel"] = channel_maxs;
656 output.
metadata[
"min_per_channel"] = channel_mins;
657 output.
metadata[
"variance_per_channel"] = channel_variances;
658 output.
metadata[
"stddev_per_channel"] = channel_stddevs;
659 output.
metadata[
"skewness_per_channel"] = channel_skewness;
660 output.
metadata[
"kurtosis_per_channel"] = channel_kurtosis;
661 output.
metadata[
"median_per_channel"] = channel_medians;
662 output.
metadata[
"window_count_per_channel"] = channel_window_counts;
679template <ComputeData InputType = std::vector<Kakshya::DataVariant>>
683template <ComputeData InputType = std::vector<Kakshya::DataVariant>>
Discrete sequence analysis primitives for MayaFlux::Kinesis.
#define MF_ERROR(comp, ctx,...)
Modern, digital-first universal analyzer framework for Maya Flux.
std::any get_analysis_parameter(const std::string &name) const override
Get analysis-specific parameter.
void set_classification_enabled(bool enabled)
Enable/disable outlier classification.
bool is_classification_enabled() const
Check if classification is enabled.
StatisticalMethod get_method() const
Get current statistical method.
StatisticalAnalysis get_statistical_analysis() const
Get last statistical analysis result (type-safe)
void validate_window_parameters() const
Validate window parameters.
std::vector< std::string > get_methods_for_type_impl(std::type_index) const
Get supported methods for specific type index.
std::string get_analyzer_name() const override
Get analyzer name.
static StatisticalMethod string_to_method(const std::string &str)
Convert string to statistical method enum.
bool supports_input_type() const
Check if analyzer supports given input type.
std::vector< std::string > get_methods_for_type() const
Get supported methods for specific input type.
StatisticalAnalysis create_analysis_result(const std::vector< std::vector< double > > &stat_values, std::vector< std::span< const double > > original_data, const auto &) const
Create comprehensive analysis result.
std::vector< std::string > get_available_methods() const override
Get available analysis methods.
StatisticalAnalyzer(uint32_t window_size=512, uint32_t hop_size=256)
Construct StatisticalAnalyzer with configurable window parameters.
StatisticalLevel classify_statistical_level(double value) const
Classify statistical value qualitatively.
static std::string method_to_string(StatisticalMethod method)
Convert statistical method enum to string.
std::vector< double > compute_statistical_values(std::span< const double > data, StatisticalMethod method) const
Compute statistical values using span (zero-copy processing)
static std::string statistical_level_to_string(StatisticalLevel level)
Convert statistical level enum to string.
AnalysisType get_analysis_type() const override
Get analysis type category.
uint32_t get_window_size() const
Get window size.
void set_window_size(uint32_t size)
Set window size for windowed analysis.
void set_method(StatisticalMethod method)
Set statistical analysis method.
output_type create_pipeline_output(const input_type &input, const StatisticalAnalysis &analysis_result, DataStructureInfo &info)
Create pipeline output for operation chaining.
uint32_t get_hop_size() const
Get hop size.
output_type analyze_implementation(const input_type &input) override
Core analysis implementation - creates analysis result AND pipeline output.
size_t calculate_num_windows(size_t data_size) const
Calculate number of windows for given data size.
void set_method(const std::string &method_name)
Set method by string name.
void set_analysis_parameter(const std::string &name, std::any value) override
Handle analysis-specific parameters.
StatisticalAnalysis analyze_statistics(const InputType &data)
Type-safe statistical analysis method.
void set_hop_size(uint32_t size)
Set hop size for windowed analysis.
High-performance statistical analyzer with zero-copy processing.
Template-flexible analyzer base with instance-defined I/O types.
AnalysisType
Categories of analysis operations for discovery and organization.
@ RMS
Root Mean Square energy.
StatisticalLevel
Qualitative classification of statistical values.
StatisticalMethod
Supported statistical computation methods.
@ PERCENTILE
Arbitrary percentile (requires parameter)
@ KURTOSIS
Fourth moment - tail heaviness.
@ ZSCORE
Z-score normalization.
@ ENTROPY
Shannon entropy for discrete data.
@ MAD
Median Absolute Deviation.
@ CV
Coefficient of Variation (std_dev/mean)
@ STD_DEV
Standard deviation.
@ MODE
Most frequent value.
@ VARIANCE
Population or sample variance.
@ SKEWNESS
Third moment - asymmetry measure.
std::map< std::string, std::any > method_specific_data
std::vector< std::pair< size_t, size_t > > window_positions
std::vector< StatisticalLevel > stat_classifications
std::vector< double > percentiles
std::vector< double > statistical_values
Statistical results for a single data channel.
Metadata about data structure for reconstruction.
T data
The actual computation data.
std::unordered_map< std::string, std::any > metadata
Associated metadata.
Input/Output container for computation pipeline data flow with structure preservation.
StatisticalMethod method_used
std::vector< ChannelStatistics > channel_statistics
Analysis result structure for statistical analysis.