MayaFlux 0.2.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
Stochastic.hpp
Go to the documentation of this file.
1#pragma once
2#include "Generator.hpp"
3
4#include <random>
5
7
8/**
9 * @class StochasticContext
10 * @brief Specialized context for stochastic generator callbacks
11 *
12 * StochasticContext extends the base NodeContext to provide detailed information
13 * about a stochastic generator's current state to callbacks. It includes the
14 * current distribution type, amplitude scaling, range parameters, and statistical
15 * configuration values.
16 *
17 * This rich context enables callbacks to perform sophisticated analysis and
18 * monitoring of stochastic behavior, such as:
19 * - Tracking statistical properties of generated sequences
20 * - Implementing adaptive responses to emergent patterns
21 * - Visualizing probability distributions in real-time
22 * - Creating cross-domain mappings based on stochastic properties
23 * - Detecting and responding to specific statistical conditions
24 */
25class MAYAFLUX_API StochasticContext : public NodeContext {
26public:
27 /**
28 * @brief Constructs a StochasticContext with the current generator state
29 * @param value Current output sample value
30 * @param type Current probability distribution algorithm
31 * @param amplitude Current scaling factor for output values
32 * @param range_start Lower bound of the current output range
33 * @param range_end Upper bound of the current output range
34 * @param normal_spread Variance parameter for normal distribution
35 *
36 * Creates a context object that provides a complete snapshot of the
37 * stochastic generator's current state, including its most recent output
38 * value and all parameters that define its statistical behavior.
39 */
40 StochasticContext(double value, Utils::distribution type, double amplitude,
41 double range_start, double range_end, double normal_spread)
42 : NodeContext(value, typeid(StochasticContext).name())
43 , distribution_type(type)
44 , amplitude(amplitude)
45 , range_start(range_start)
46 , range_end(range_end)
47 , normal_spread(normal_spread)
48 {
49 }
50
51 /**
52 * @brief Current distribution type
53 *
54 * Identifies which probability algorithm is currently active in the
55 * generator (uniform, normal, exponential, etc.). This determines the
56 * fundamental statistical properties of the generated sequence.
57 */
59
60 /**
61 * @brief Current amplitude scaling factor
62 */
63 double amplitude;
64
65 /**
66 * @brief Current lower bound of the range
67 */
69
70 /**
71 * @brief Current upper bound of the range
72 */
73 double range_end;
74
75 /**
76 * @brief Current variance parameter for normal distribution
77 */
79};
80
81/**
82 * @class StochasticContextGpu
83 */
84class MAYAFLUX_API StochasticContextGpu : public StochasticContext, public GpuVectorData {
85public:
87 double value,
89 double amplitude,
90 double range_start,
91 double range_end,
92 double normal_spread,
93 std::span<const float> gpu_data)
94 : StochasticContext(value, type, amplitude, range_start, range_end, normal_spread)
95 , GpuVectorData(gpu_data)
96 {
97 type_id = typeid(StochasticContextGpu).name();
98 }
99};
100
101/**
102 * @class Random
103 * @brief Computational stochastic signal generator with multiple probability distributions
104 *
105 * The Random generates algorithmic signals based on mathematical probability
106 * distributions, serving as a foundational component for generative composition,
107 * procedural sound design, and data-driven audio transformation. Unlike deterministic
108 * processes, stochastic generators introduce controlled mathematical randomness
109 * into computational signal paths.
110 *
111 * Stochastic processes are fundamental in computational audio for:
112 * - Procedural generation of complex timbral structures
113 * - Algorithmic composition and generative music systems
114 * - Data-driven environmental simulations
115 * - Creating emergent sonic behaviors through probability fields
116 * - Cross-domain control signal generation (audio influencing visual, haptic, etc.)
117 *
118 * This implementation supports multiple probability distributions:
119 * - Uniform: Equal probability across the entire range
120 * - Normal (Gaussian): Bell-shaped distribution centered around the midpoint
121 * - Exponential: Higher probability near the start, decreasing exponentially
122 *
123 * The Random can function at any rate - from audio-rate signal generation to
124 * control-rate parameter modulation, to event-level algorithmic decision making.
125 * It can be integrated with other computational domains (graphics, physics, data)
126 * to create cross-domain generative systems.
127 */
128class MAYAFLUX_API Random : public Generator {
129public:
130 /**
131 * @brief Constructor for the stochastic generator
132 * @param type Distribution type to use (default: uniform distribution)
133 *
134 * Creates a stochastic generator with the specified probability distribution.
135 * The generator is initialized with entropy from the system's
136 * random device for non-deterministic behavior across program executions.
137 */
138 Random(Utils::distribution type = Utils::distribution::UNIFORM);
139
140 /**
141 * @brief Virtual destructor
142 */
143 ~Random() override = default;
144
145 /**
146 * @brief Changes the probability distribution type
147 * @param type New distribution type to use
148 *
149 * This allows dynamic reconfiguration of the stochastic behavior,
150 * enabling real-time transformation of the generator's mathematical properties.
151 */
153 {
154 m_type = type;
155 }
156
157 /**
158 * @brief Generates a single stochastic value
159 * @param input Input value (can be used for distribution modulation)
160 * @return Generated stochastic value
161 *
162 * This method generates a single value according to the current
163 * distribution settings. The input parameter can be used to modulate
164 * or influence the distribution in advanced applications.
165 */
166 double process_sample(double input = 0.) override;
167
168 /**
169 * @brief Generates a stochastic value within a specified range
170 * @param start Lower bound of the range
171 * @param end Upper bound of the range
172 * @return Value within the specified range based on current distribution
173 *
174 * This method provides precise control over the output range while
175 * maintaining the statistical properties of the selected distribution.
176 */
177 double random_sample(double start, double end);
178
179 /**
180 * @brief Generates multiple stochastic values at once
181 * @param num_samples Number of values to generate
182 * @return Vector of generated values
183 *
184 * This method efficiently generates multiple values in a single operation,
185 * useful for batch processing or filling buffers.
186 */
187 std::vector<double> process_batch(unsigned int num_samples) override;
188
189 /**
190 * @brief Generates an array of stochastic values within a specified range
191 * @param start Lower bound of the range
192 * @param end Upper bound of the range
193 * @param num_samples Number of values to generate
194 * @return Vector of values within the specified range
195 *
196 * Generates a collection of values following the current distribution,
197 * mapped to the specified numerical range.
198 */
199 std::vector<double> random_array(double start, double end, unsigned int num_samples);
200
201 /**
202 * @brief Visualizes the distribution characteristics
203 *
204 * Outputs a data visualization of the distribution's statistical properties,
205 * useful for understanding the mathematical behavior of the generator.
206 */
207 void printGraph() override;
208
209 /**
210 * @brief Outputs the current configuration parameters
211 *
212 * Displays the current distribution type, scaling factor, and other
213 * mathematical parameters of the generator.
214 */
215 void printCurrent() override;
216
217 /**
218 * @brief Sets the variance parameter for normal distribution
219 * @param spread New variance value
220 *
221 * For normal (Gaussian) distribution, this controls the statistical
222 * variance of the distribution. Higher values create greater entropy
223 * with more values in the extremes, while lower values concentrate
224 * values toward the center of the distribution.
225 */
226 void set_normal_spread(double spread);
227
228 void save_state() override { }
229 void restore_state() override { }
230
231protected:
232 /**
233 * @brief Updates the context object with the current node state
234 * @param value The current sample value
235 *
236 * This method is responsible for updating the NodeContext object
237 * with the latest state information from the node. It is called
238 * internally whenever a new output value is produced, ensuring that
239 * the context reflects the current state of the node for use in callbacks.
240 */
241 void update_context(double value) override;
242
243 /**
244 * @brief Notifies all registered callbacks about a new value
245 * @param value The newly generated value
246 *
247 * This method is called internally whenever a new value is generated,
248 * creating the appropriate context and invoking all registered callbacks
249 * that should receive notification about this value.
250 */
251 void notify_tick(double value) override;
252
253 NodeContext& get_last_context() override;
254
255private:
256 /**
257 * @brief Generates a raw value according to the current distribution
258 * @return Raw stochastic value before range transformation
259 *
260 * This internal method applies the selected probability algorithm
261 * to generate a value with the appropriate statistical properties.
262 */
263 double generate_distributed_sample();
264
265 /**
266 * @brief Transforms a raw value to fit within the specified range
267 * @param sample Raw value from the distribution
268 * @param start Lower bound of the target range
269 * @param end Upper bound of the target range
270 * @return Transformed value within the specified range
271 *
272 * Different distributions require different mathematical transformations
273 * to properly map their output while preserving their statistical properties.
274 */
275 [[nodiscard]] double transform_sample(double sample, double start, double end) const;
276
277 /**
278 * @brief Validates that the specified range is mathematically valid
279 * @param start Lower bound of the range
280 * @param end Upper bound of the range
281 * @throws std::invalid_argument if the range is invalid
282 *
283 * Ensures that the range parameters satisfy the mathematical constraints
284 * of the selected distribution algorithm.
285 */
286 void validate_range(double start, double end) const;
287
288 /**
289 * @brief Fast uniform random number generator using xorshift algorithm
290 * @return Pseudo-random double in the range [0.0, 1.0)
291 *
292 * This method implements a simple and efficient xorshift algorithm
293 * to produce uniform random numbers quickly, suitable for high-performance
294 * applications where speed is critical.
295 */
296 [[nodiscard]] inline double fast_uniform() noexcept
297 {
298 m_xorshift_state ^= m_xorshift_state >> 12;
299 m_xorshift_state ^= m_xorshift_state << 25;
300 m_xorshift_state ^= m_xorshift_state >> 27;
301 return static_cast<double>(m_xorshift_state * 0x2545F4914F6CDD1DULL)
302 * (1.0 / 18446744073709551616.0);
303 }
304
305 /**
306 * @brief Rebuilds distribution objects if parameters have changed
307 *
308 * This method checks if any distribution parameters have been modified
309 * since the last generation and rebuilds the internal distribution
310 * objects accordingly to ensure accurate statistical behavior.
311 */
312 void rebuild_distributions_if_needed() noexcept;
313
314 /**
315 * @brief Mersenne Twister entropy generator
316 *
317 * A high-quality pseudo-random number algorithm that provides
318 * excellent statistical properties for computational applications.
319 */
320 std::mt19937 m_random_engine;
321
322 /**
323 * @brief Current probability distribution algorithm
324 */
325 Utils::distribution m_type;
326
327 /**
328 * @brief Lower bound of the current output range
329 */
330 double m_current_start;
331
332 /**
333 * @brief Upper bound of the current output range
334 */
335 double m_current_end;
336
337 /**
338 * @brief Variance parameter for normal distribution
339 *
340 * Controls the statistical spread in normal distribution.
341 * Higher values increase entropy and distribution width.
342 */
343 double m_normal_spread;
344
345 /** @brief Normal distribution with mean 0 and standard deviation 1 */
346 std::normal_distribution<double> m_normal_dist { 0.0, 1.0 };
347
348 /** @brief Exponential distribution with lambda = 1 */
349 std::exponential_distribution<double> m_exponential_dist { 1.0 };
350
351 /** @brief Internal state for xorshift random number generation */
353
356
357 double m_cached_start = -1.0;
358 double m_cached_end = 1.0;
359 double m_cached_spread = 4.0;
360 bool m_dist_dirty = true;
361};
362}
Base class for all signal and pattern generators in Maya Flux.
uint64_t m_xorshift_state
Internal state for xorshift random number generation.
void set_type(Utils::distribution type)
Changes the probability distribution type.
~Random() override=default
Virtual destructor.
void save_state() override
Saves the node's current state for later restoration Recursively cascades through all connected modul...
void restore_state() override
Restores the node's state from the last save Recursively cascades through all connected modulator nod...
double fast_uniform() noexcept
Fast uniform random number generator using xorshift algorithm.
Computational stochastic signal generator with multiple probability distributions.
StochasticContextGpu(double value, Utils::distribution type, double amplitude, double range_start, double range_end, double normal_spread, std::span< const float > gpu_data)
Utils::distribution distribution_type
Current distribution type.
StochasticContext(double value, Utils::distribution type, double amplitude, double range_start, double range_end, double normal_spread)
Constructs a StochasticContext with the current generator state.
double normal_spread
Current variance parameter for normal distribution.
double amplitude
Current amplitude scaling factor.
double range_start
Current lower bound of the range.
double range_end
Current upper bound of the range.
Specialized context for stochastic generator callbacks.
GPU-uploadable 1D array data interface.
Base context class for node callbacks.
Definition Node.hpp:30