MayaFlux 0.3.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
Stochastic.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <random>
4
6
7/**
8 * @enum Algorithm
9 * @brief Stochastic and procedural generation algorithms
10 */
11enum class Algorithm : uint8_t {
12 UNIFORM,
13 NORMAL,
15 POISSON,
16 PERLIN,
17 GENDY,
19 PINK,
20 BLUE
21};
22
23/**
24 * @struct GeneratorState
25 * @brief Encapsulates internal state for stateful generators
26 *
27 * Stateful generators (Gendy, Brownian, Perlin) maintain internal state
28 * that evolves over successive calls. This structure provides unified
29 * state management across different algorithmic approaches.
30 *
31 * **Future Interaction Pathways:**
32 * - External ML inference can populate `internal_buffer` with predicted sequences
33 * - Analysis of audio/visual data can derive breakpoints for Gendy synthesis
34 * - Cross-domain mappings can modulate `velocity` or `phase` in real-time
35 * - Pattern recognition can inject structure into `algorithm_specific` state
36 *
37 * All fields are publicly accessible for maximum flexibility in live interaction.
38 */
40 double current_value { 0.0 };
41 double previous_value { 0.0 };
42 double velocity { 0.0 };
43 double phase { 0.0 };
44 uint64_t step_count { 0 };
45
46 std::vector<double> internal_buffer;
47 std::map<std::string, std::any> algorithm_specific;
48
49 void reset()
50 {
51 current_value = 0.0;
52 previous_value = 0.0;
53 velocity = 0.0;
54 phase = 0.0;
55 step_count = 0;
56 internal_buffer.clear();
57 algorithm_specific.clear();
58 }
59};
60
61/**
62 * @class Stochastic
63 * @brief Unified generative infrastructure for stochastic and procedural algorithms
64 *
65 * Provides mathematical primitives for controlled randomness and procedural generation
66 * across all computational domains. Unlike traditional random number generators focused
67 * on independent samples, Stochastic embraces both memoryless distributions and stateful
68 * processes that evolve over time.
69 *
70 * ## Architectural Philosophy
71 * Treats stochastic generation as fundamental mathematical infrastructure rather than
72 * domain-specific processing. The same primitives that generate sonic textures can
73 * drive visual phenomena, parametric modulation, or data synthesis - the numbers
74 * themselves are discipline-agnostic.
75 *
76 * ## Algorithm Categories
77 *
78 * **Memoryless Distributions** (each call independent):
79 * - UNIFORM: Flat probability across range
80 * - NORMAL: Gaussian distribution
81 * - EXPONENTIAL: Exponential decay
82 * - POISSON: Discrete event distribution
83 *
84 * **Stateful Processes** (evolution over successive calls):
85 * - PERLIN: Coherent gradient noise with spatial/temporal continuity
86 * - GENDY: Xenakis dynamic stochastic synthesis (pitch/amplitude breakpoints)
87 * - BROWNIAN: Random walk (integrated white noise)
88 * - PINK: 1/f noise (equal energy per octave)
89 * - BLUE: Rising spectral energy
90 *
91 * ## Usage Patterns
92 *
93 * Memoryless generation:
94 * ```cpp
95 * Stochastic gen(Algorithm::NORMAL);
96 * double value = gen(0.0, 1.0);
97 * ```
98 *
99 * Stateful evolution:
100 * ```cpp
101 * Stochastic walker(Algorithm::BROWNIAN);
102 * walker.configure("step_size", 0.01);
103 * for (int i = 0; i < 1000; ++i) {
104 * double pos = walker(0.0, 1.0);
105 * }
106 * ```
107 *
108 * Multi-dimensional generation:
109 * ```cpp
110 * Stochastic perlin(Algorithm::PERLIN);
111 * double noise_2d = perlin.at(x, y);
112 * double noise_3d = perlin.at(x, y, z);
113 * ```
114 *
115 * @note Thread-unsafe for maximum performance. Use separate instances per thread.
116 */
117class MAYAFLUX_API Stochastic {
118public:
119 /**
120 * @brief Constructs generator with specified algorithm
121 * @param algo Algorithm for generation (default: UNIFORM)
122 */
123 explicit Stochastic(Algorithm algo = Algorithm::UNIFORM);
124
125 /**
126 * @brief Seeds entropy source
127 * @param seed Seed value for deterministic sequences
128 */
129 void seed(uint64_t seed);
130
131 /**
132 * @brief Changes active algorithm
133 * @param algo New generation algorithm
134 *
135 * Resets internal state when switching algorithms.
136 */
137 void set_algorithm(Algorithm algo);
138
139 /**
140 * @brief Gets current algorithm
141 * @return Active algorithm
142 */
143 [[nodiscard]] inline Algorithm get_algorithm() const { return m_algorithm; }
144
145 /**
146 * @brief Configures algorithm-specific parameters
147 * @param key Parameter name
148 * @param value Parameter value
149 *
150 * Standard parameters (algorithm-dependent):
151 * - NORMAL: "spread" (double) - std deviation divisor
152 * - PERLIN: "octaves" (int), "persistence" (double), "frequency" (double)
153 * - GENDY: "breakpoints" (int), "amplitude_dist" (Algorithm), "duration_dist" (Algorithm)
154 * - BROWNIAN: "step_size" (double), "bounds_mode" (string)
155 * - PINK/BLUE: "pole_count" (int)
156 *
157 * Interactive/Live parameters (future-ready):
158 * - GENDY: "breakpoint_amplitudes" (std::vector<double>) - inject external breakpoints
159 * - GENDY: "breakpoint_durations" (std::vector<double>) - inject temporal structure
160 * - PERLIN: "permutation_table" (std::vector<int>) - custom noise characteristics
161 * - ANY: "modulation_source" (std::function<double()>) - external control signal
162 * - ANY: "inference_callback" (std::function<void(GeneratorState&)>) - ML-driven state
163 *
164 * Dynamic reconfiguration is fully supported - call anytime to alter behavior.
165 */
166 void configure(const std::string& key, std::any value);
167
168 /**
169 * @brief Gets configuration parameter
170 * @param key Parameter name
171 * @return Parameter value or std::nullopt
172 */
173 [[nodiscard]] std::optional<std::any> get_config(const std::string& key) const;
174
175 /**
176 * @brief Generates single value in range
177 * @param min Lower bound
178 * @param max Upper bound
179 * @return Generated value
180 *
181 * For stateful algorithms, successive calls evolve internal state.
182 */
183 [[nodiscard]] double operator()(double min, double max);
184
185 /**
186 * @brief Multi-dimensional generation (Perlin, spatial noise)
187 * @param x Primary coordinate
188 * @param y Secondary coordinate (optional)
189 * @param z Tertiary coordinate (optional)
190 * @return Noise value at coordinates
191 */
192 [[nodiscard]] double at(double x, double y = 0.0, double z = 0.0);
193
194 /**
195 * @brief Batch generation
196 * @param min Lower bound
197 * @param max Upper bound
198 * @param count Number of values
199 * @return Vector of generated values
200 */
201 [[nodiscard]] std::vector<double> batch(double min, double max, size_t count);
202
203 /**
204 * @brief Resets internal state for stateful algorithms
205 *
206 * Memoryless distributions unaffected. Stateful processes return to initial state.
207 */
208 void reset_state();
209
210 /**
211 * @brief Gets current internal state
212 * @return Read-only reference to generator state
213 *
214 * Exposes complete internal state for:
215 * - Analysis and visualization of stochastic evolution
216 * - Debugging algorithmic behavior
217 * - Extracting learned patterns from stateful processes
218 * - Cross-domain mapping of generative trajectories
219 */
220 [[nodiscard]] const GeneratorState& state() const { return m_state; }
221
222 /**
223 * @brief Gets mutable internal state
224 * @return Mutable reference to generator state
225 *
226 * Enables direct manipulation of internal state for:
227 * - Injecting externally computed breakpoints (Gendy)
228 * - Seeding noise fields with analyzed data (Perlin)
229 * - Nudging random walks toward attractors (Brownian)
230 * - Implementing hybrid human/algorithmic control
231 *
232 * **Example: Inject ML-inferred Gendy breakpoints**
233 * ```cpp
234 * auto& state = gen.state_mutable();
235 * state.algorithm_specific["breakpoint_amplitudes"] = ml_predicted_amps;
236 * state.algorithm_specific["breakpoint_durations"] = ml_predicted_durs;
237 * ```
238 */
239 [[nodiscard]] GeneratorState& state_mutable() { return m_state; }
240
241 // ========================================================================
242 // FUTURE INTERACTION INTERFACES (Placeholders for Dynamic Control)
243 // ========================================================================
244 // These demonstrate intended interaction patterns without implementing them yet.
245 // Uncomment and implement as features are needed.
246
247 // /**
248 // * @brief Inject external breakpoints for Gendy synthesis
249 // * @param amplitudes Amplitude control points
250 // * @param durations Duration control points
251 // *
252 // * Enables ML inference, analysis-driven, or hand-crafted breakpoint injection:
253 // * - Analyze audio spectral contour → derive amplitude breakpoints
254 // * - Train ML model on corpus → predict generative trajectories
255 // * - Map visual motion tracking → temporal breakpoint structure
256 // */
257 // void inject_gendy_breakpoints(const std::vector<double>& amplitudes,
258 // const std::vector<double>& durations);
259
260 // /**
261 // * @brief Set external modulation source for any parameter
262 // * @param target_param Parameter to modulate ("phase", "velocity", etc.)
263 // * @param modulator Function returning control value each call
264 // *
265 // * Connects arbitrary external signals to internal generator state:
266 // * ```cpp
267 // * gen.set_modulation("phase", []() { return audio_analysis.get_centroid(); });
268 // * ```
269 // */
270 // void set_modulation(const std::string& target_param,
271 // std::function<double()> modulator);
272
273 // /**
274 // * @brief Register callback for state analysis/visualization
275 // * @param callback Function receiving state snapshot each generation
276 // *
277 // * Enables real-time monitoring and adaptive control:
278 // * ```cpp
279 // * gen.on_generate([](const GeneratorState& s) {
280 // * visualizer.plot_trajectory(s.current_value, s.velocity);
281 // * });
282 // * ```
283 // */
284 // void on_generate(std::function<void(const GeneratorState&)> callback);
285
286 // /**
287 // * @brief Seed Perlin noise with custom permutation table
288 // * @param permutation Custom permutation for noise field
289 // *
290 // * Inject analyzed or designed noise characteristics:
291 // * - Extract permutation from natural textures
292 // * - Design specific correlation properties
293 // * - Create deterministic but complex fields
294 // */
295 // void set_perlin_permutation(const std::vector<int>& permutation);
296
297 // /**
298 // * @brief Inject attractor for Brownian motion
299 // * @param attractor_value Target value to drift toward
300 // * @param strength Pull strength (0.0 = no effect, 1.0 = strong)
301 // *
302 // * Creates biased random walks:
303 // * ```cpp
304 // * walker.set_attractor(0.5, 0.1); // Gentle drift toward center
305 // * ```
306 // */
307 // void set_attractor(double attractor_value, double strength);
308
309private:
310 [[nodiscard]] double generate_memoryless(double min, double max);
311 [[nodiscard]] double generate_stateful(double min, double max);
312 [[nodiscard]] double generate_perlin_impl(double x, double y, double z);
313 [[nodiscard]] double generate_gendy_impl(double min, double max);
314 [[nodiscard]] double generate_brownian_impl(double min, double max);
315 [[nodiscard]] double generate_colored_noise_impl(double min, double max);
316
317 void validate_range(double min, double max) const;
318 void rebuild_distributions_if_needed(double min, double max);
319
320 [[nodiscard]] inline double fast_uniform() noexcept
321 {
322 m_xorshift_state ^= m_xorshift_state >> 12;
323 m_xorshift_state ^= m_xorshift_state << 25;
324 m_xorshift_state ^= m_xorshift_state >> 27;
325 return static_cast<double>(m_xorshift_state * 0x2545F4914F6CDD1DULL)
326 * (1.0 / 18446744073709551616.0);
327 }
328
329 std::mt19937 m_engine;
332
334 std::map<std::string, std::any> m_config;
335
336 std::normal_distribution<double> m_normal_dist { 0.0, 1.0 };
337 std::exponential_distribution<double> m_exponential_dist { 1.0 };
338
339 double m_cached_min { 0.0 };
340 double m_cached_max { 1.0 };
341 bool m_dist_dirty { true };
342};
343
344/**
345 * @brief Creates uniform random generator
346 * @return Configured Stochastic instance
347 */
349
350/**
351 * @brief Creates Gaussian random generator
352 * @param spread Standard deviation divisor (default: 4.0 for ~95% in range)
353 * @return Configured Stochastic instance
354 */
355inline Stochastic gaussian(double spread = 4.0)
356{
358 gen.configure("spread", spread);
359 return gen;
360}
361
362/**
363 * @brief Creates Perlin noise generator
364 * @param octaves Number of noise octaves (default: 4)
365 * @param persistence Amplitude decay per octave (default: 0.5)
366 * @return Configured Stochastic instance
367 */
368inline Stochastic perlin(int octaves = 4, double persistence = 0.5)
369{
371 gen.configure("octaves", octaves);
372 gen.configure("persistence", persistence);
373 return gen;
374}
375
376/**
377 * @brief Creates Gendy dynamic stochastic generator
378 * @param breakpoints Number of control points (default: 12)
379 * @return Configured Stochastic instance
380 */
381inline Stochastic gendy(int breakpoints = 12)
382{
384 gen.configure("breakpoints", breakpoints);
385 return gen;
386}
387
388/**
389 * @brief Creates Brownian motion generator
390 * @param step_size Maximum step per call (default: 0.01)
391 * @return Configured Stochastic instance
392 */
393inline Stochastic brownian(double step_size = 0.01)
394{
396 gen.configure("step_size", step_size);
397 return gen;
398}
399
400}
Eigen::Index count
std::map< std::string, std::any > m_config
GeneratorState & state_mutable()
Gets mutable internal state.
void configure(const std::string &key, std::any value)
Configures algorithm-specific parameters.
Algorithm get_algorithm() const
Gets current algorithm.
const GeneratorState & state() const
Gets current internal state.
Unified generative infrastructure for stochastic and procedural algorithms.
Stochastic gendy(int breakpoints=12)
Creates Gendy dynamic stochastic generator.
Stochastic perlin(int octaves=4, double persistence=0.5)
Creates Perlin noise generator.
Stochastic brownian(double step_size=0.01)
Creates Brownian motion generator.
Stochastic uniform()
Creates uniform random generator.
Stochastic gaussian(double spread=4.0)
Creates Gaussian random generator.
Algorithm
Stochastic and procedural generation algorithms.
std::map< std::string, std::any > algorithm_specific
Encapsulates internal state for stateful generators.