MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
MathematicalTransformer.hpp
Go to the documentation of this file.
1#pragma once
2
6
7namespace MayaFlux::Yantra {
8
10/**
11 * @enum MathematicalOperation
12 * @brief Specific mathematical operations supported
13 */
14enum class MathematicalOperation : uint8_t {
15 GAIN, ///< Linear gain/attenuation
16 OFFSET, ///< DC offset
17 POWER, ///< Power function
18 LOGARITHMIC, ///< Logarithmic transform
19 EXPONENTIAL, ///< Exponential transform
20 TRIGONOMETRIC, ///< Trigonometric functions
21 QUANTIZE, ///< Quantization/bit reduction
22 NORMALIZE, ///< Normalization
23 POLYNOMIAL ///< Polynomial transform
24};
25
26/** @brief Construction settings for MathematicalTransformer. */
28
29/**
30 * @class MathematicalTransformer
31 * @brief Concrete transformer for mathematical operations
32 *
33 * Handles pure mathematical transformations:
34 * - Arithmetic operations (gain, offset, scaling)
35 * - Trigonometric functions
36 * - Logarithmic and exponential transforms
37 * - Polynomial and power functions
38 * - Quantization and bit reduction
39 */
40template <ComputeData InputType = std::vector<Kakshya::DataVariant>, ComputeData OutputType = InputType>
41class MathematicalTransformer final : public UniversalTransformer<InputType, OutputType> {
42public:
45
46 /**
47 * @brief Constructs a MathematicalTransformer with specified operation
48 * @param op The mathematical operation to perform (default: GAIN)
49 */
55
56 /**
57 * @brief Construct and configure a mathematical transformer in one step.
58 * @param config Initial transformation settings.
59 */
61 : MathematicalTransformer(config.operation)
62 {
63 this->set_strategy(config.strategy);
64 this->set_quality(config.quality);
65 this->set_scope(config.scope);
66 this->set_intensity(config.intensity);
67
68 for (const auto& key : config.keys) {
69 this->add_transformation_key(key);
70 }
71
72 for (const auto& [name, value] : config.parameters) {
73 this->set_parameter(name, value);
74 }
75 }
76
77 /**
78 * @brief Gets the transformation type
79 * @return TransformationType::MATHEMATICAL
80 */
81 [[nodiscard]] TransformationType get_transformation_type() const override
82 {
84 }
85
86 /**
87 * @brief Gets the transformer name including the operation type
88 * @return String representation of the transformer name
89 */
90 [[nodiscard]] std::string get_transformer_name() const override
91 {
92 return std::string("MathematicalTransformer_").append(Reflect::enum_to_string(m_operation));
93 }
94
95protected:
96 /**
97 * @brief Core transformation implementation
98 * @param input Input data to transform
99 * @return Transformed output data
100 *
101 * Performs the mathematical operation specified by m_operation on the input data.
102 * Supports both in-place and out-of-place transformations based on transformer settings.
103 */
105 {
106 switch (m_operation) {
107
109 const auto a = get_parameter_or<double>("gain_factor", 1.0);
110 return apply_per_channel(input, [a](std::span<double> ch) {
111 D::linear(ch, a, 0.0);
112 });
113 }
114
116 const auto b = get_parameter_or<double>("offset_value", 0.0);
117 return apply_per_channel(input, [b](std::span<double> ch) {
118 D::linear(ch, 1.0, b);
119 });
120 }
121
123 const auto exp = get_parameter_or<double>("exponent", 2.0);
124 return apply_per_channel(input, [exp](std::span<double> ch) {
125 D::power(ch, exp);
126 });
127 }
128
130 const auto a = get_parameter_or<double>("scale", 1.0);
131 const auto b = get_parameter_or<double>("input_scale", 1.0);
132 const auto c = get_parameter_or<double>("offset", 1.0);
133 const auto base = get_parameter_or<double>("base", std::numbers::e);
134 return apply_per_channel(input, [a, b, c, base](std::span<double> ch) {
135 D::logarithmic(ch, a, b, c, base);
136 });
137 }
138
140 const auto a = get_parameter_or<double>("scale", 1.0);
141 const auto b = get_parameter_or<double>("rate", 1.0);
142 const auto base = get_parameter_or<double>("base", std::numbers::e);
143 return apply_per_channel(input, [a, b, base](std::span<double> ch) {
144 D::exponential(ch, a, b, base);
145 });
146 }
147
149 const auto fn = get_parameter_or<std::string>("trig_function", "sin");
150 const auto freq = get_parameter_or<double>("frequency", 1.0);
151 const auto amp = get_parameter_or<double>("amplitude", 1.0);
152 const auto ph = get_parameter_or<double>("phase", 0.0);
153 if (fn == "cos")
154 return apply_per_channel(input, [freq, amp, ph](std::span<double> ch) {
155 D::apply_trig(ch, [](double x) { return std::cos(x); }, freq, amp, ph);
156 });
157 if (fn == "tan")
158 return apply_per_channel(input, [freq, amp, ph](std::span<double> ch) {
159 D::apply_trig(ch, [](double x) { return std::tan(x); }, freq, amp, ph);
160 });
161 return apply_per_channel(input, [freq, amp, ph](std::span<double> ch) {
162 D::apply_trig(ch, [](double x) { return std::sin(x); }, freq, amp, ph);
163 });
164 }
165
167 const auto bits = get_parameter_or<uint8_t>("bits", 16);
168 return apply_per_channel(input, [bits](std::span<double> ch) {
169 D::quantize(ch, bits);
170 });
171 }
172
174 const auto peak = get_parameter_or<double>("target_peak", 1.0);
175 return apply_per_channel(input, [peak](std::span<double> ch) {
176 D::normalize(ch, -peak, peak);
177 });
178 }
179
181 const auto coeffs = get_parameter_or<std::vector<double>>(
182 "coefficients", std::vector<double> { 0.0, 1.0 });
183 auto poly = std::make_shared<Nodes::Generator::Polynomial>(coeffs);
184 return apply_per_channel(input, [&poly](std::span<double> ch) {
185 std::ranges::transform(ch, ch.begin(),
186 [&poly](double x) { return poly->process_sample(x); });
187 });
188 }
189
190 default:
191 return create_output(input);
192 }
193 }
194
195 /**
196 * @brief Sets transformation parameters
197 * @param name Parameter name
198 * @param value Parameter value
199 *
200 * Handles setting of operation type and delegates other parameters to base class.
201 * Supports both enum and string values for the "operation" parameter.
202 */
203 void set_transformation_parameter(const std::string& name, std::any value) override
204 {
205 if (name == "operation") {
206 if (auto r = safe_any_cast<MathematicalOperation>(value)) {
207 m_operation = *r.value;
208 return;
209 }
210 if (auto r = safe_any_cast<std::string>(value)) {
211 if (auto e = Reflect::string_to_enum_case_insensitive<MathematicalOperation>(*r.value)) {
212 m_operation = *e;
213 return;
214 }
215 }
216 }
217
219 }
220
221private:
222 MathematicalOperation m_operation; ///< Current mathematical operation
223 mutable std::vector<std::vector<double>> m_working_buffer; ///< Buffer for out-of-place operations
224
225 /**
226 * @brief Extracts per-channel spans, applies an in-place func to each, and reconstructs.
227 * @tparam Func Callable matching void(std::span<double>)
228 *
229 * In-place: results are copied back into the original channel spans of @p input before
230 * reconstruction. Out-of-place: input is not mutated.
231 */
232 template <typename Func>
234 {
236 m_working_buffer.resize(channels.size());
237 for (size_t i = 0; i < channels.size(); ++i) {
238 m_working_buffer[i].assign(channels[i].begin(), channels[i].end());
239 func(std::span<double> { m_working_buffer[i] });
240 }
241 if (this->is_in_place())
242 for (size_t i = 0; i < channels.size(); ++i)
243 std::ranges::copy(m_working_buffer[i], channels[i].begin());
244 return create_output(
245 OperationHelper::reconstruct_from_double<InputType>(m_working_buffer, structure_info));
246 }
247
248 /**
249 * @brief Sets default parameter values for all mathematical operations
250 *
251 * Initializes all possible parameters with sensible defaults to ensure
252 * the transformer works correctly regardless of the selected operation.
253 */
255 {
256 this->set_parameter("gain_factor", 1.0);
257 this->set_parameter("offset_value", 0.0);
258 this->set_parameter("exponent", 2.0);
259 this->set_parameter("base", std::numbers::e);
260 this->set_parameter("scale", 1.0);
261 this->set_parameter("trig_function", std::string { "sin" });
262 this->set_parameter("frequency", 1.0);
263 this->set_parameter("amplitude", 1.0);
264 this->set_parameter("phase", 0.0);
265 this->set_parameter("bits", uint8_t { 16 });
266 this->set_parameter("target_peak", 1.0);
267 this->set_parameter("coefficients", std::vector<double> { 0.0, 1.0 });
268 this->set_parameter("input_scale", 1.0);
269 this->set_parameter("offset", 1.0);
270 this->set_parameter("rate", 1.0);
271 }
272
273 /**
274 * @brief Gets a parameter value with fallback to default
275 * @tparam T Parameter type
276 * @param name Parameter name
277 * @param default_value Default value if parameter not found or wrong type
278 * @return Parameter value or default
279 */
280 template <typename T>
281 T get_parameter_or(const std::string& name, const T& default_value) const
282 {
283 auto param = this->get_transformation_parameter(name);
284 if (!param.has_value())
285 return default_value;
286
287 auto result = safe_any_cast<T>(param);
288 return result.value_or(default_value);
289 }
290
291 /**
292 * @brief Creates output with proper type conversion
293 * @param data Input data to convert
294 * @return Output with converted data type
295 *
296 * Handles type conversion between InputType and OutputType when necessary,
297 * or direct assignment when types match.
298 */
300 {
301 if constexpr (std::is_same_v<InputType, OutputType>) {
302 return input;
303 } else {
305 return this->convert_result(result_data, metadata);
306 }
307 }
308};
309}
Core::GlobalInputConfig input
Definition Config.cpp:42
size_t a
size_t b
std::unordered_map< std::string, std::string > metadata
Discrete sequence transformation primitives for MayaFlux::Kinesis.
Float Processing Guidelines.
glm::vec3 value
std::string name
Definition VKDevice.cpp:123
uint32_t channels
uint32_t ph
output_type convert_result(std::vector< std::vector< double > > &result_data, DataStructureInfo &metadata)
Convert processed double data back to OutputType using metadata and optional callback.
output_type create_output(const input_type &input)
Creates output with proper type conversion.
MathematicalTransformer(MathematicalOperation op=MathematicalOperation::GAIN)
Constructs a MathematicalTransformer with specified operation.
std::string get_transformer_name() const override
Gets the transformer name including the operation type.
TransformationType get_transformation_type() const override
Gets the transformation type.
void set_default_parameters()
Sets default parameter values for all mathematical operations.
void set_transformation_parameter(const std::string &name, std::any value) override
Sets transformation parameters.
T get_parameter_or(const std::string &name, const T &default_value) const
Gets a parameter value with fallback to default.
output_type transform_implementation(input_type &input) override
Core transformation implementation.
MathematicalTransformer(const MathematicalTransformerConfig &config)
Construct and configure a mathematical transformer in one step.
MathematicalOperation m_operation
Current mathematical operation.
std::vector< std::vector< double > > m_working_buffer
Buffer for out-of-place operations.
output_type apply_per_channel(input_type &input, Func &&func)
Extracts per-channel spans, applies an in-place func to each, and reconstructs.
Concrete transformer for mathematical operations.
static std::tuple< std::vector< std::span< double > >, DataStructureInfo > extract_structured_double(T &compute_data)
Extract structured double data from Datum container or direct ComputeData with automatic container ha...
void set_strategy(TransformationStrategy strategy)
Sets the transformation strategy.
void set_intensity(double intensity)
Set transformation intensity (0.0 = no transformation, 1.0 = full transformation)
void set_scope(TransformationScope scope)
Sets the transformation scope.
virtual bool is_in_place() const
Indicates whether the transformation modifies the input data directly.
virtual std::any get_transformation_parameter(const std::string &name) const
Gets a transformation-specific parameter value.
void set_parameter(const std::string &name, std::any value) override
Type-safe parameter management with transformation-specific defaults.
void set_quality(TransformationQuality quality)
Sets the transformation quality level.
void add_transformation_key(const TransformationKey &key)
Add transformation key for multi-dimensional transformations.
virtual void set_transformation_parameter(const std::string &name, std::any value)
Transformation-specific parameter handling (override for custom parameters)
Template-flexible transformer base with instance-defined I/O types.
void logarithmic(std::span< double > data, double a, double b, double c, double base) noexcept
Logarithmic map y = a * log_base(b*x + c) applied in-place Values where (b*x + c) <= 0 are mapped to ...
Definition Transform.cpp:34
void exponential(std::span< double > data, double a, double b, double base) noexcept
Exponential map y = a * base^(b*x) applied in-place Scalar transcendental — not SIMD hot-path.
Definition Transform.cpp:23
void quantize(std::span< double > data, uint8_t bits) noexcept
Quantize to n-bit resolution in-place Input is assumed to be in [-1, 1]; values outside are clamped f...
Definition Transform.cpp:50
std::vector< double > power(std::span< const double > data, size_t n_windows, uint32_t hop_size, uint32_t window_size)
Power (sum of squares) per window.
Definition Analysis.cpp:70
void normalize(std::span< double > data, double target_min, double target_max) noexcept
Normalize to [target_min, target_max] in-place Single-pass min/max reduction followed by a single tra...
Definition Transform.cpp:61
void linear(std::span< double > data, double a, double b) noexcept
Linear map y = a*x + b applied in-place.
Definition Transform.cpp:11
void apply_trig(std::span< double > data, TrigFunc func, double frequency, double amplitude, double phase) noexcept
Trigonometric map y = amplitude * f(frequency*x + phase) applied in-place.
Definition Transform.hpp:81
constexpr std::string_view enum_to_string(EnumType value) noexcept
Universal enum to string converter using magic_enum (original case)
@ POWER
Power (sum of squares)
MathematicalOperation
Specific mathematical operations supported.
@ GAIN
Linear gain/attenuation.
@ QUANTIZE
Quantization/bit reduction.
@ TRIGONOMETRIC
Trigonometric functions.
@ LOGARITHMIC
Logarithmic transform.
@ EXPONENTIAL
Exponential transform.
TransformationType
Categories of transformation operations for discovery and organization.
@ MATHEMATICAL
Mathematical transformations (polynomial mapping, matrix operations)
Input/Output container for computation pipeline data flow with structure preservation.
Definition DataIO.hpp:26
TransformationQuality quality
Requested transformation quality.
TransformationScope scope
Portion of the input to transform.
TransformationStrategy strategy
How transformation work is performed.
std::vector< TransformationKey > keys
Transformation keys to register before processing.
std::map< std::string, std::any > parameters
Additional named parameters applied last.
double intensity
Overall transformation strength.
Initial settings shared by concrete transformer families.