MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
OperationRegistry.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "GrammarHelper.hpp"
6
7namespace MayaFlux::Yantra {
8
9namespace detail {
10 template <typename T>
11 struct UnwrapEnum {
12 using type = T;
13 };
14
15 template <typename E>
16 struct UnwrapEnum<Reflect::EnumByte<E>> {
17 using type = E;
18 };
19
20 template <typename Config>
21 constexpr auto selector_field()
22 {
23 if constexpr (requires { std::declval<Config&>().method; }) {
24 return std::type_identity<decltype(std::declval<Config&>().method)> {};
25 } else if constexpr (requires { std::declval<Config&>().operation; }) {
26 return std::type_identity<decltype(std::declval<Config&>().operation)> {};
27 } else if constexpr (requires { std::declval<Config&>().algorithm; }) {
28 return std::type_identity<decltype(std::declval<Config&>().algorithm)> {};
29 } else {
30 return std::type_identity<void> {};
31 }
32 }
33}
34
35/** @brief The enum a config selects its method from, or void when it has no selector. */
36template <typename Config>
38 typename decltype(detail::selector_field<Config>())::type>::type;
39
40/** @brief Explicitly owned registrations connecting enum vocabularies, configs, and implementations. */
42public:
43 /** @brief A constructed implementation with its erased input and execution contracts. */
44 struct Binding {
45 std::type_index type { typeid(void) };
47 std::function<std::any(const std::any&, const ExecutionContext&)> executor;
48 int priority { 50 };
51 bool sticky { false };
52 };
53
54 /** @brief Catalog an implementation for an enum vocabulary. A factory may supply its dependencies. */
55 template <typename E, typename Op, typename Config = default_config_t<Op>>
56 requires std::is_enum_v<E>
58 std::type_identity_t<std::function<std::shared_ptr<Op>(Config)>> factory = {}, int priority = 50)
59 {
60 return catalog_impl<E, Op, Config>(std::nullopt, std::move(factory), priority);
61 }
62
63 /** @brief Catalog an implementation for one selection within an enum vocabulary. */
64 template <typename Op, typename E, typename Config = default_config_t<Op>>
65 requires std::is_enum_v<E>
67 std::type_identity_t<std::function<std::shared_ptr<Op>(Config)>> factory = {}, int priority = 50)
68 {
69 return catalog_impl<E, Op, Config>(selection, std::move(factory), priority);
70 }
71
72 /**
73 * @brief Catalog an implementation for every config it supports.
74 *
75 * Each config of Op::supports is registered under the enum its selector field takes.
76 * Implementations built from their config are constructed by it.
77 */
78 template <typename Op>
79 requires requires { typename Op::supports; }
80 OperationRegistry& add(int priority = 50)
81 {
82 Op::supports::each([&]<typename Config>() {
83 using Selection = selection_t<Config>;
84 static_assert(!std::is_void_v<Selection>, "The config has no method, operation or algorithm selector");
85 catalog_impl<Selection, Op, Config>(std::nullopt, {}, priority);
86 });
87 return *this;
88 }
89
90 /** @brief Construct all registered implementations accepting this signature and config type. */
91 [[nodiscard]] std::vector<Binding> resolve(
92 const ComputationSignature& signature, const OperationConfig* config = nullptr) const
93 {
94 std::vector<Binding> bindings;
95 for (const auto& registration : m_registrations) {
96 if (auto binding = registration(signature, config)) {
97 bindings.push_back(std::move(*binding));
98 }
99 }
100 return bindings;
101 }
102
103private:
104 template <typename E, typename Op, typename Config>
105 OperationRegistry& catalog_impl(std::optional<E> only,
106 std::function<std::shared_ptr<Op>(Config)> factory, int priority)
107 {
108 m_registrations.push_back(
109 [only, factory = std::move(factory), priority](
110 const ComputationSignature& signature, const OperationConfig* supplied) -> std::optional<Binding> {
111 const auto selection = signature.template selection<E>(0);
112 if (signature.size() != 1 || !selection || (only && *only != *selection)) {
113 return std::nullopt;
114 }
115 Config config {};
116 if (supplied) {
117 if constexpr (std::same_as<Config, OperationConfig>) {
118 config = *supplied;
119 } else {
120 const auto* typed = supplied->template get<Config>();
121 if (!typed) {
122 return std::nullopt;
123 }
124 config = *typed;
125 }
126 }
127 if constexpr (requires { config.method = *selection; }
128 || requires { config.operation = *selection; }
129 || requires { config.algorithm = *selection; }) {
130 config = select_operation(*selection, std::move(config));
131 } else if (!only) {
132 error<std::invalid_argument>(Journal::Component::Yantra, Journal::Context::Runtime,
133 std::source_location::current(),
134 "Catalog a single enum selection for an implementation without a method selector");
135 }
136 std::shared_ptr<Op> operation;
137 if (factory) {
138 operation = factory(config);
139 } else if constexpr (std::constructible_from<Op, Config>) {
140 operation = std::make_shared<Op>(config);
141 } else if constexpr (std::default_initializable<Op>) {
142 operation = std::make_shared<Op>();
143 } else {
144 error<std::invalid_argument>(Journal::Component::Yantra, Journal::Context::Runtime,
145 std::source_location::current(), "Catalog a factory for this operation");
146 }
147 if (!operation) {
148 error<std::invalid_argument>(Journal::Component::Yantra, Journal::Context::Runtime,
149 std::source_location::current(), "Catalog factory returned no operation");
150 }
151 if constexpr (requires { operation->set_config(config); }) {
152 operation->set_config(config);
153 }
154 using Input = std::remove_cvref_t<decltype(std::declval<typename Op::input_type>().data)>;
155 using Output = std::remove_cvref_t<decltype(std::declval<typename Op::output_type>().data)>;
156 std::shared_ptr<ComputeOperation<Input, Output>> base = std::move(operation);
157 return Binding {
158 .type = std::type_index(typeid(Op)),
159 .matcher = [base](const std::any& input, const ExecutionContext&) {
160 const auto* typed = std::any_cast<typename Op::input_type>(&input);
161 return typed && base->validate_input(*typed);
162 },
163 .executor = [base](const std::any& input, const ExecutionContext& ctx) -> std::any {
164 apply_context_parameters(base, ctx);
165 base->set_last_execution_context(ctx);
166 return base->apply_operation(safe_any_cast_or_throw<typename Op::input_type>(input));
167 },
168 .priority = priority,
169 .target = target_of_v<Op>,
170 .fitness = fitness_of<Op>(),
171 .sticky = stateful_v<Op>,
172 };
173 });
174 return *this;
175 }
176
177 using Registration = std::function<std::optional<Binding>(const ComputationSignature&, const OperationConfig*)>;
178 std::vector<Registration> m_registrations;
179};
180
181/**
182 * @brief A registry holding the library's own operations, each in its standard instantiations.
183 *
184 * RegionKeySorter shares its selector with StandardSorter and the granular operations have
185 * none, so they are not listed. Add your own operations to the returned registry with add().
186 */
187[[nodiscard]] MAYAFLUX_API OperationRegistry make_default_registry();
188
189}
Ordered operation selections, preserving each enum's type and value.
std::function< bool(const std::any &, const ExecutionContext &)> MatcherFunc
OperationRegistry & catalog_impl(std::optional< E > only, std::function< std::shared_ptr< Op >(Config)> factory, int priority)
OperationRegistry & add(int priority=50)
Catalog an implementation for every config it supports.
std::vector< Registration > m_registrations
std::function< std::optional< Binding >(const ComputationSignature &, const OperationConfig *)> Registration
OperationRegistry & catalog(std::type_identity_t< std::function< std::shared_ptr< Op >(Config)> > factory={}, int priority=50)
Catalog an implementation for an enum vocabulary.
std::vector< Binding > resolve(const ComputationSignature &signature, const OperationConfig *config=nullptr) const
Construct all registered implementations accepting this signature and config type.
OperationRegistry & catalog(E selection, std::type_identity_t< std::function< std::shared_ptr< Op >(Config)> > factory={}, int priority=50)
Catalog an implementation for one selection within an enum vocabulary.
Explicitly owned registrations connecting enum vocabularies, configs, and implementations.
Globlal configuration for MayaFlux.
Definition Config.cpp:20
@ Runtime
General runtime operations (default fallback).
@ Yantra
DSP algorithms, computational units, matrix operations, Grammar.
void apply_context_parameters(std::shared_ptr< OperationType > operation, const ExecutionContext &ctx)
Applies context settings to an operation.
std::function< float(const std::any &)> Fitness
How well a candidate suits an input.
constexpr Target target_of_v
The target an operation class declares through static constexpr Target target, or the CPU when it dec...
constexpr bool stateful_v
Whether the class keeps state between calls and must stay on its candidate.
Fitness fitness_of()
The candidate's fitness for an erased input.
typename detail::UnwrapEnum< typename decltype(detail::selector_field< Config >())::type >::type selection_t
The enum a config selects its method from, or void when it has no selector.
OperationRegistry make_default_registry()
A registry holding the library's own operations, each in its standard instantiations.
Config select_operation(E selection, Config config)
Set the config's method selector from its corresponding operation enum.
Context information controlling how a compute operation executes.
Base of every operation's config struct.
std::function< std::any(const std::any &, const ExecutionContext &)> executor
A constructed implementation with its erased input and execution contracts.
A set of (device, runtime) pairs.