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