| commit | author | age | ||
| 7c2a8f | 1 | import random |
| 91fb15 | 2 | from . import Exceptions |
| 7c2a8f | 3 | |
| d89217 | 4 | |
| 404823 | 5 | class VariableGeneratorFactory: |
| 7c2a8f | 6 | @staticmethod |
| SP | 7 | def get_generator(definition): |
| 8 | spl = definition.split() | |
| 9 | type = spl[0] | |
| 10 | arglist = spl[1:] | |
| 11 | ||
| 12 | if type == "FixedVals": | |
| 404823 | 13 | return FixedVariableGenerator(arglist) |
| 91fb15 | 14 | if type == "RandLinear": |
| SP | 15 | return RandLinearVariableGenerator(arglist) |
| 7c2a8f | 16 | |
| SP | 17 | else: |
| 18 | return None | |
| 19 | ||
| 20 | ||
| 404823 | 21 | class FixedVariableGenerator(VariableGeneratorFactory): |
| 7c2a8f | 22 | def __init__(self, arglist): |
| 91fb15 | 23 | |
| d89217 | 24 | if len(arglist) == 0: |
| SP | 25 | raise Exceptions.WrongParameters( |
| 26 | "In FixedVals you must provide at least one element to chose from." | |
| 27 | ) | |
| 91fb15 | 28 | |
| SP | 29 | try: |
| 30 | self.pool = [float(i) for i in arglist] | |
| 31 | except (ValueError, TypeError): | |
| 32 | raise ValueError | |
| 7c2a8f | 33 | |
| SP | 34 | def __next__(self): |
| 35 | return random.choice(self.pool) | |
| 36 | ||
| 37 | def __iter__(self): | |
| 38 | return self | |
| 91fb15 | 39 | |
| SP | 40 | |
| 41 | class RandLinearVariableGenerator(VariableGeneratorFactory): | |
| 42 | def __init__(self, arglist): | |
| 43 | try: | |
| d89217 | 44 | self.min = float(arglist[0]) |
| SP | 45 | self.max = float(arglist[1]) |
| 91fb15 | 46 | except (ValueError, TypeError): |
| SP | 47 | raise ValueError |
| 48 | ||
| d89217 | 49 | if len(arglist) != 2: |
| 91fb15 | 50 | raise Exceptions.WrongParameters("RandLinear accepts exactly 2 arguments.") |
| d89217 | 51 | if self.min >= self.max: |
| SP | 52 | raise ValueError( |
| 53 | "In RandLinear, first argument must be lower than second argument." | |
| 54 | ) | |
| 91fb15 | 55 | |
| SP | 56 | def __next__(self): |
| 57 | return random.uniform(self.min, self.max) | |
| 58 | ||
| 59 | def __iter__(self): | |
| d89217 | 60 | return self |