MayaFlux 0.4.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
StatisticalAnalyzer.hpp
Go to the documentation of this file.
1#pragma once
2
5
7
9#include <Eigen/Dense>
10
11/**
12 * @file StatisticalAnalyzer_new.hpp
13 * @brief Span-based statistical analysis for digital signals in Maya Flux
14 *
15 * Defines the StatisticalAnalyzer using the new UniversalAnalyzer framework with
16 * zero-copy span processing and automatic structure handling via OperationHelper.
17 * This analyzer extracts statistical features from digital data streams with multiple
18 * computation methods and flexible output configurations.
19 *
20 * Key Features:
21 * - **Zero-copy processing:** Uses spans for maximum efficiency
22 * - **Template-flexible I/O:** Instance defines input/output types at construction
23 * - **Multiple statistical methods:** Mean, variance, std dev, skewness, kurtosis, percentiles, etc.
24 * - **Parallel processing:** Utilizes std::execution for performance
25 * - **Cross-modal support:** Works on any numeric data stream - truly digital-first
26 * - **Statistical classification:** Maps values to qualitative levels (outliers, normal, etc.)
27 * - **Automatic data handling:** OperationHelper manages all extraction/conversion
28 */
29
30namespace MayaFlux::Yantra {
31
32/**
33 * @enum StatisticalMethod
34 * @brief Supported statistical computation methods
35 */
36enum class StatisticalMethod : uint8_t {
37 MEAN, ///< Arithmetic mean
38 VARIANCE, ///< Population or sample variance
39 STD_DEV, ///< Standard deviation
40 SKEWNESS, ///< Third moment - asymmetry measure
41 KURTOSIS, ///< Fourth moment - tail heaviness
42 MIN, ///< Minimum value
43 MAX, ///< Maximum value
44 MEDIAN, ///< 50th percentile
45 RANGE, ///< Max - min
46 PERCENTILE, ///< Arbitrary percentile (requires parameter)
47 MODE, ///< Most frequent value
48 MAD, ///< Median Absolute Deviation
49 CV, ///< Coefficient of Variation (std_dev/mean)
50 SUM, ///< Sum of all values
51 COUNT, ///< Number of values
52 RMS, ///< Root Mean Square
53 ENTROPY, ///< Shannon entropy for discrete data
54 ZSCORE ///< Z-score normalization
55};
56
57/**
58 * @enum StatisticalLevel
59 * @brief Qualitative classification of statistical values
60 */
61enum class StatisticalLevel : uint8_t {
63 LOW,
64 NORMAL,
65 HIGH,
68};
69
70/**
71 * @struct ChannelStatistics
72 * @brief Statistical results for a single data channel
73 */
74struct MAYAFLUX_API ChannelStatistics {
75 std::vector<double> statistical_values;
76
77 double mean_stat {};
78 double max_stat {};
79 double min_stat {};
80 double stat_variance {};
81 double stat_std_dev {};
82
83 double skewness {};
84 double kurtosis {};
85 double median {};
86 std::vector<double> percentiles;
87
88 std::vector<StatisticalLevel> stat_classifications;
89 std::array<int, 6> level_counts {};
90
91 std::vector<std::pair<size_t, size_t>> window_positions;
92 std::map<std::string, std::any> method_specific_data;
93};
94
95/**
96 * @struct StatisticalAnalysis
97 * @brief Analysis result structure for statistical analysis
98 */
99struct MAYAFLUX_API StatisticalAnalysis {
100 StatisticalMethod method_used { StatisticalMethod::MEAN };
101 uint32_t window_size {};
102 uint32_t hop_size {};
103
104 std::vector<ChannelStatistics> channel_statistics;
105};
106
107/**
108 * @class StatisticalAnalyzer
109 * @brief High-performance statistical analyzer with zero-copy processing
110 *
111 * The StatisticalAnalyzer provides comprehensive statistical analysis capabilities for
112 * digital data streams using span-based processing for maximum efficiency.
113 * All data extraction and conversion is handled automatically by OperationHelper.
114 *
115 * Example usage:
116 * ```cpp
117 * // DataVariant -> VectorXd analyzer
118 * auto stat_analyzer = std::make_shared<StatisticalAnalyzer<Kakshya::DataVariant, Eigen::VectorXd>>();
119 *
120 * // User-facing analysis
121 * auto analysis = stat_analyzer->analyze_data(numeric_data);
122 * auto stat_result = safe_any_cast<StatisticalAnalysisResult>(analysis);
123 *
124 * // Pipeline usage
125 * auto pipeline_output = stat_analyzer->apply_operation(IO{numeric_data});
126 * ```
127 */
128template <ComputeData InputType = std::vector<Kakshya::DataVariant>, ComputeData OutputType = Eigen::VectorXd>
129class MAYAFLUX_API StatisticalAnalyzer : public UniversalAnalyzer<InputType, OutputType> {
130public:
134
135 /**
136 * @brief Construct StatisticalAnalyzer with configurable window parameters
137 * @param window_size Size of analysis window in samples (default: 512)
138 * @param hop_size Step size between windows in samples (default: 256)
139 */
140 explicit StatisticalAnalyzer(uint32_t window_size = 512, uint32_t hop_size = 256)
141 : m_window_size(window_size)
142 , m_hop_size(hop_size)
143 {
144 validate_window_parameters();
145 }
146
147 /**
148 * @brief Type-safe statistical analysis method
149 * @param data Input data
150 * @return StatisticalAnalysisResult directly
151 */
153 {
154 auto result = this->analyze_data(data);
155 return safe_any_cast_or_throw<StatisticalAnalysis>(result);
156 }
157
159 {
160 return this->analyze_statistics(input_type { data });
161 }
162
163 /**
164 * @brief Get last statistical analysis result (type-safe)
165 * @return StatisticalAnalysisResult from last operation
166 */
168 {
169 return safe_any_cast_or_throw<StatisticalAnalysis>(this->get_current_analysis());
170 }
171
172 /**
173 * @brief Get analysis type category
174 * @return AnalysisType::STATISTICAL
175 */
176 [[nodiscard]] AnalysisType get_analysis_type() const override
177 {
178 return AnalysisType::STATISTICAL;
179 }
180
181 /**
182 * @brief Get available analysis methods
183 * @return Vector of supported statistical method names
184 */
185 [[nodiscard]] std::vector<std::string> get_available_methods() const override
186 {
187 return Reflect::get_enum_names_lowercase<StatisticalMethod>();
188 }
189
190 /**
191 * @brief Get supported methods for specific input type
192 * @tparam T Input type to check
193 * @return Vector of method names supported for this type
194 */
195 template <typename T>
196 [[nodiscard]] std::vector<std::string> get_methods_for_type() const
197 {
198 return get_methods_for_type_impl(std::type_index(typeid(T)));
199 }
200
201 /**
202 * @brief Check if analyzer supports given input type
203 * @tparam T Input type to check
204 * @return True if supported
205 */
206 template <typename T>
207 [[nodiscard]] bool supports_input_type() const
208 {
209 return !get_methods_for_type<T>().empty();
210 }
211
212 /**
213 * @brief Set statistical analysis method
214 * @param method StatisticalMethod enum value
215 */
217 {
218 m_method = method;
219 this->set_parameter("method", method_to_string(method));
220 }
221
222 /**
223 * @brief Set method by string name
224 * @param method_name String representation of method
225 */
226 void set_method(const std::string& method_name)
227 {
228 m_method = string_to_method(method_name);
229 this->set_parameter("method", method_name);
230 }
231
232 /**
233 * @brief Get current statistical method
234 * @return StatisticalMethod enum value
235 */
236 [[nodiscard]] StatisticalMethod get_method() const
237 {
238 return m_method;
239 }
240
241 /**
242 * @brief Set window size for windowed analysis
243 * @param size Window size in samples
244 */
245 void set_window_size(uint32_t size)
246 {
247 m_window_size = size;
248 validate_window_parameters();
249 }
250
251 /**
252 * @brief Set hop size for windowed analysis
253 * @param size Hop size in samples
254 */
255 void set_hop_size(uint32_t size)
256 {
257 m_hop_size = size;
258 validate_window_parameters();
259 }
260
261 /**
262 * @brief Get window size
263 * @return Current window size
264 */
265 [[nodiscard]] uint32_t get_window_size() const { return m_window_size; }
266
267 /**
268 * @brief Get hop size
269 * @return Current hop size
270 */
271 [[nodiscard]] uint32_t get_hop_size() const { return m_hop_size; }
272
273 /**
274 * @brief Enable/disable outlier classification
275 * @param enabled Whether to classify outliers
276 */
277 void set_classification_enabled(bool enabled)
278 {
279 m_classification_enabled = enabled;
280 }
281
282 /**
283 * @brief Check if classification is enabled
284 * @return True if classification enabled
285 */
286 [[nodiscard]] bool is_classification_enabled() const { return m_classification_enabled; }
287
288 /**
289 * @brief Classify statistical value qualitatively
290 * @param value Statistical value to classify
291 * @return StatisticalLevel classification
292 */
293 [[nodiscard]] StatisticalLevel classify_statistical_level(double value) const
294 {
295 if (std::abs(value) > m_outlier_threshold)
296 return StatisticalLevel::OUTLIER;
297 if (value <= m_extreme_low_threshold)
298 return StatisticalLevel::EXTREME_LOW;
299 if (value <= m_low_threshold)
300 return StatisticalLevel::LOW;
301 if (value <= m_high_threshold)
302 return StatisticalLevel::NORMAL;
303 if (value <= m_extreme_high_threshold)
304 return StatisticalLevel::HIGH;
305 return StatisticalLevel::EXTREME_HIGH;
306 }
307
308 /**
309 * @brief Convert statistical method enum to string
310 * @param method StatisticalMethod value
311 * @return String representation
312 */
313 static std::string method_to_string(StatisticalMethod method)
314 {
315 return Reflect::enum_to_lowercase_string(method);
316 }
317
318 /**
319 * @brief Convert string to statistical method enum
320 * @param str String representation
321 * @return StatisticalMethod value
322 */
323 static StatisticalMethod string_to_method(const std::string& str)
324 {
325 if (str == "default")
326 return StatisticalMethod::MEAN;
327 return Reflect::string_to_enum_or_throw_case_insensitive<StatisticalMethod>(str, "StatisticalMethod");
328 }
329
330 /**
331 * @brief Convert statistical level enum to string
332 * @param level StatisticalLevel value
333 * @return String representation
334 */
336 {
337 return Reflect::enum_to_lowercase_string(level);
338 }
339
340protected:
341 /**
342 * @brief Get analyzer name
343 * @return "StatisticalAnalyzer"
344 */
345 [[nodiscard]] std::string get_analyzer_name() const override
346 {
347 return "StatisticalAnalyzer";
348 }
349
350 /**
351 * @brief Core analysis implementation - creates analysis result AND pipeline output
352 * @param input Input data wrapped in Datum container
353 * @return Pipeline output (data flow for chaining operations)
354 */
356 {
357 if constexpr (requires { input.data.empty(); }) {
358 if (input.data.empty()) {
359 error<std::runtime_error>(Journal::Component::Yantra, Journal::Context::ComputeMatrix, std::source_location::current(), "Input is empty");
360 }
361 } else if constexpr (std::is_same_v<InputType, Kakshya::RegionGroup>) {
362 if (input.data.regions.empty()) {
363 error<std::runtime_error>(Journal::Component::Yantra, Journal::Context::ComputeMatrix, std::source_location::current(), "Input is empty");
364 }
365 }
366 try {
367 auto [data_span, structure_info] = OperationHelper::extract_structured_double(
368 const_cast<input_type&>(input));
369
370 std::vector<std::span<const double>> channel_spans;
371 for (const auto& span : data_span)
372 channel_spans.emplace_back(span.data(), span.size());
373
374 std::vector<std::vector<double>> stat_values;
375 stat_values.reserve(channel_spans.size());
376 for (const auto& ch_span : channel_spans) {
377 stat_values.push_back(compute_statistical_values(ch_span, m_method));
378 }
379
380 StatisticalAnalysis analysis_result = create_analysis_result(
381 stat_values, channel_spans, structure_info);
382
383 this->store_current_analysis(analysis_result);
384 return create_pipeline_output(input, analysis_result, structure_info);
385 } catch (const std::exception& e) {
386 MF_ERROR(Journal::Component::Yantra, Journal::Context::ComputeMatrix, "Statistical analysis failed: {}", e.what());
387 output_type error_result;
388 error_result.metadata = input.metadata;
389 error_result.metadata["error"] = std::string("Analysis failed: ") + e.what();
390 return error_result;
391 }
392 }
393
394 /**
395 * @brief Handle analysis-specific parameters
396 */
397 void set_analysis_parameter(const std::string& name, std::any value) override
398 {
399 try {
400 if (name == "method") {
401 try {
402 auto method_str = safe_any_cast_or_throw<std::string>(value);
403 m_method = string_to_method(method_str);
404 } catch (const std::runtime_error&) {
405 auto method_enum = safe_any_cast_or_throw<StatisticalMethod>(value);
406 m_method = method_enum;
407 }
408 } else if (name == "window_size") {
409 auto size = safe_any_cast_or_throw<uint32_t>(value);
410 m_window_size = size;
411 validate_window_parameters();
412 } else if (name == "hop_size") {
413 auto size = safe_any_cast_or_throw<uint32_t>(value);
414 m_hop_size = size;
415 validate_window_parameters();
416 } else if (name == "classification_enabled") {
417 auto enabled = safe_any_cast_or_throw<bool>(value);
418 m_classification_enabled = enabled;
419 } else if (name == "percentile") {
420 auto percentile = safe_any_cast_or_throw<double>(value);
421 if (percentile < 0.0 || percentile > 100.0) {
422 throw std::invalid_argument("Percentile must be between 0.0 and 100.0, got: " + std::to_string(percentile));
423 }
424 m_percentile_value = percentile;
425 } else if (name == "sample_variance") {
426 auto sample = safe_any_cast_or_throw<bool>(value);
427 m_sample_variance = sample;
428 } else {
429 base_type::set_analysis_parameter(name, std::move(value));
430 }
431 } catch (const std::runtime_error& e) {
432 error_rethrow(Journal::Component::Yantra, Journal::Context::ComputeMatrix, std::source_location::current(), "Failed to set parameter '{}': {}", name, e.what());
433 }
434 }
435
436 /**
437 * @brief Get analysis-specific parameter
438 */
439 [[nodiscard]] std::any get_analysis_parameter(const std::string& name) const override
440 {
441 if (name == "method")
442 return std::any(method_to_string(m_method));
443 if (name == "window_size")
444 return std::any(m_window_size);
445 if (name == "hop_size")
446 return std::any(m_hop_size);
447 if (name == "classification_enabled")
448 return std::any(m_classification_enabled);
449 if (name == "percentile")
450 return std::any(m_percentile_value);
451 if (name == "sample_variance")
452 return std::any(m_sample_variance);
453
454 return base_type::get_analysis_parameter(name);
455 }
456
457 /**
458 * @brief Get supported methods for specific type index
459 * @param type_info Type index to check
460 * @return Vector of supported method names
461 */
462 [[nodiscard]] std::vector<std::string> get_methods_for_type_impl(std::type_index /*type_info*/) const
463 {
464 return get_available_methods();
465 }
466
467private:
468 StatisticalMethod m_method { StatisticalMethod::MEAN };
470 uint32_t m_hop_size;
471 bool m_classification_enabled { true };
472 double m_percentile_value { 50.0 };
473 bool m_sample_variance { true };
474
475 double m_outlier_threshold { 3.0 };
476 double m_extreme_low_threshold { -2.0 };
477 double m_low_threshold { -1.0 };
478 double m_high_threshold { 1.0 };
479 double m_extreme_high_threshold { 2.0 };
480
481 /**
482 * @brief Validate window parameters
483 */
485 {
486 if (m_window_size == 0 || m_hop_size == 0) {
487 error<std::invalid_argument>(Journal::Component::Yantra, Journal::Context::ComputeMatrix, std::source_location::current(), "Window size and hop size must be greater than 0");
488 }
489 if (m_hop_size > m_window_size) {
490 error<std::invalid_argument>(Journal::Component::Yantra, Journal::Context::ComputeMatrix, std::source_location::current(), "Hop size should not exceed window size");
491 }
492 }
493
494 /**
495 * @brief Compute statistical values using span (zero-copy processing)
496 */
497 [[nodiscard]] std::vector<double> compute_statistical_values(std::span<const double> data, StatisticalMethod method) const
498 {
499 const size_t num_windows = calculate_num_windows(data.size());
500
501 namespace D = MayaFlux::Kinesis::Discrete;
502
503 switch (method) {
504 case StatisticalMethod::MEAN:
505 return D::mean(data, num_windows, m_hop_size, m_window_size);
506 case StatisticalMethod::VARIANCE:
507 return D::variance(data, num_windows, m_hop_size, m_window_size, m_sample_variance);
508 case StatisticalMethod::STD_DEV:
509 return D::std_dev(data, num_windows, m_hop_size, m_window_size, m_sample_variance);
510 case StatisticalMethod::SKEWNESS:
511 return D::skewness(data, num_windows, m_hop_size, m_window_size);
512 case StatisticalMethod::KURTOSIS:
513 return D::kurtosis(data, num_windows, m_hop_size, m_window_size);
514 case StatisticalMethod::MEDIAN:
515 return D::median(data, num_windows, m_hop_size, m_window_size);
516 case StatisticalMethod::PERCENTILE:
517 return D::percentile(data, num_windows, m_hop_size, m_window_size, m_percentile_value);
518 case StatisticalMethod::ENTROPY:
519 return D::entropy(data, num_windows, m_hop_size, m_window_size);
520 case StatisticalMethod::MIN:
521 return D::min(data, num_windows, m_hop_size, m_window_size);
522 case StatisticalMethod::MAX:
523 return D::max(data, num_windows, m_hop_size, m_window_size);
524 case StatisticalMethod::RANGE:
525 return D::range(data, num_windows, m_hop_size, m_window_size);
526 case StatisticalMethod::SUM:
527 return D::sum(data, num_windows, m_hop_size, m_window_size);
528 case StatisticalMethod::COUNT:
529 return D::count(data, num_windows, m_hop_size, m_window_size);
530 case StatisticalMethod::RMS:
531 return D::rms(data, num_windows, m_hop_size, m_window_size);
532 case StatisticalMethod::MAD:
533 return D::mad(data, num_windows, m_hop_size, m_window_size);
534 case StatisticalMethod::CV:
535 return D::coefficient_of_variation(data, num_windows, m_hop_size, m_window_size, m_sample_variance);
536 case StatisticalMethod::MODE:
537 return D::mode(data, num_windows, m_hop_size, m_window_size);
538 case StatisticalMethod::ZSCORE:
539 return D::mean_zscore(data, num_windows, m_hop_size, m_window_size, m_sample_variance);
540 default:
541 return D::mean(data, num_windows, m_hop_size, m_window_size);
542 }
543 }
544
545 /**
546 * @brief Calculate number of windows for given data size
547 */
548 [[nodiscard]] size_t calculate_num_windows(size_t data_size) const
549 {
550 if (data_size < m_window_size)
551 return 0;
552 return (data_size - m_window_size) / m_hop_size + 1;
553 }
554
555 /**
556 * @brief Create comprehensive analysis result
557 */
558 StatisticalAnalysis create_analysis_result(const std::vector<std::vector<double>>& stat_values,
559 std::vector<std::span<const double>> original_data, const auto& /*structure_info*/) const
560 {
561 namespace D = MayaFlux::Kinesis::Discrete;
562
563 StatisticalAnalysis result;
564 result.method_used = m_method;
565 result.window_size = m_window_size;
566 result.hop_size = m_hop_size;
567
568 if (stat_values.empty()) {
569 return result;
570 }
571
572 result.channel_statistics.resize(stat_values.size());
573
574 for (size_t ch = 0; ch < stat_values.size(); ++ch) {
575 auto& channel_result = result.channel_statistics[ch];
576 const auto& ch_stats = stat_values[ch];
577
578 channel_result.statistical_values = ch_stats;
579
580 if (ch_stats.empty())
581 continue;
582
583 const auto [min_it, max_it] = std::ranges::minmax_element(ch_stats);
584 channel_result.min_stat = *min_it;
585 channel_result.max_stat = *max_it;
586
587 const std::span<const double> sp(ch_stats);
588 const auto sz = static_cast<uint32_t>(ch_stats.size());
589
590 const auto single = [&](auto fn) { return fn(sp, 1, 0, sz)[0]; };
591
592 channel_result.mean_stat = single([](auto&&... a) { return D::mean(a...); });
593 channel_result.stat_variance = single([&](auto&&... a) { return D::variance(a..., m_sample_variance); });
594 channel_result.stat_std_dev = std::sqrt(channel_result.stat_variance);
595 channel_result.skewness = single([](auto&&... a) { return D::skewness(a...); });
596 channel_result.kurtosis = single([](auto&&... a) { return D::kurtosis(a...); });
597 channel_result.median = single([](auto&&... a) { return D::median(a...); });
598
599 channel_result.percentiles = {
600 D::percentile(sp, 1, 0, sz, 25.0)[0],
601 channel_result.median,
602 D::percentile(sp, 1, 0, sz, 75.0)[0]
603 };
604
605 const size_t data_size = (ch < original_data.size()) ? original_data[ch].size() : 0;
606 channel_result.window_positions.reserve(ch_stats.size());
607 for (size_t i = 0; i < ch_stats.size(); ++i) {
608 const size_t start = i * m_hop_size;
609 const size_t end = std::min(start + m_window_size, data_size);
610 channel_result.window_positions.emplace_back(start, end);
611 }
612
613 if (m_classification_enabled) {
614 channel_result.stat_classifications.reserve(ch_stats.size());
615 channel_result.level_counts.fill(0);
616
617 for (double value : ch_stats) {
618 const StatisticalLevel level = classify_statistical_level(value);
619 channel_result.stat_classifications.push_back(level);
620 channel_result.level_counts[static_cast<size_t>(level)]++;
621 }
622 }
623 }
624
625 return result;
626 }
627
628 /**
629 * @brief Create pipeline output for operation chaining
630 */
632 {
633 std::vector<std::vector<double>> channel_stats;
634 channel_stats.reserve(analysis_result.channel_statistics.size());
635 for (const auto& ch : analysis_result.channel_statistics) {
636 channel_stats.push_back(ch.statistical_values);
637 }
638
639 output_type output = this->convert_result(channel_stats, info);
640
641 output.metadata = input.metadata;
642
643 output.metadata["source_analyzer"] = "StatisticalAnalyzer";
644 output.metadata["statistical_method"] = method_to_string(analysis_result.method_used);
645 output.metadata["window_size"] = analysis_result.window_size;
646 output.metadata["hop_size"] = analysis_result.hop_size;
647 output.metadata["num_channels"] = analysis_result.channel_statistics.size();
648
649 if (!analysis_result.channel_statistics.empty()) {
650 std::vector<double> channel_means, channel_maxs, channel_mins, channel_variances, channel_stddevs, channel_skewness, channel_kurtosis, channel_medians;
651 std::vector<size_t> channel_window_counts;
652
653 for (const auto& ch : analysis_result.channel_statistics) {
654 channel_means.push_back(ch.mean_stat);
655 channel_maxs.push_back(ch.max_stat);
656 channel_mins.push_back(ch.min_stat);
657 channel_variances.push_back(ch.stat_variance);
658 channel_stddevs.push_back(ch.stat_std_dev);
659 channel_skewness.push_back(ch.skewness);
660 channel_kurtosis.push_back(ch.kurtosis);
661 channel_medians.push_back(ch.median);
662 channel_window_counts.push_back(ch.statistical_values.size());
663 }
664
665 output.metadata["mean_per_channel"] = channel_means;
666 output.metadata["max_per_channel"] = channel_maxs;
667 output.metadata["min_per_channel"] = channel_mins;
668 output.metadata["variance_per_channel"] = channel_variances;
669 output.metadata["stddev_per_channel"] = channel_stddevs;
670 output.metadata["skewness_per_channel"] = channel_skewness;
671 output.metadata["kurtosis_per_channel"] = channel_kurtosis;
672 output.metadata["median_per_channel"] = channel_medians;
673 output.metadata["window_count_per_channel"] = channel_window_counts;
674 }
675
676 return output;
677 }
678};
679
680/// Standard statistical analyzer: DataVariant -> MatrixXd
682
683/// Container statistical analyzer: SignalContainer -> MatrixXd
685
686/// Region statistical analyzer: Region -> MatrixXd
688
689/// Raw statistical analyzer: produces double vectors
690template <ComputeData InputType = std::vector<Kakshya::DataVariant>>
692
693/// Variant statistical analyzer: produces DataVariant output
694template <ComputeData InputType = std::vector<Kakshya::DataVariant>>
696
697/**
698 * @brief Extract a named scalar from a StatisticalAnalysis result.
699 *
700 * Maps qualifier strings to scalar fields of the first channel in @p analysis.
701 * All scalar-valued fields of ChannelStatistics are addressable.
702 *
703 * Supported qualifiers:
704 * - "mean_stat" arithmetic mean of the statistical values
705 * - "max_stat" maximum statistical value
706 * - "min_stat" minimum statistical value
707 * - "variance" variance of the statistical values
708 * - "std_dev" standard deviation
709 * - "skewness" third moment
710 * - "kurtosis" fourth moment
711 * - "median" 50th percentile
712 * - "window_count" number of analysis windows
713 *
714 * An empty qualifier resolves to "mean_stat".
715 * Unknown qualifiers fall back to mean_stat.
716 *
717 * @param analysis Result produced by StatisticalAnalyzer.
718 * @param qualifier Name of the scalar to extract.
719 * @return Extracted double value, or 0.0 if channel_statistics is empty.
720 */
721[[nodiscard]] MAYAFLUX_API inline double extract_scalar_statistics(
722 const StatisticalAnalysis& analysis, const std::string& qualifier)
723{
724 if (analysis.channel_statistics.empty())
725 return 0.0;
726
727 const auto& ch = analysis.channel_statistics[0];
728 const std::string q = qualifier.empty() ? "mean_stat" : qualifier;
729
730 if (q == "mean_stat")
731 return ch.mean_stat;
732 if (q == "max_stat")
733 return ch.max_stat;
734 if (q == "min_stat")
735 return ch.min_stat;
736 if (q == "variance")
737 return ch.stat_variance;
738 if (q == "std_dev")
739 return ch.stat_std_dev;
740 if (q == "skewness")
741 return ch.skewness;
742 if (q == "kurtosis")
743 return ch.kurtosis;
744 if (q == "median")
745 return ch.median;
746 if (q == "window_count")
747 return static_cast<double>(ch.statistical_values.size());
748
749 return ch.mean_stat;
750}
751
752} // namespace MayaFlux::Yantra
Discrete sequence analysis primitives for MayaFlux::Kinesis.
#define MF_ERROR(comp, ctx,...)
size_t a
double q
Range size
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)
StatisticalAnalysis analyze_statistics(const input_type &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)
@ VARIANCE
Population or sample variance.
@ SKEWNESS
Third moment - asymmetry measure.
MAYAFLUX_API double extract_scalar_statistics(const StatisticalAnalysis &analysis, const std::string &qualifier)
Extract a named scalar from a StatisticalAnalysis result.
std::map< std::string, std::any > method_specific_data
std::vector< std::pair< size_t, size_t > > window_positions
std::vector< StatisticalLevel > stat_classifications
Statistical results for a single data channel.
Metadata about data structure for reconstruction.
T data
The actual computation data.
Definition DataIO.hpp:25
std::unordered_map< std::string, std::any > metadata
Associated metadata.
Definition DataIO.hpp:28
Input/Output container for computation pipeline data flow with structure preservation.
Definition DataIO.hpp:24
std::vector< ChannelStatistics > channel_statistics
Analysis result structure for statistical analysis.