-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator_builder.py
More file actions
780 lines (631 loc) · 30.1 KB
/
generator_builder.py
File metadata and controls
780 lines (631 loc) · 30.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
"""
Copyright (c) 2026 Peter Robinson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Support for building generators that could, for example, be used to drive PWM LEDs.
This module provides a set of generator factory classes that make it easy to compose and reuse
generator behavior across applications. Each GeneratorFactory, when called, returns a fresh generator
that yields values. Many classes are 'higher order' - they take generator factories as parameters
and return new factories that combine them in useful ways (sequencing, repeating, filtering, etc.)
Example:
Create and compose generators:
>>> constant_seq_gen = Sequencer([Constant(1.0,2), Constant(0.0,1)])
>>> repeater = Repeater(constant_seq_gen, 2)
>>> for value in repeater():
... print(value)
1.0
1.0
0.0
1.0
1.0
0.0
Note: Throughout the documentation there is a slight abuse of notation. When we say "yields from a generator factory"
we really mean "yields from a generator created by calling the generator factory"
"""
import sys
import random
import time
# These generators are intended to be generally useful and so for writing the implementation
# we use type hints that would be valid in standard Python. However this is not supported in MicroPython
# so we skip type checking support when running in MicroPython
# The following two lines (as well as any type annotations) are removed when strip_type_hints.py is run
from typing import Generator, TypeVar, Callable
T = TypeVar('T')
class GeneratorFactory[T]:
"""Base class for all generator factories.
A GeneratorFactory is a callable object that returns a fresh generator each time it is called.
Subclasses implement the _generate() method to define the specific generator behavior.
This design allows factories to be composed together to create complex generator behaviors
while maintaining the ability to generate fresh, independent instances.
Example:
>>> gen_factory = Constant(42)
>>> gen1 = gen_factory() # Fresh generator
>>> next(gen1)
42
>>> gen2 = gen_factory() # Another fresh generator
>>> gen1 is gen2
False
"""
def __call__(self) -> Generator[T, None, None]:
"""Create and return a fresh generator instance.
Returns:
A new generator that yields values of type T.
"""
return self._generate()
def _generate(self) -> Generator[T, None, None]:
"""Generate values. Must be implemented by subclasses.
This is an abstract method that subclasses must override to provide
the actual generator logic.
Returns:
A generator yielding values of type T.
Raises:
NotImplementedError: Always, as this is an abstract method.
"""
raise NotImplementedError("Subclasses must implement _generate")
class Sequencer[T](GeneratorFactory[T]):
"""Chains multiple generators sequentially.
When called, returns a generator factory that yields all values from the first generator factory,
then all values from the second, and so on. Each generator factory is called once to create
a fresh generator.
Note: Each generator (except possibly the last) should be finite, otherwise the sequencer
will never move on to the next generator.
Args:
factories: A list of generator factory callables that return generators.
Example:
>>> fact1 = ConstantFor(1, 2) # Yield 1 twice
>>> fact2 = ConstantFor(2, 2) # Yield 2 twice
>>> seq = Sequencer([fact1, fact2])
>>> list(seq())
[1, 1, 2, 2]
"""
def __init__(self, factories: list[Callable[[], Generator[T,None,None]]]):
"""Initialize the Sequencer.
Args:
factories: A list of generator factories.
"""
self.factories = factories
def _generate(self) -> Generator[T,None,None]:
"""Yield values from each generator in sequence.
Yields:
Values from the generator instance from each generator factory in order.
"""
for factory in self.factories:
yield from factory()
class Chooser[T](GeneratorFactory[T]):
"""Randomly selects one factory and yields all the values from that factory.
When called, randomly chooses one generator factory from the list and returns a generator factory
that yields all values from the chosen generator factory. Each call to the Chooser factory will
make a new random selection.
Args:
factories: A list of generator factories to choose from.
Example:
>>> fact1 = ConstantFor(1, 2)
>>> fact2 = ConstantFor(2, 2)
>>> chooser = Chooser([fact1, fact2])
>>> # Result is either [1, 1] or [2, 2], chosen randomly
>>> list(chooser())
"""
def __init__(self, factories: list[Callable[[], Generator[T,None,None]]]):
"""Initialize the Chooser.
Args:
factories: A list of generator factories.
"""
self.factories = factories
def _generate(self) -> Generator[T,None,None]:
"""Randomly select and yield from one generator factory.
Yields:
All values from a randomly selected generator factory call.
"""
yield from random.choice(self.factories)()
class Repeater[T](GeneratorFactory[T]):
""" This generator factory repeats in three different ways depending on the supplied arguments.
The first argument is a generator factory.
The second argument defines the repeating behaviour:
- None: repeat indefinitely.
- number: repeat that many times.
- [min, max]: repeat a random number of times between min and max (inclusive).
When called, returns a generator factory that yields from the supplied generator factory the specified number of times.
Each repetition uses a fresh generator from the factory.
Note: Each generator produced from the supplied factory should be finite, otherwise the repeater is redundant.
Args:
factory: A generator factory.
repeats: Arguments to determine repetition behavior.
- None: repeat indefinitely.
- number: repeat that many times.
- [min, max]: repeat a random number of times between min and max (inclusive).
"""
def __init__(self, factory: Callable[[], Generator[T,None,None]],
repeats: int | list[int] | None = None):
"""Initialize the Repeater.
Args:
factory: A generator factory callable.
repeats: Arguments to determine repetition behavior.
- None: repeat indefinitely.
- number: repeat that many times.
- [min, max]: repeat a random number of times between min and max (inclusive).
"""
self.factory = factory
self.repeats = repeats
def _generate(self) -> Generator[T,None,None]:
"""Yield values from the generator, repeated according to the specified behavior.
Yields:
Values from the generator, repeated according to the initialization parameters.
Note that each repitition calls the factory producing a new generator.
"""
if self.repeats is None:
# Repeat indefinitely
while True:
yield from self.factory()
elif isinstance(self.repeats, int):
# Repeat a fixed number of times
for _ in range(self.repeats):
yield from self.factory()
else:
# Repeat a random number of times between min and max
count = random.randint(self.repeats[0], self.repeats[1])
for _ in range(count):
yield from self.factory()
class ProbabilityRepeater[T](GeneratorFactory[T]):
"""Repeats a generator with a specified probability.
When called, returns a generator factory that repeatedly yields from the supplied generator factory
with the specified probability. On each iteration, a random number determines whether to yield
from the generator again or stop. Each repetition uses a fresh generator from the factory.
Note: The supplied generator factory should be finite, otherwise each repetition will not complete.
Args:
probability: Probability (0-100) of repeating the generator on each iteration.
factory: A generator factory.
Example:
>>> fact = Constant(1, 1) # Yield 1 once
>>> repeater = ProbabilityRepeater(50, fact) # 50% chance to repeat
>>> list(repeater()) # Result varies: could be [1] or [1, 1] or [1, 1, 1], etc.
"""
def __init__(self, probability: int, factory: Callable[[], Generator[T,None,None]]):
"""Initialize the ProbabilityRepeater.
Args:
probability: The probability (0-100) of repeating on each iteration.
factory: A generator factory.
"""
self.probability = probability
self.factory = factory
def _generate(self) -> Generator[T,None,None]:
"""Yield values from the generator factory, repeating based on random probability.
Yields:
Values from the generator factory. After each iteration, continues with supplied probability %.
A new generator is created on each iteration
"""
while random.randint(0,100) < self.probability:
yield from self.factory()
class SingleConstant[T](GeneratorFactory[T]):
"""Yields a single constant value.
When called, returns a generator that yields the specified value once and then stops.
Useful for fixed single-value outputs or as a building block in compositions.
It is expected that the user will not use this directly as yielding a constant once is not very useful.
Instead Constant is SingleConstant wrapped with a Repeater - see below.
Args:
value: The constant value to yield once.
Example:
>>> single_const = SingleConstant(42)
>>> list(single_const())
[42]
"""
def __init__(self, value: T):
"""Initialize the SingleConstant.
Args:
value: The constant value to yield.
"""
self.value = value
def _generate(self) -> Generator[T, None, None]:
"""Yield the constant value once.
Yields:
The constant value a single time.
"""
yield self.value
def Constant(value: T, *args) -> GeneratorFactory[T]:
"""A factory function that creates a generator factory yielding a constant value with flexible repetition.
This function provides a convenient interface for creating generator factories that yield a constant value
with various repetition behaviors. The aditional argument determine how the constant value is repeated and is
the same as for the Repeater class"""
return Repeater(SingleConstant(value), *args)
class BasicWaveGeneratorFactory[T](GeneratorFactory[T]):
"""Generator factory derived from a function that has configurable discretization and offset.
Yields values according to a function that maps the interval [0, 1] to [0, 1]. The function is discretized into a
configurable number of steps and can be repeated multiple times. The function is treated as defining one complete
cycle of a periodic function.
As with SingleConstant it is expected that the user will more typically use this with a Repeater wrapper - see below.
Args:
func: A callable that takes a float in [0, 1] and returns a float in [0, 1].
steps: the number of steps for one cycle of the periodic function (default 4) is either:
int: the number of steps
(low, hi): choose a random number in the range [low, hi]
runs: the number of cycles computed (default 1) is either:
int: the number of steps
(low, hi): choose a random number in the range [low, hi]
offset: an offset for the start of the cycle (default 0.0)
For symmetry reasons steps/steps range is modified so that the staps become a multiple of 4.
Attributes:
func: The supplied function.
steps_is_int: True iff the steps argument is an int
steps: the number of steps for one cycle of the periodic function (0 if not steps_is_int)
low_steps_4: if not steps_is_int then this is the first element of steps divided by 4 (0 if steps_is_int)
hi_steps_4: if not steps_is_int then this is the second element of steps divided by 4 (0 if steps_is_int)
runs_is_int: True iff the steps argument is an int
runs: the number of cycles computed (0 if not runs_is_int)
low_runs: if not runs_is_int then this is the first element of runs (0 if runs_is_int)
hi_runs: if not runs_is_int then this is the second element of runs (0 if runs_is_int)
offset: an offset for the start of the cycle (default 0.0)
Example:
>>> sine_wave = BasicWaveGeneratorFactory(sine_function, steps=16)
>>> gen = sine_wave()
>>> values = list(gen)
>>> len(values)
16
"""
def __init__(self, func: Callable[[float], T], steps: int | tuple[int,int] = 4,
runs: int | tuple[int,int] = 1, offset: float = 0.0):
"""Initialize the BasicWaveGeneratorFactory generator factory.
Args:
func: A callable that takes a float in [0, 1] and returns a float in [0, 1].
steps: the number of steps for one cycle of the periodic function (default 4) is either:
int: the number of steps
(low, hi): choose a random number in the range [low, hi]
runs: the number of cycles computed (default 1) is either:
int: the number of steps
(low, hi): choose a random number in the range [low, hi]
offset: an offset for the start of the cycle (default 0.0)
"""
self.func = func
if isinstance(steps, int):
self.steps_is_int = True
self.steps = 4*(steps // 4) # make steps a multiple of 4
self.low_steps_4 = 0
self.hi_steps_4 = 0
else:
self.steps_is_int = False
self.steps = 0
self.low_steps_4 = steps[0]//4
self.hi_steps_4 = steps[1]//4
if isinstance(runs, int):
self.runs_is_int = True
self.runs = runs
self.low_runs = 0
self.hi_runs = 0
else:
self.runs_is_int = False
self.runs = 0
self.low_runs = runs[0]
self.hi_runs = runs[1]
self.offset = offset
def _generate(self) -> Generator[T, None, None]:
"""Generate one or more complete cycles of the waveform.
Yields:
Float values in [0, 1] from the waveform
"""
if self.steps_is_int:
steps = self.steps
else:
steps = 4*random.randint(self.low_steps_4, self.hi_steps_4)
if self.runs_is_int:
runs = self.runs
else:
runs = random.randint(self.low_runs, self.hi_runs)
step_slice = 1.0 / steps
for _ in range(runs):
for i in range(steps):
position = (self.offset + i * step_slice) % 1.0 # float version of modulo for wrap-around
yield self.func(position)
def WaveGeneratorFactory[T](func: Callable[[float], T], *args, **kwargs) -> GeneratorFactory[T]:
"""A factory function that creates a generator factory yielding values from a wave factory with flexible repetition.
This function provides a convenient interface for creating generator factories for waves
with various repetition behaviors. This factory is a BasicWaveGeneratorFactory wrapped in a Repeater factory.
If repeats is given (defaults to prducing an infinite generator) it needs to be given as a keyword arg.
The runs argument only needs to be set to anything other than the default of 1 if steps is chosen randomly as
the repart part will take care of repition.
Example:
>>> sine_wave = BasicWaveGeneratorFactory(sine_function, steps=16, repeats = 2)
>>> gen = sine_wave()
>>> values = list(gen)
>>> len(values)
32
"""
# Pop repeats so as not to cause trouble for the call to BasicWaveGeneratorFactory
repeats = kwargs.pop('repeats', None)
if repeats == 1: # no repeating
return BasicWaveGeneratorFactory(func, *args, **kwargs)
return Repeater(BasicWaveGeneratorFactory(func, *args, **kwargs), repeats)
class TabledFunction[T]:
"""This class is used to precompute fuction values and store them in a table and then look up values
rather than compute the function.
Args:
func: a function defined on [0,1]
power: a table (list) is constructed of size 2**power. The bigger power is the more accurate the calculation
is at the expense of consuming more space.
Attributes:
table_size: the size of the table (2**power)
table_size_1: 2**power-1
table: a list of precomputed values
"""
def __init__(self, func: Callable[[float], T], power:int):
"""Args:
func: a function defined on [0,1]
power: a table (list) is constructed of size 2**power. The bigger power is the more accurate the calculation
is at the expense of consuming more space.
"""
self.func = func
self.table_size = 2**power
self.table_size_1 = self.table_size-1
self.table = []
# Precompute the table: each index (integer value in [0, self.table_size-1]) is mapped to a value in [0,1]
# and the result of applying the function to that value is stored in the table at that index
for index in range(self.table_size):
self.table.append(self.func(index/(self.table_size_1)))
def __call__(self, x):
# Given an x in [0,1], the index in the table is computed. If the computed index is outside the range
# (typically because of an offset calculation) the result is shifted by taking the value mod self.table_size-1
# (treating the function as cyclic)
return self.table[round(x*(self.table_size_1)) & (self.table_size_1)]
class Tester:
"""Base class for testers used with TakeWhile.
A Tester is used by TakeWhile to determine when to stop yielding values.
When called, a Tester returns a callable that can be invoked repeatedly to test a condition.
The design separates the tester factory (the Tester object itself) from the actual test function,
allowing state to be reset for each new use of a TakeWhile generator.
Subclasses should override __call__() to return a test function, and may override on_false()
to perform cleanup when the test first returns False.
"""
def __call__(self) -> Callable[[], bool]:
"""Create and return a fresh test function.
Returns:
A callable that takes no arguments and returns a boolean. The callable will be
invoked repeatedly by TakeWhile until it returns False.
Raises:
NotImplementedError: Always, as this is an abstract method.
"""
raise NotImplementedError("Subclasses must implement __call__")
def on_false(self):
"""Called when the tester returns False for the first time.
Override this method in subclasses to perform cleanup or state management when
the test condition becomes false. The default implementation does nothing.
"""
pass
class TakeWhile[T](GeneratorFactory[T]):
"""Yields values while a test condition is true.
When called, returns a generator that yields values from the supplied generator factory
only while the supplied tester returns True. Once the tester returns False, the generator
stops and the tester's on_false() method is called.
This allows for sophisticated filtering and early termination based on custom conditions,
including time-based or count-based limits.
Args:
tester: A Tester object that determines when to stop yielding.
factory: A generator factory callable that produces generators.
Example:
>>> tester = CountTester(3) # Stop after 3 values
>>> gen = Constant(1) # Infinite generator
>>> take_while = TakeWhile(tester, gen)
>>> list(take_while())
[1, 1, 1]
"""
def __init__(self, tester: Tester, factory: Callable[[], Generator[T,None,None]]):
"""Initialize the TakeWhile.
Args:
tester: A Tester instance.
factory: A generator factory.
"""
self.tester = tester
self.factory = factory
def _generate(self) -> Generator[T,None,None]:
"""Yield values while the test condition is true.
Yields:
Values from the generator while the tester's test function returns True.
After yielding stops, calls tester.on_false().
"""
g = self.factory() # Get a fresh generator
test = self.tester() # Get a fresh tester function
while test():
yield next(g)
# Tester returned false
self.tester.on_false()
class CountTester(Tester):
"""Tester that stops after a specified number of iterations.
Returns True while an internal counter is below the limit, False once the limit is reached.
Resets the counter each time __call__() is invoked, allowing fresh starts for multiple
uses of TakeWhile with the same tester.
Args:
limit: The maximum number of iterations before returning False.
Example:
>>> tester = CountTester(3)
>>> gen = TakeWhile(tester, Constant(1))
>>> list(gen())
[1, 1, 1]
"""
def __init__(self, limit: int):
"""Initialize the CountTester.
Args:
limit: The iteration limit.
"""
self.limit = limit
self.count = 0
def __call__(self) -> Callable[[], bool]:
"""Create a fresh test function with counter reset.
Returns:
A callable that returns True while counter < limit, False when limit is reached.
"""
# reset count each time __call__ is invoked as part of a fresh
# use of a TakeWhile generator
self.count = 0
def test_fun() -> bool:
result = self.count < self.limit
self.count += 1
return result
return test_fun
class TimeoutTester(Tester):
"""Tester that stops after a specified time duration.
Returns True while elapsed time is below the limit, False once the time limit is exceeded.
Resets the start time each time __call__() is invoked, allowing fresh starts for multiple
uses of TakeWhile with the same tester.
The time measurement can be overridden via _get_time() for different environments
(e.g., MicroPython vs standard Python).
Args:
limit_seconds: The maximum time in seconds before returning False.
Example:
>>> tester = TimeoutTester(1.0) # 1 second timeout
>>> gen = TakeWhile(tester, Constant(1))
>>> # Yields values for 1 second, then stops
>>> list(gen())
"""
def __init__(self, limit_seconds: float):
"""Initialize the TimeoutTester.
Args:
limit_seconds: The time limit in seconds.
"""
self.limit_seconds = limit_seconds
def _get_time(self) -> float:
"""Get the current time in seconds.
Override this method if running in an environment with a different time API
(e.g., MicroPython). For standard Python, uses time.time(). For MicroPython,
attempts to use mp_time.ticks_ms().
Returns:
Current time in seconds as a float.
"""
if 'micropython' in sys.modules:
return time.ticks_ms() / 1000.0
else:
return time.time()
def __call__(self) -> Callable[[], bool]:
"""Create a fresh test function with timer reset.
Returns:
A callable that returns True if elapsed time < limit, False otherwise.
"""
# reset start time each time __call__ is invoked as part of a fresh
# use of a TakeWhile generator
start_time = self._get_time()
def test_fun() -> bool:
return (self._get_time() - start_time) < self.limit_seconds
return test_fun
# Test code and example usage
if __name__ == "__main__":
class RampGen(GeneratorFactory[float]):
"""A generator that yields values from start to end in steps."""
def __init__(self, start: float, end: float, steps: int):
self.start = start
self.end = end
self.steps = steps
def _generate(self) -> Generator[float, None, None]:
step_size = (self.end - self.start) / self.steps
current = self.start
for _ in range(self.steps):
yield current
current += step_size
class SineGeneratorFactoryFromFunctionGen(GeneratorFactory[float]):
"""A generator that yields values from a sine wave."""
def __init__(self, amplitude: float = 1.0, frequency: float = 1.0, steps: int = 100):
self.amplitude = amplitude
self.frequency = frequency
self.steps = steps
def _generate(self) -> Generator[float, None, None]:
import math
for i in range(self.steps):
yield self.amplitude * math.sin(2 * math.pi * self.frequency * i / self.steps)
class AlwaysTrueTester(Tester):
"""A tester that always returns True."""
def __call__(self) -> Callable[[], bool]:
def test_fun() -> bool:
return True
return test_fun
print("Testing generator builders...")
print("\n1. Testing take_while:")
tester = CountTester(3)
take_while_gen = TakeWhile(tester, Constant(1.0))
values = []
for val in take_while_gen():
values.append(val)
print(f"Take while output (while counter < 3): {values}")
take_while_1 = TakeWhile(CountTester(3), Constant(1.0))
take_while_2 = TakeWhile(CountTester(3), Constant(2.0))
take_while_3 = TakeWhile(CountTester(3), Constant(3.0))
print("\n2. Testing sequencer:")
seq_gen = Sequencer([
TakeWhile(CountTester(3), Constant(1.0)),
TakeWhile(CountTester(5), RampGen(0.0, 1.0, 5)),
Constant(0.01, 1)
])
values = []
for i, val in enumerate(seq_gen()):
values.append(round(val, 2))
if len(values) >= 10: # Limit output
break
print(f"Sequencer output: {values}")
print("\n3. Testing repeater:")
repeat_gen = Repeater(RampGen(0.0, 1.0, 3), 3)
values = []
for val in repeat_gen():
values.append(round(val, 2))
print(f"Repeater output (3 times): {values}")
print("\n4. Testing chooser:")
choose_gen = Repeater(Chooser([
take_while_1,
take_while_2,
take_while_3
]), 10)
values = []
gen = choose_gen()
for i in range(20):
val = next(gen)
values.append(val)
print(f"Chooser output (20 random choices): {values}")
print("\n5. Testing ProbabilityRepeater:")
random_repeat_gen = ProbabilityRepeater(50, take_while_1) # 50% probability
values = []
count = 0
for val in random_repeat_gen():
values.append(val)
count += 1
if count >= 20: # Safety limit
break
print(f"Random repeater output (up to 20 values): {values}")
print("\n6. Testing always_repeater:")
always_repeat_gen = Repeater(Sequencer([take_while_1, take_while_2]))
values = []
for i, val in enumerate(always_repeat_gen()):
values.append(val)
if i >= 20: # Only take first 20 values
break
print(f"Always repeater output (first 20): {values}")
print("\n7. Testing sine_wave_gen:")
sine_gen = SineGeneratorFactoryFromFunctionGen(amplitude=1.0, frequency=1.0, steps=10)
values = []
for val in sine_gen():
values.append(round(val, 2))
print(f"Sine wave output (first 10 steps): {values}")
print("\n8. Testing inheritance and callable interface:")
generators = [
Sequencer([Constant(1.0)]),
Chooser([Constant(1.0)]),
Repeater(Constant(1.0),1),
ProbabilityRepeater(100, Constant(1.0)),
Repeater(Constant(1.0)),
TakeWhile(AlwaysTrueTester(), Constant(1.0)),
Constant(1.0),
Constant(1.0, 5),
RampGen(0.0, 1.0, 5),
SineGeneratorFactoryFromFunctionGen()
]
for gen in generators:
print(f"{gen.__class__.__name__}: isinstance(GeneratorFactory) = {isinstance(gen, GeneratorFactory)}")
gen_iter = gen()
print(f" Returns generator: {hasattr(gen_iter, '__iter__') and hasattr(gen_iter, '__next__')}")
gen_iter2 = gen()
print(f" Fresh generator each call: {gen_iter is not gen_iter2}")
print("\nAll tests completed!")