MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
RewriteOperator.hpp
Go to the documentation of this file.
1#pragma once
2
4
6
7/**
8 * @brief Bounded parallel rewriting of a typed word in a RelationNetwork.
9 *
10 * A symbol is an id plus up to eight numeric parameters. A character literal
11 * is its own id, so grammars read the way they are written on paper.
12 * Replacements may be conditional, context sensitive and stochastic.
13 *
14 * Rewriting runs on one producer lane and builds a draft word. submit() hands
15 * the draft to the network, and process() makes it the active word at a block
16 * boundary without allocating or releasing word storage.
17 *
18 * @code
19 * auto rewrite = n->add<RewriteOperator>(RewriteOperator::Config {
20 * .axiom = RewriteOperator::symbols_from_text("F"),
21 * .max_word_length = 4096,
22 * .max_generations = 5 });
23 * rewrite->replace('F', "F[+F]F[-F]F");
24 * rewrite->rewrite(4);
25 * rewrite->submit();
26 * @endcode
27 */
28class MAYAFLUX_API RewriteOperator final : public RelationOperator {
29public:
30 using SymbolId = uint32_t;
31 static constexpr size_t max_symbol_parameters = 8;
32
33 struct MAYAFLUX_API Symbol {
34 SymbolId id {};
35 std::array<double, max_symbol_parameters> parameters {};
36 uint8_t arity {};
37
38 Symbol(SymbolId id, std::initializer_list<double> values = {});
39
40 template <std::convertible_to<double>... Values>
41 requires(sizeof...(Values) > 0 && sizeof...(Values) <= max_symbol_parameters)
42 Symbol(SymbolId symbol_id, Values... values)
43 : id(symbol_id)
44 , parameters { static_cast<double>(values)... }
45 , arity(static_cast<uint8_t>(sizeof...(Values)))
46 {
47 }
48
49 [[nodiscard]] std::optional<double> parameter(size_t index) const noexcept;
50 };
51
52 struct Word {
53 std::vector<Symbol> symbols;
54 uint64_t generation {};
55 };
56
57 /** @brief A tag that is the same for every use of one type C in a module, and differs between types. */
58 template <typename C>
59 [[nodiscard]] static const void* controls_tag() noexcept
60 {
61 static const char tag {};
62 return &tag;
63 }
64
65 /** @brief What a replacement sees: the caller's inputs, the word with the symbol's position in it, and the grammar's controls. */
66 struct Environment {
67 std::span<const double> inputs;
68 std::span<const Symbol> word;
69 size_t position {};
70 const void* held {};
71 const void* held_tag {};
72
73 /**
74 * @brief The grammar's controls as they were when this rewrite began.
75 * @tparam C The struct given to declare(). Any other type returns a default one.
76 */
77 template <typename C>
78 [[nodiscard]] const C& controls() const noexcept
79 {
80 static const C none {};
81 return held_tag == controls_tag<C>() && held != nullptr ? *static_cast<const C*>(held) : none;
82 }
83 };
84
85 /** @brief Append a symbol; false on a bound violation. Valid only during the replacement call. */
86 using EmitSymbol = std::function<bool(Symbol)>;
87 using Predicate = std::function<bool(const Symbol&, Environment)>;
88 using Successor = std::function<void(const Symbol&, Environment, const EmitSymbol&)>;
89
90 /**
91 * @brief One rewrite rule: left < predecessor > right, if predicate, with weight
92 *
93 * left and right are matched against the symbols adjacent to the
94 * predecessor in word order, skipping Config::ignore. The first matching
95 * replacement wins, unless it has a positive weight: then one of the
96 * matching weighted replacements of that symbol is drawn in proportion to
97 * its weight, which is the stochastic L-system.
98 */
99 struct Replacement {
101 std::vector<SymbolId> left;
102 std::vector<SymbolId> right;
104 double weight {};
106 };
107
108 struct Config {
109 std::vector<Symbol> axiom;
111 uint64_t max_generations {};
112 std::vector<SymbolId> ignore;
113 };
114
115 enum class RewriteResult : uint8_t {
116 REWRITTEN,
117 INVALID_CONFIG,
118 GENERATION_LIMIT,
119 WORD_LIMIT,
120 REPLACEMENT_FAILED
121 };
122
123 enum class SubmitResult : uint8_t {
124 SUBMITTED,
125 INVALID_CONFIG,
126 BUSY,
127 SUBMISSION_LIMIT
128 };
129
130 /** @brief What grow() did; the first failure of its rewrite or its submit. */
131 enum class GrowResult : uint8_t {
132 GROWN,
133 BUSY,
134 INVALID_CONFIG,
135 GENERATION_LIMIT,
136 WORD_LIMIT,
137 REPLACEMENT_FAILED,
138 SUBMISSION_LIMIT
139 };
140
141 explicit RewriteOperator(Config config);
142
143 [[nodiscard]] bool valid() const noexcept { return m_valid; }
144
145 /** @brief One parameterless symbol per character, each character being its own id. */
146 [[nodiscard]] static std::vector<Symbol> symbols_from_text(std::string_view text);
147
148 /** @brief A successor that emits the text's characters as parameterless symbols. */
149 [[nodiscard]] static Successor text_successor(std::string_view text);
150
151 /** @brief Append a rule; false when the operator is invalid or the successor is empty. */
152 bool replace(Replacement replacement);
153 bool replace(SymbolId predecessor, Successor successor, Predicate predicate = {});
154
155 /** @brief Append a rule whose successor is text. A positive weight makes it one choice of a stochastic rule. */
156 bool replace(SymbolId predecessor, std::string_view successor, double weight = 0.0);
157 void clear_replacements() noexcept { m_replacements.clear(); }
158
159 /**
160 * @brief The generator behind weighted choices
161 * @note Producer lane only. Seed it for a repeatable word.
162 */
163 [[nodiscard]] Kinesis::Stochastic::Stochastic& generator() noexcept { return m_generator; }
164
165 /**
166 * @brief Declare the struct of controls the grammar's rules read, and return it.
167 * @tparam C A described struct whose members are all Control.
168 *
169 * Call once, before the first rewrite() and before any thread sets or reads the
170 * controls. A rule reads them through Environment::controls<C>().
171 *
172 * @code
173 * struct Bloom { Control rate; Control angle; };
174 * MF_DESCRIBE(Bloom)
175 *
176 * rewrite->declare<Bloom>();
177 * rewrite->replace('F', [](const Symbol& s, Environment env, const EmitSymbol& emit) {
178 * emit({ 'F', s.parameters[0] * env.controls<Bloom>().rate.value() });
179 * });
180 * rewrite->set<Bloom>({ .rate = 0.3, .angle = lfo });
181 * @endcode
182 */
183 template <typename C>
185 {
186 m_hold = [this] {
187 return std::shared_ptr<const void>(std::make_shared<const C>(snapshot_controls<C>()));
188 };
189 m_read = [this](std::string_view name) {
191 };
193 return declare_controls<C>();
194 }
195
196 /**
197 * @brief Apply the members of @p incoming that hold a value; empty members are left alone.
198 *
199 * A number may be set from any thread. A node source is attached outside rewrite().
200 */
201 template <typename C>
202 void set(const C& incoming)
203 {
204 merge_controls(incoming);
205 }
206
207 /** @brief The controls with the values the operator holds now. */
208 template <typename C>
209 [[nodiscard]] C get() const
210 {
211 return snapshot_controls<C>();
212 }
213
214 /** @brief Rewrite the draft word on the producer lane, without submitting it. */
215 [[nodiscard]] RewriteResult rewrite(uint64_t steps = 1, std::span<const double> inputs = {});
216
217 /** @brief Submit the draft word; it becomes the active word at the next RelationNetwork block. */
218 [[nodiscard]] SubmitResult submit();
219
220 /**
221 * @brief Rewrite the draft word and submit it, on the producer lane
222 * @param steps Generations to build, as for rewrite()
223 * @param inputs Numeric inputs, as for rewrite()
224 *
225 * Does nothing and returns BUSY while a submission is still pending, so the draft
226 * never moves ahead of what can be published. To keep rewriting while a
227 * submission is pending, call rewrite() and submit() yourself.
228 */
229 [[nodiscard]] GrowResult grow(uint64_t steps = 1, std::span<const double> inputs = {});
230
231 /**
232 * @brief True once the word last submitted is the draft and is the active word
233 * @note Producer lane only. A restore_axiom() or a later rewrite() makes it false again.
234 */
235 [[nodiscard]] bool published() const noexcept;
236
237 /** @brief Restore the axiom as the draft word on the producer lane, without submitting it. */
238 [[nodiscard]] bool restore_axiom();
239
240 [[nodiscard]] uint64_t draft_generation() const noexcept { return m_draft->generation; }
241
242 /**
243 * @brief The draft word on the producer lane: the axiom, or what rewrite() last built.
244 *
245 * It is the word submit() would hand over, so a producer can read what it
246 * has just rewritten before submitting it. A rewrite that a bound refused
247 * leaves it unchanged. The word is immutable and stays valid after it is
248 * submitted or replaced.
249 */
250 [[nodiscard]] std::shared_ptr<const Word> draft_word() const noexcept { return m_draft; }
251 [[nodiscard]] uint64_t active_generation() const noexcept
252 {
253 return m_active_generation.load(std::memory_order_acquire);
254 }
255
256 /** @brief Return the latest active word on the producer lane. */
257 [[nodiscard]] std::shared_ptr<const Word> active_word() const;
258
259 /** @brief Read the active word on the RelationNetwork processing lane. */
260 [[nodiscard]] std::span<const Symbol> active_symbols() const noexcept
261 {
262 return m_active.word->symbols;
263 }
264
265 void process(float frames) override;
266
267 /** @brief Set the control called @p name; unknown names are logged and ignored. map() reaches it the same way. */
268 void set_parameter(std::string_view name, double value) override;
269
270 /** @brief The number held by the control called @p name, or nullopt for an unknown name. */
271 [[nodiscard]] std::optional<double> query_state(std::string_view name) const override;
272 [[nodiscard]] std::string_view get_type_name() const override { return "Rewrite"; }
273
274private:
275 struct Submission {
276 std::shared_ptr<const Word> word;
277 uint64_t id {};
278 };
279
281 public:
282 [[nodiscard]] bool push(Submission& submission) noexcept;
283 [[nodiscard]] Submission pop() noexcept;
284
285 private:
287 std::atomic<bool> m_full { false };
288 };
289
290 void drain_retired();
291 [[nodiscard]] bool matches_context(const Replacement& replacement, const Environment& environment) const;
292 [[nodiscard]] const Replacement* select_replacement(const Symbol& symbol, const Environment& environment);
293
294 std::shared_ptr<const Word> m_axiom;
298 std::function<std::shared_ptr<const void>()> m_hold;
299 std::function<std::optional<double>(std::string_view)> m_read;
300 const void* m_held_tag {};
301 std::vector<SymbolId> m_ignore;
302 std::vector<Replacement> m_replacements;
304 std::vector<const Replacement*> m_candidates;
305 std::vector<double> m_weights;
306
307 std::shared_ptr<const Word> m_draft;
308 std::shared_ptr<const Word> m_active_word;
311 bool m_pending {};
313
318 std::atomic<uint64_t> m_active_generation;
319 std::atomic<uint64_t> m_active_submission_id;
320};
321
322} // namespace MayaFlux::Nodes::Network
static std::optional< double > read_named(const C &controls, std::string_view name)
Unified generative infrastructure for stochastic and procedural algorithms.
C & declare_controls()
Create the operator's controls struct and keep it alive.
void merge_controls(const C &incoming)
Apply the members of incoming that hold a value, for an operator whose controls type is not fixed.
C snapshot_controls() const
A copy of the declared struct, for an operator whose controls type is not fixed.
Operator that acts on a network's slots over one block at a time.
std::string_view get_type_name() const override
Type name for introspection.
std::function< bool(Symbol)> EmitSymbol
Append a symbol; false on a bound violation.
void set(const C &incoming)
Apply the members of incoming that hold a value; empty members are left alone.
std::function< std::shared_ptr< const void >()> m_hold
std::shared_ptr< const Word > m_active_word
std::shared_ptr< const Word > draft_word() const noexcept
The draft word on the producer lane: the axiom, or what rewrite() last built.
Kinesis::Stochastic::Stochastic & generator() noexcept
The generator behind weighted choices.
static const void * controls_tag() noexcept
A tag that is the same for every use of one type C in a module, and differs between types.
std::function< std::optional< double >(std::string_view)> m_read
std::vector< const Replacement * > m_candidates
std::function< void(const Symbol &, Environment, const EmitSymbol &)> Successor
std::span< const Symbol > active_symbols() const noexcept
Read the active word on the RelationNetwork processing lane.
C get() const
The controls with the values the operator holds now.
Kinesis::Stochastic::Stochastic m_generator
GrowResult
What grow() did; the first failure of its rewrite or its submit.
C & declare()
Declare the struct of controls the grammar's rules read, and return it.
std::function< bool(const Symbol &, Environment)> Predicate
Bounded parallel rewriting of a typed word in a RelationNetwork.
Globlal configuration for MayaFlux.
Definition Config.cpp:20
const C & controls() const noexcept
The grammar's controls as they were when this rewrite began.
What a replacement sees: the caller's inputs, the word with the symbol's position in it,...
One rewrite rule: left < predecessor > right, if predicate, with weight.
std::array< double, max_symbol_parameters > parameters
Symbol(SymbolId symbol_id, Values... values)
Symbol(SymbolId id, std::initializer_list< double > values={})