MayaFlux 0.3.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 /**
128 * @brief Type-safe parameter management with sorting-specific defaults
129 */
130 void set_parameter(const std::string& name, std::any value) override
131 {
132 if (name == "strategy") {
133 auto strategy_result = safe_any_cast<SortingStrategy>(value);
134 if (strategy_result) {
135 m_strategy = *strategy_result.value;
136 return;
137 }
138 auto str_result = safe_any_cast<std::string>(value);
139 if (str_result) {
140 auto strategy_enum = Reflect::string_to_enum_case_insensitive<SortingStrategy>(*str_result.value);
141 if (strategy_enum) {
142 m_strategy = *strategy_enum;
143 return;
144 }
145 }
146 }
147 if (name == "direction") {
148 auto direction_result = safe_any_cast<SortingDirection>(value);
149 if (direction_result) {
150 m_direction = *direction_result.value;
151 return;
152 }
153 auto str_result = safe_any_cast<std::string>(value);
154 if (str_result) {
155 auto direction_enum = Reflect::string_to_enum_case_insensitive<SortingDirection>(*str_result.value);
156 if (direction_enum) {
157 m_direction = *direction_enum;
158 return;
159 }
160 }
161 }
162 if (name == "granularity") {
163 auto granularity_result = safe_any_cast<SortingGranularity>(value);
164 if (granularity_result) {
165 m_granularity = *granularity_result.value;
166 return;
167 }
168 auto str_result = safe_any_cast<std::string>(value);
169 if (str_result) {
170 auto granularity_enum = Reflect::string_to_enum_case_insensitive<SortingGranularity>(*str_result.value);
171 if (granularity_enum) {
172 m_granularity = *granularity_enum;
173 return;
174 }
175 }
176 }
177 set_sorting_parameter(name, std::move(value));
178 }
179
180 [[nodiscard]] std::any get_parameter(const std::string& name) const override
181 {
182 if (name == "strategy") {
183 return m_strategy;
184 }
185 if (name == "direction") {
186 return m_direction;
187 }
188 if (name == "granularity") {
189 return m_granularity;
190 }
191 return get_sorting_parameter(name);
192 }
193
194 [[nodiscard]] std::map<std::string, std::any> get_all_parameters() const override
195 {
196 auto params = get_all_sorting_parameters();
197 params["strategy"] = m_strategy;
198 params["direction"] = m_direction;
199 params["granularity"] = m_granularity;
200 return params;
201 }
202
203 /**
204 * @brief Type-safe parameter access with defaults
205 * @tparam T Parameter type
206 * @param name Parameter name
207 * @param default_value Default if not found/wrong type
208 * @return Parameter value or default
209 */
210 template <typename T>
211 T get_parameter_or_default(const std::string& name, const T& default_value) const
212 {
213 auto param = get_sorting_parameter(name);
214 return safe_any_cast_or_default<T>(param, default_value);
215 }
216
217 /**
218 * @brief Configure sorting strategy
219 */
220 void set_strategy(SortingStrategy strategy) { m_strategy = strategy; }
221 SortingStrategy get_strategy() const { return m_strategy; }
222
223 /**
224 * @brief Configure sorting direction
225 */
226 void set_direction(SortingDirection direction) { m_direction = direction; }
227 SortingDirection get_direction() const { return m_direction; }
228
229 /**
230 * @brief Configure output granularity
231 */
232 void set_granularity(SortingGranularity granularity) { m_granularity = granularity; }
233 SortingGranularity get_granularity() const { return m_granularity; }
234
235 /**
236 * @brief Add multi-key sorting capability
237 * @param keys Vector of sort keys for complex sorting
238 */
239 void set_sort_keys(const std::vector<SortKey>& keys) { m_sort_keys = keys; }
240 const std::vector<SortKey>& get_sort_keys() const { return m_sort_keys; }
241
242 /**
243 * @brief Configure custom comparator for CUSTOM direction
244 * @param comparator Custom comparison function
245 */
246 template <typename T>
247 void set_custom_comparator(std::function<bool(const T&, const T&)> comparator)
248 {
249 m_custom_comparator = [comparator](const std::any& a, const std::any& b) -> bool {
250 auto val_a_result = safe_any_cast<T>(a);
251 auto val_b_result = safe_any_cast<T>(b);
252 if (val_a_result && val_b_result) {
253 return comparator(*val_a_result, *val_b_result);
254 }
255 return false;
256 };
257 }
258
259protected:
260 /**
261 * @brief Core operation implementation - called by ComputeOperation interface
262 * @param input Input data with metadata
263 * @return Output data with metadata
264 */
266 {
267 auto raw_result = sort_implementation(input);
268 return apply_granularity_formatting(raw_result);
269 }
270
271 /**
272 * @brief Pure virtual sorting implementation - derived classes implement this
273 * @param input Input data with metadata
274 * @return Raw sorting output before granularity processing
275 */
276 virtual output_type sort_implementation(const input_type& input) = 0;
277
278 /**
279 * @brief Get sorter-specific name (derived classes override this)
280 * @return Sorter name string
281 */
282 [[nodiscard]] virtual std::string get_sorter_name() const { return "UniversalSorter"; }
283
284 /**
285 * @brief Sorting-specific parameter handling (override for custom parameters)
286 */
287 virtual void set_sorting_parameter(const std::string& name, std::any value)
288 {
289 m_parameters[name] = std::move(value);
290 }
291
292 [[nodiscard]] virtual std::any get_sorting_parameter(const std::string& name) const
293 {
294 auto it = m_parameters.find(name);
295 return (it != m_parameters.end()) ? it->second : std::any {};
296 }
297
298 [[nodiscard]] virtual std::map<std::string, std::any> get_all_sorting_parameters() const
299 {
300 return m_parameters;
301 }
302
303 /**
304 * @brief Input validation (override for custom validation logic)
305 */
306 virtual bool validate_sorting_input(const input_type& /*input*/) const
307 {
308 // Default: accept any input that satisfies ComputeData concept
309 return true;
310 }
311
312 /**
313 * @brief Apply granularity-based output formatting
314 * @param raw_output Raw sorting results
315 * @return Formatted output based on granularity setting
316 */
318 {
319 switch (m_granularity) {
320 case SortingGranularity::RAW_DATA:
321 return raw_output;
322
323 case SortingGranularity::ATTRIBUTED_INDICES:
324 return add_sorting_metadata(raw_output);
325
326 case SortingGranularity::ORGANIZED_GROUPS:
327 return organize_into_groups(raw_output);
328
329 case SortingGranularity::DETAILED_ANALYSIS:
330 return create_sorting_analysis(raw_output);
331
332 default:
333 return raw_output;
334 }
335 }
336
337 /**
338 * @brief Add sorting metadata to results (override for custom attribution)
339 */
341 {
342 output_type attributed = raw_output;
343 attributed.metadata["sorting_type"] = static_cast<int>(get_sorting_type());
344 attributed.metadata["sorter_name"] = get_sorter_name();
345 attributed.metadata["strategy"] = static_cast<int>(m_strategy);
346 attributed.metadata["direction"] = static_cast<int>(m_direction);
347 attributed.metadata["granularity"] = static_cast<int>(m_granularity);
348 return attributed;
349 }
350
351 /**
352 * @brief Organize results into hierarchical groups (override for custom grouping)
353 */
355 {
356 // Default implementation: just add grouping metadata
357 return add_sorting_metadata(raw_output);
358 }
359
360 /**
361 * @brief Create detailed sorting analysis (override for custom analysis)
362 */
364 {
365 // Default implementation: add analysis metadata
366 auto analysis = add_sorting_metadata(raw_output);
367 analysis.metadata["is_analysis"] = true;
368 analysis.metadata["sort_keys_count"] = m_sort_keys.size();
369 return analysis;
370 }
371
372 /**
373 * @brief Helper to check if custom comparator is available
374 */
375 bool has_custom_comparator() const { return m_custom_comparator != nullptr; }
376
377 /**
378 * @brief Apply custom comparator if available
379 */
380 bool apply_custom_comparator(const std::any& a, const std::any& b) const
381 {
382 if (m_custom_comparator) {
383 return m_custom_comparator(a, b);
384 }
385 return false;
386 }
387
388 /**
389 * @brief Apply multi-key sorting if keys are configured
390 */
391 virtual bool should_use_multi_key_sorting() const
392 {
393 return !m_sort_keys.empty();
394 }
395
396 /**
397 * @brief Current sorting operation storage for complex operations
398 */
399 mutable std::any m_current_sorting;
400
401 template <typename SortingResultType>
402 void store_current_sorting(SortingResultType&& result) const
403 {
404 m_current_sorting = std::forward<SortingResultType>(result);
405 }
406
408
409private:
410 SortingStrategy m_strategy = SortingStrategy::COPY_SORT;
411 SortingDirection m_direction = SortingDirection::ASCENDING;
412 SortingGranularity m_granularity = SortingGranularity::RAW_DATA;
413 std::map<std::string, std::any> m_parameters;
414
415 std::vector<SortKey> m_sort_keys;
416 std::function<bool(const std::any&, const std::any&)> m_custom_comparator;
417};
418
419/// Sorter that takes DataVariant and produces DataVariant
420template <ComputeData OutputType = std::vector<Kakshya::DataVariant>>
422
423/// Sorter for signal container processing
424template <ComputeData OutputType = std::shared_ptr<Kakshya::SignalSourceContainer>>
426
427/// Sorter for region-based sorting
428template <ComputeData OutputType = Kakshya::Region>
430
431/// Sorter for region group processing
432template <ComputeData OutputType = Kakshya::RegionGroup>
434
435/// Sorter for segment processing
436template <ComputeData OutputType = std::vector<Kakshya::RegionSegment>>
438
439/// Sorter that produces Eigen matrices
440template <ComputeData InputType = std::vector<Kakshya::DataVariant>>
442
443/// Sorter that produces Eigen vectors
444template <ComputeData InputType = std::vector<Kakshya::DataVariant>>
446
447/// Sorter for vector containers
448template <typename T, ComputeData OutputType = std::vector<std::vector<T>>>
450
451/// Sorter for indices generation
452template <ComputeData InputType = std::vector<Kakshya::DataVariant>>
454
455// ============================================================================
456// UNIVERSAL COMPUTE DATA FUNCTIONS
457// ============================================================================
458
459} // 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
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.
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