MayaFlux 0.1.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
UniversalSorter.hpp
Go to the documentation of this file.
1#pragma once
2
5
6/**
7 * @file UniversalSorter.hpp
8 * @brief Modern, digital-first universal sorting framework for Maya Flux
9 *
10 * The UniversalSorter system provides a clean, extensible foundation for data sorting
11 * in the Maya Flux ecosystem. Unlike traditional sorting which operates on simple containers,
12 * this embraces the digital paradigm: data-driven workflows, composability, and type safety.
13 *
14 * ## Core Philosophy
15 * A sorter **organizes ComputeData** through digital-first approaches:
16 * 1. **Algorithmic sorting:** Advanced mathematical operations, not simple comparisons
17 * 2. **Multi-dimensional sorting:** N-dimensional sort keys, not just single values
18 * 3. **Temporal sorting:** Sort based on time-series patterns, predictions
19 * 4. **Cross-modal sorting:** Sort audio by visual features, video by audio, etc.
20 * 5. **Computational sorting:** Leverage digital capabilities beyond analog metaphors
21 *
22 * ## Key Features
23 * - **Universal input/output:** Template-based I/O types defined at instantiation
24 * - **Type-safe sorting:** C++20 concepts and compile-time guarantees
25 * - **Sorting strategies:** Algorithmic, pattern-based, predictive
26 * - **Composable operations:** Integrates with ComputeMatrix execution modes
27 * - **Digital-first design:** Embraces computational possibilities beyond analog metaphors
28 *
29 * ## Usage Examples
30 * ```cpp
31 * // Sort DataVariant containing vectors
32 * auto sorter = std::make_shared<MySorter<Kakshya::DataVariant>>();
33 *
34 * // Sort regions by custom criteria
35 * auto region_sorter = std::make_shared<MySorter<
36 * std::vector<Kakshya::Region>,
37 * std::vector<Kakshya::Region>>>();
38 *
39 * // Sort with mathematical transformation
40 * auto matrix_sorter = std::make_shared<MySorter<
41 * Eigen::MatrixXd,
42 * Eigen::MatrixXd>>();
43 * ```
44 */
45
46namespace MayaFlux::Yantra {
47
48/**
49 * @enum SortingType
50 * @brief Categories of sorting operations for discovery and organization
51 */
52enum class SortingType : uint8_t {
53 STANDARD, ///< Traditional comparison-based sorting
54 ALGORITHMIC, ///< Mathematical/computational sorting algorithms
55 PATTERN_BASED, ///< Sort based on pattern recognition
56 TEMPORAL, ///< Time-series aware sorting
57 SPATIAL, ///< Multi-dimensional spatial sorting
58 PREDICTIVE, ///< ML/AI-based predictive sorting
59 CROSS_MODAL, ///< Sort one modality by features of another
60 RECURSIVE, ///< Recursive/hierarchical sorting
61 CUSTOM ///< User-defined sorting types
62};
63
64/**
65 * @enum SortingStrategy
66 * @brief Sorting execution strategies
67 */
68enum class SortingStrategy : uint8_t {
69 IN_PLACE, ///< Sort data in-place (modifies input)
70 COPY_SORT, ///< Create sorted copy (preserves input)
71 INDEX_ONLY, ///< Generate sort indices only
72 PARTIAL_SORT, ///< Sort only top-K elements
73 LAZY_SORT, ///< Lazy evaluation sorting (future: coroutines)
74 CHUNKED_SORT, ///< Sort in chunks for large datasets
75 PARALLEL_SORT ///< Parallel/concurrent sorting
76};
77
78/**
79 * @enum SortingDirection
80 * @brief Basic sort direction for simple comparisons
81 */
82enum class SortingDirection : uint8_t {
83 ASCENDING, ///< Smallest to largest
84 DESCENDING, ///< Largest to smallest
85 CUSTOM, ///< Use custom comparator function
86 BIDIRECTIONAL ///< Sort with both directions (for special algorithms)
87};
88
89/**
90 * @enum SortingGranularity
91 * @brief Output granularity control for sorting results
92 */
93enum class SortingGranularity : uint8_t {
94 RAW_DATA, ///< Direct sorted data
95 ATTRIBUTED_INDICES, ///< Sort indices with metadata
96 ORGANIZED_GROUPS, ///< Hierarchically organized sorted data
97 DETAILED_ANALYSIS ///< Sorting analysis with statistics
98};
99
100/**
101 * @struct SortKey
102 * @brief Multi-dimensional sort key specification for complex sorting
103 */
104struct MAYAFLUX_API SortKey {
105 std::string name;
106 std::function<double(const std::any&)> extractor; ///< Extract sort value from data
107 SortingDirection direction = SortingDirection::ASCENDING;
108 double weight = 1.0; ///< Weight for multi-key sorting
109 bool normalize = false; ///< Normalize values before sorting
110
111 SortKey(std::string n, std::function<double(const std::any&)> e)
112 : name(std::move(n))
113 , extractor(std::move(e))
114 {
115 }
116};
117
118/**
119 * @class UniversalSorter
120 * @brief Template-flexible sorter base with instance-defined I/O types
121 *
122 * The UniversalSorter provides a clean, concept-based foundation for all sorting
123 * operations. I/O types are defined at instantiation time, providing maximum flexibility
124 * while maintaining type safety through C++20 concepts.
125 *
126 * Unlike traditional sorters that only handle simple containers, this embraces the
127 * digital paradigm with analyzer delegation, cross-modal sorting, and computational
128 * approaches that go beyond analog metaphors.
129 */
130template <ComputeData InputType = std::vector<Kakshya::DataVariant>, ComputeData OutputType = InputType>
131class MAYAFLUX_API UniversalSorter : public ComputeOperation<InputType, OutputType> {
132public:
136
137 virtual ~UniversalSorter() = default;
138
139 /**
140 * @brief Gets the sorting type category for this sorter
141 * @return SortingType enum value
142 */
143 [[nodiscard]] virtual SortingType get_sorting_type() const = 0;
144
145 /**
146 * @brief Gets human-readable name for this sorter
147 * @return String identifier for the sorter
148 */
149 [[nodiscard]] std::string get_name() const override
150 {
151 return get_sorter_name();
152 }
153
154 /**
155 * @brief Type-safe parameter management with sorting-specific defaults
156 */
157 void set_parameter(const std::string& name, std::any value) override
158 {
159 if (name == "strategy") {
160 auto strategy_result = safe_any_cast<SortingStrategy>(value);
161 if (strategy_result) {
162 m_strategy = *strategy_result.value;
163 return;
164 }
165 auto str_result = safe_any_cast<std::string>(value);
166 if (str_result) {
167 auto strategy_enum = Utils::string_to_enum_case_insensitive<SortingStrategy>(*str_result.value);
168 if (strategy_enum) {
169 m_strategy = *strategy_enum;
170 return;
171 }
172 }
173 }
174 if (name == "direction") {
175 auto direction_result = safe_any_cast<SortingDirection>(value);
176 if (direction_result) {
177 m_direction = *direction_result.value;
178 return;
179 }
180 auto str_result = safe_any_cast<std::string>(value);
181 if (str_result) {
182 auto direction_enum = Utils::string_to_enum_case_insensitive<SortingDirection>(*str_result.value);
183 if (direction_enum) {
184 m_direction = *direction_enum;
185 return;
186 }
187 }
188 }
189 if (name == "granularity") {
190 auto granularity_result = safe_any_cast<SortingGranularity>(value);
191 if (granularity_result) {
192 m_granularity = *granularity_result.value;
193 return;
194 }
195 auto str_result = safe_any_cast<std::string>(value);
196 if (str_result) {
197 auto granularity_enum = Utils::string_to_enum_case_insensitive<SortingGranularity>(*str_result.value);
198 if (granularity_enum) {
199 m_granularity = *granularity_enum;
200 return;
201 }
202 }
203 }
204 set_sorting_parameter(name, std::move(value));
205 }
206
207 [[nodiscard]] std::any get_parameter(const std::string& name) const override
208 {
209 if (name == "strategy") {
210 return m_strategy;
211 }
212 if (name == "direction") {
213 return m_direction;
214 }
215 if (name == "granularity") {
216 return m_granularity;
217 }
218 return get_sorting_parameter(name);
219 }
220
221 [[nodiscard]] std::map<std::string, std::any> get_all_parameters() const override
222 {
223 auto params = get_all_sorting_parameters();
224 params["strategy"] = m_strategy;
225 params["direction"] = m_direction;
226 params["granularity"] = m_granularity;
227 return params;
228 }
229
230 /**
231 * @brief Type-safe parameter access with defaults
232 * @tparam T Parameter type
233 * @param name Parameter name
234 * @param default_value Default if not found/wrong type
235 * @return Parameter value or default
236 */
237 template <typename T>
238 T get_parameter_or_default(const std::string& name, const T& default_value) const
239 {
240 auto param = get_sorting_parameter(name);
241 return safe_any_cast_or_default<T>(param, default_value);
242 }
243
244 /**
245 * @brief Configure sorting strategy
246 */
247 void set_strategy(SortingStrategy strategy) { m_strategy = strategy; }
248 SortingStrategy get_strategy() const { return m_strategy; }
249
250 /**
251 * @brief Configure sorting direction
252 */
253 void set_direction(SortingDirection direction) { m_direction = direction; }
254 SortingDirection get_direction() const { return m_direction; }
255
256 /**
257 * @brief Configure output granularity
258 */
259 void set_granularity(SortingGranularity granularity) { m_granularity = granularity; }
260 SortingGranularity get_granularity() const { return m_granularity; }
261
262 /**
263 * @brief Add multi-key sorting capability
264 * @param keys Vector of sort keys for complex sorting
265 */
266 void set_sort_keys(const std::vector<SortKey>& keys) { m_sort_keys = keys; }
267 const std::vector<SortKey>& get_sort_keys() const { return m_sort_keys; }
268
269 /**
270 * @brief Configure custom comparator for CUSTOM direction
271 * @param comparator Custom comparison function
272 */
273 template <typename T>
274 void set_custom_comparator(std::function<bool(const T&, const T&)> comparator)
275 {
276 m_custom_comparator = [comparator](const std::any& a, const std::any& b) -> bool {
277 auto val_a_result = safe_any_cast<T>(a);
278 auto val_b_result = safe_any_cast<T>(b);
279 if (val_a_result && val_b_result) {
280 return comparator(*val_a_result, *val_b_result);
281 }
282 return false;
283 };
284 }
285
286protected:
287 /**
288 * @brief Core operation implementation - called by ComputeOperation interface
289 * @param input Input data with metadata
290 * @return Output data with metadata
291 */
293 {
294 auto raw_result = sort_implementation(input);
295 return apply_granularity_formatting(raw_result);
296 }
297
298 /**
299 * @brief Pure virtual sorting implementation - derived classes implement this
300 * @param input Input data with metadata
301 * @return Raw sorting output before granularity processing
302 */
303 virtual output_type sort_implementation(const input_type& input) = 0;
304
305 /**
306 * @brief Get sorter-specific name (derived classes override this)
307 * @return Sorter name string
308 */
309 [[nodiscard]] virtual std::string get_sorter_name() const { return "UniversalSorter"; }
310
311 /**
312 * @brief Sorting-specific parameter handling (override for custom parameters)
313 */
314 virtual void set_sorting_parameter(const std::string& name, std::any value)
315 {
316 m_parameters[name] = std::move(value);
317 }
318
319 [[nodiscard]] virtual std::any get_sorting_parameter(const std::string& name) const
320 {
321 auto it = m_parameters.find(name);
322 return (it != m_parameters.end()) ? it->second : std::any {};
323 }
324
325 [[nodiscard]] virtual std::map<std::string, std::any> get_all_sorting_parameters() const
326 {
327 return m_parameters;
328 }
329
330 /**
331 * @brief Input validation (override for custom validation logic)
332 */
333 virtual bool validate_sorting_input(const input_type& /*input*/) const
334 {
335 // Default: accept any input that satisfies ComputeData concept
336 return true;
337 }
338
339 /**
340 * @brief Apply granularity-based output formatting
341 * @param raw_output Raw sorting results
342 * @return Formatted output based on granularity setting
343 */
345 {
346 switch (m_granularity) {
347 case SortingGranularity::RAW_DATA:
348 return raw_output;
349
350 case SortingGranularity::ATTRIBUTED_INDICES:
351 return add_sorting_metadata(raw_output);
352
353 case SortingGranularity::ORGANIZED_GROUPS:
354 return organize_into_groups(raw_output);
355
356 case SortingGranularity::DETAILED_ANALYSIS:
357 return create_sorting_analysis(raw_output);
358
359 default:
360 return raw_output;
361 }
362 }
363
364 /**
365 * @brief Add sorting metadata to results (override for custom attribution)
366 */
368 {
369 output_type attributed = raw_output;
370 attributed.metadata["sorting_type"] = static_cast<int>(get_sorting_type());
371 attributed.metadata["sorter_name"] = get_sorter_name();
372 attributed.metadata["strategy"] = static_cast<int>(m_strategy);
373 attributed.metadata["direction"] = static_cast<int>(m_direction);
374 attributed.metadata["granularity"] = static_cast<int>(m_granularity);
375 return attributed;
376 }
377
378 /**
379 * @brief Organize results into hierarchical groups (override for custom grouping)
380 */
382 {
383 // Default implementation: just add grouping metadata
384 return add_sorting_metadata(raw_output);
385 }
386
387 /**
388 * @brief Create detailed sorting analysis (override for custom analysis)
389 */
391 {
392 // Default implementation: add analysis metadata
393 auto analysis = add_sorting_metadata(raw_output);
394 analysis.metadata["is_analysis"] = true;
395 analysis.metadata["sort_keys_count"] = m_sort_keys.size();
396 return analysis;
397 }
398
399 /**
400 * @brief Helper to check if custom comparator is available
401 */
402 bool has_custom_comparator() const { return m_custom_comparator != nullptr; }
403
404 /**
405 * @brief Apply custom comparator if available
406 */
407 bool apply_custom_comparator(const std::any& a, const std::any& b) const
408 {
409 if (m_custom_comparator) {
410 return m_custom_comparator(a, b);
411 }
412 return false;
413 }
414
415 /**
416 * @brief Apply multi-key sorting if keys are configured
417 */
418 virtual bool should_use_multi_key_sorting() const
419 {
420 return !m_sort_keys.empty();
421 }
422
423 /**
424 * @brief Current sorting operation storage for complex operations
425 */
426 mutable std::any m_current_sorting;
427
428 template <typename SortingResultType>
429 void store_current_sorting(SortingResultType&& result) const
430 {
431 m_current_sorting = std::forward<SortingResultType>(result);
432 }
433
435
436private:
437 SortingStrategy m_strategy = SortingStrategy::COPY_SORT;
438 SortingDirection m_direction = SortingDirection::ASCENDING;
439 SortingGranularity m_granularity = SortingGranularity::RAW_DATA;
440 std::map<std::string, std::any> m_parameters;
441
442 std::vector<SortKey> m_sort_keys;
443 std::function<bool(const std::any&, const std::any&)> m_custom_comparator;
444};
445
446/// Sorter that takes DataVariant and produces DataVariant
447template <ComputeData OutputType = std::vector<Kakshya::DataVariant>>
449
450/// Sorter for signal container processing
451template <ComputeData OutputType = std::shared_ptr<Kakshya::SignalSourceContainer>>
453
454/// Sorter for region-based sorting
455template <ComputeData OutputType = Kakshya::Region>
457
458/// Sorter for region group processing
459template <ComputeData OutputType = Kakshya::RegionGroup>
461
462/// Sorter for segment processing
463template <ComputeData OutputType = std::vector<Kakshya::RegionSegment>>
465
466/// Sorter that produces Eigen matrices
467template <ComputeData InputType = std::vector<Kakshya::DataVariant>>
469
470/// Sorter that produces Eigen vectors
471template <ComputeData InputType = std::vector<Kakshya::DataVariant>>
473
474/// Sorter for vector containers
475template <typename T, ComputeData OutputType = std::vector<std::vector<T>>>
477
478/// Sorter for indices generation
479template <ComputeData InputType = std::vector<Kakshya::DataVariant>>
481
482} // namespace MayaFlux::Yantra
Base interface for all computational operations in the processing pipeline.
void set_custom_comparator(std::function< bool(const T &, const T &)> comparator)
Configure custom comparator for CUSTOM direction.
void set_sort_keys(const std::vector< SortKey > &keys)
Add multi-key sorting capability.
virtual output_type add_sorting_metadata(const output_type &raw_output)
Add sorting metadata to results (override for custom attribution)
virtual output_type organize_into_groups(const output_type &raw_output)
Organize results into hierarchical groups (override for custom grouping)
virtual std::any get_sorting_parameter(const std::string &name) const
virtual ~UniversalSorter()=default
SortingStrategy get_strategy() const
virtual void set_sorting_parameter(const std::string &name, std::any value)
Sorting-specific parameter handling (override for custom parameters)
virtual output_type apply_granularity_formatting(const output_type &raw_output)
Apply granularity-based output formatting.
std::function< bool(const std::any &, const std::any &)> m_custom_comparator
virtual SortingType get_sorting_type() const =0
Gets the sorting type category for this sorter.
virtual bool should_use_multi_key_sorting() const
Apply multi-key sorting if keys are configured.
std::any get_parameter(const std::string &name) const override
Retrieves a parameter's current value.
std::any m_current_sorting
Current sorting operation storage for complex operations.
void set_strategy(SortingStrategy strategy)
Configure sorting strategy.
std::map< std::string, std::any > m_parameters
bool has_custom_comparator() const
Helper to check if custom comparator is available.
T get_parameter_or_default(const std::string &name, const T &default_value) const
Type-safe parameter access with defaults.
void set_granularity(SortingGranularity granularity)
Configure output granularity.
SortingGranularity get_granularity() const
virtual std::string get_sorter_name() const
Get sorter-specific name (derived classes override this)
const std::vector< SortKey > & get_sort_keys() const
virtual output_type create_sorting_analysis(const output_type &raw_output)
Create detailed sorting analysis (override for custom analysis)
void store_current_sorting(SortingResultType &&result) const
virtual std::map< std::string, std::any > get_all_sorting_parameters() const
void set_parameter(const std::string &name, std::any value) override
Type-safe parameter management with sorting-specific defaults.
std::map< std::string, std::any > get_all_parameters() const override
Retrieves all parameters and their values.
void set_direction(SortingDirection direction)
Configure sorting direction.
output_type operation_function(const input_type &input) override
Core operation implementation - called by ComputeOperation interface.
bool apply_custom_comparator(const std::any &a, const std::any &b) const
Apply custom comparator if available.
SortingDirection get_direction() const
virtual bool validate_sorting_input(const input_type &) const
Input validation (override for custom validation logic)
virtual output_type sort_implementation(const input_type &input)=0
Pure virtual sorting implementation - derived classes implement this.
std::string get_name() const override
Gets human-readable name for this sorter.
Template-flexible sorter base with instance-defined I/O types.
@ TEMPORAL
Time-based patterns, onset detection.
@ CUSTOM
User-defined analysis types.
@ SPATIAL
Multi-dimensional geometric analysis.
@ RECURSIVE
Recursive/nested extraction.
@ PATTERN_BASED
Extract based on pattern recognition.
SortingStrategy
Sorting execution strategies.
@ LAZY_SORT
Lazy evaluation sorting (future: coroutines)
@ PARTIAL_SORT
Sort only top-K elements.
@ IN_PLACE
Sort data in-place (modifies input)
@ COPY_SORT
Create sorted copy (preserves input)
@ CHUNKED_SORT
Sort in chunks for large datasets.
@ PARALLEL_SORT
Parallel/concurrent sorting.
@ INDEX_ONLY
Generate sort indices only.
SortingType
Categories of sorting operations for discovery and organization.
@ CROSS_MODAL
Sort one modality by features of another.
@ PREDICTIVE
ML/AI-based predictive sorting.
@ ALGORITHMIC
Mathematical/computational sorting algorithms.
@ ORGANIZED_GROUPS
Hierarchically organized results.
SortingDirection
Basic sort direction for simple comparisons.
@ BIDIRECTIONAL
Sort with both directions (for special algorithms)
@ ASCENDING
Smallest to largest.
@ DESCENDING
Largest to smallest.
@ STANDARD
std::sort with comparator
SortingGranularity
Output granularity control for sorting results.
@ DETAILED_ANALYSIS
Sorting analysis with statistics.
@ ATTRIBUTED_INDICES
Sort indices with metadata.
void normalize(std::vector< double > &data, double target_peak)
Normalize single-channel data to specified peak level (in-place)
Definition Yantra.cpp:558
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::function< double(const std::any &)> extractor
Extract sort value from data.
SortKey(std::string n, std::function< double(const std::any &)> e)
Multi-dimensional sort key specification for complex sorting.