### Run all examples with uv Source: https://github.com/alcides/geneticengine/blob/main/docs/source/index.md Runs all example scripts using uv, which automatically resolves dependencies from the project. Requires uv to be installed. ```bash ./run_examples.sh ``` -------------------------------- ### Run examples with Codon enabled Source: https://github.com/alcides/geneticengine/blob/main/docs/source/index.md Runs examples with Codon enabled, using `codon run -release` when feasible and falling back to `uv run python` for examples requiring unsupported third-party packages. Requires Codon to be installed. ```bash CODON=1 ./run_examples.sh ``` -------------------------------- ### Install dependencies and compile with Nuitka Source: https://github.com/alcides/geneticengine/blob/main/CompilingGeneticEngine.md Install Nuitka and project requirements with /opt/homebrew/bin/python3, then compile 'examples/game_of_life.py' as a standalone binary with the numpy plugin. Finally, run the compiled binary with Z3_LIBRARY_PATH set to the Homebrew Z3 library directory. ```text /opt/homebrew/bin/python3 -m pip install nuitka /opt/homebrew/bin/python3 -m pip install -r requirements.txt /opt/homebrew/bin/python3 -m nuitka --standalone --follow-imports --enable-plugin=numpy examples/game_of_life.py Z3_LIBRARY_PATH=/opt/homebrew/Cellar/z3/4.12.1/lib/ game_of_life.dist/game_of_life.bin ``` -------------------------------- ### Install dependencies from requirements.txt Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Install the required dependencies for GeneticEngine using pip and the requirements.txt file. ```bash python -m pip install -r requirements.txt ``` -------------------------------- ### Dependent metahandler example Source: https://github.com/alcides/geneticengine/blob/main/docs/source/metahandlers/index.md Shows how to create a field whose range depends on a previously generated field using the Dependent metahandler. ```python @dataclass class SimplePair: a: Annotated[int, IntRange(0, 3)] b: Annotated[int, Dependent("a", lambda a: IntRange(a, 4))] ``` -------------------------------- ### Public API facade imports Source: https://github.com/alcides/geneticengine/blob/main/docs/architecture/module-reorganization.md Example of importing the public API facade for geneticengine. Shows the intended stable imports for algorithms, evaluation, grammar, problems, random, and representations. ```python from geneticengine.algorithms import GeneticProgramming, RandomSearch from geneticengine.evaluation import EvaluationBudget, TimeBudget from geneticengine.grammar import Grammar, extract_grammar from geneticengine.problems import Problem, SingleObjectiveProblem from geneticengine.random import NativeRandomSource from geneticengine.representations import TreeBasedRepresentation ``` -------------------------------- ### GeneticProgrammingRegressor usage Source: https://github.com/alcides/geneticengine/blob/main/docs/source/sklearn.md Example of initializing and training a GeneticProgrammingRegressor for regression tasks. ```python from geml.regressors import GeneticProgrammingRegressor model = GeneticProgrammingRegressor() model.fit(X, y) ``` -------------------------------- ### GeneticProgrammingClassifier usage Source: https://github.com/alcides/geneticengine/blob/main/docs/source/sklearn.md Example of initializing and training a GeneticProgrammingClassifier for classification tasks. ```python from geml.classifiers import GeneticProgrammingClassifier model = GeneticProgrammingClassifier() model.fit(X, y) ``` -------------------------------- ### Dependency rules diagram Source: https://github.com/alcides/geneticengine/blob/main/docs/architecture/module-reorganization.md ASCII diagram showing allowed dependencies between modules. Core utilities are the base, with representations, algorithms, geml, and examples depending on them. ```text geneticengine.grammar ─┐ geneticengine.problems │ geneticengine.random ├── may depend on core utilities only geneticengine.solutions │ geneticengine.evaluation ─┘ geneticengine.representations ──> grammar, solutions, random geneticengine.algorithms ──> evaluation, problems, representations, random geml ──> geneticengine examples and tests ──> geneticengine and geml ``` -------------------------------- ### Grammar extraction output Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Example output of the grammar extraction, showing the generated grammar in a compact form. ```text Grammar Value(value: float)|ScalarVar(index: [0...2])|Add(right: Scalar, left: Scalar)|Mean(arr: Vectorial);Vectorial -> VectorialVar(index: [2...4])|CumulativeSum(arr: Vectorial)]>. ``` -------------------------------- ### Define a generic programming step with ParallelStep and SequenceStep Source: https://github.com/alcides/geneticengine/blob/main/docs/source/genetic_operators.md This example defines a genetic programming step that randomly selects individuals from the previous generation with elitism (5%), novelty (5%), and tournament selection followed by crossover and mutation (90%). The ParallelStep weights sum to 0.05 + 0.05 + 0.90 = 1.00, and the SequenceStep applies tournament selection, crossover, and mutation in sequence. Note that the population size is not specified here; the steps are agnostic and can be used inside other combinators. ```python default_generic_programming_step = ParallelStep([ ElitismStep(), NoveltyStep() SequenceStep( TournamentSelection(tournament_size=5), GenericCrossoverStep(probability=0.01), GenericMutationStep(probability=0.9), ) ], weights=[.05, .05, .90]) ) ``` -------------------------------- ### Run Genetic Programming with Levenshtein fitness on synthetic grammar Source: https://github.com/alcides/geneticengine/blob/main/docs/source/synthetic_problems.md Use a distance-based fitness (Levenshtein on stringified phenotypes) with GeneticProgramming to evolve candidates toward a target individual. Requires G and P_target from the minimal example; the budget is EvaluationBudget(100) and the search returns the best individual with its fitness. ```python from polyleven import levenshtein from geneticengine.algorithms.gp.gp import GeneticProgramming from geneticengine.evaluation.budget import EvaluationBudget from geneticengine.problems import SingleObjectiveProblem # Assume G and P_target are created as above def fitness_function(p): return levenshtein(str(p), str(P_target)) problem = SingleObjectiveProblem( fitness_function=fitness_function, minimize=True, target=0, ) r = NativeRandomSource(0) alg = GeneticProgramming( problem=problem, budget=EvaluationBudget(100), representation=TreeBasedRepresentation(G, decider=MaxDepthDecider(r, G, G.get_min_tree_depth() + 10)), population_size=10, random=r, ) ind = alg.search()[0] print(ind, ind.get_fitness(problem)) ``` -------------------------------- ### SimpleGP search output Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Example output from the SimpleGP search, showing the best fitness per generation and the best individual found. ```text BEST at 0 / 5 is 0 BEST at 1 / 5 is 0 BEST at 2 / 5 is 0 BEST at 3 / 5 is 0 BEST at 4 / 5 is 0 0 Mean(arr=VectorialVar(index=2)) ``` -------------------------------- ### Example grammar for expansion depthing Source: https://github.com/alcides/geneticengine/blob/main/docs/source/grammars.md A simple grammar with two production rules used to illustrate grammar-expansion depthing. A tree with a single node of value 0 has depth 2, while a tree with value 1 or 2 has depth 3. ```plaintext A :== 0 | B B :== 1 | 2 ``` -------------------------------- ### Proposed target directory layout for geneticengine Source: https://github.com/alcides/geneticengine/blob/main/docs/architecture/module-reorganization.md Proposed target directory layout for the geneticengine repository. It separates the core engine, optional geml integrations, and examples, and keeps existing top-level package names available during migration. ```text geneticengine/ __init__.py # small, documented public facade algorithms/ # complete search algorithms and GP steps evaluation/ # budgets, evaluators, trackers, recorders grammar/ # grammar extraction, decorators, metahandlers problems/ # Problem and fitness abstractions random/ # RandomSource implementations representations/ # genotype/phenotype representations and operators solutions/ # Individual and tree solution types exceptions.py geml/ # optional integrations built on geneticengine estimators/ # sklearn-compatible classifiers/regressors grammars/ # reusable domain grammars simplegp.py # compatibility facade during migration examples/ ... # runnable examples only benchmarks/ # benchmark definitions and benchmark runners tests/ docs/ ``` -------------------------------- ### Define dataset for vectorial GP regression Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Dataset with four samples: first two columns are scalars, next two are vectorial, last is the target value. Used for regression in the vectorial GP example. ```python dataset = [ [1, 5, [1, 2, 3], [1, 5, 6], 0], [2, 2, [3, 2, 3], [1, 8, 6], 1], [1, 6, [2, 2, 3], [1, 5, 9], 2], [2, 8, [3, 2, 3], [1, 6, 6], 3], ] ``` -------------------------------- ### Extract grammar from class-based representation Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Extracts a grammar from the defined classes using extract_grammar, starting from the Scalar type. Prints the grammar representation. ```python g = extract_grammar([Value, ScalarVar, VectorialVar, Mean, CumulativeSum], Scalar) print("Grammar: {}.".format(repr(g))) ``` -------------------------------- ### Define a simple expression language with Plus and Literal Source: https://github.com/alcides/geneticengine/blob/main/Readme.md Defines an abstract class MyExpr with an eval method, and two dataclasses Plus and Literal that implement it. This language supports the plus operator and integer literals, and GeneticEngine can automatically generate all possible expressions and guide the search towards a goal. ```python class MyExpr(ABC): "MyExpr is a non-terminal/abstract class." def eval(self): ... @dataclass class Plus(MyExpr): "E -> E + E" left: MyExpr right: MyExpr def eval(self): return self.left.eval() + self.right.eval() @dataclass class Literal(MyExpr): "E -> " value: int def eval(self): return self.value ``` -------------------------------- ### InjectInitialPopulationWrapper Source: https://github.com/alcides/geneticengine/blob/main/docs/source/genetic_operators.md Wrapper that injects pre-existing programs into the initial population, using a backup initializer for the remainder. ```APIDOC ## InjectInitialPopulationWrapper ### Description Allows passing a list of programs to include in the initial population. The remainder of the initial population will be selected via a backup initializer. ### Class `geneticengine.algorithms.gp.operators.initializers.InjectInitialPopulationWrapper` ### Usage Refer to the auto-generated API reference for constructor parameters and methods. ``` -------------------------------- ### StandardInitializer Source: https://github.com/alcides/geneticengine/blob/main/docs/source/genetic_operators.md Standard population initializer that works across all representations. ```APIDOC ## StandardInitializer ### Description Standard population initializer that works across all representations. ### Class `geneticengine.algorithms.gp.operators.initializers.StandardInitializer` ### Usage Refer to the auto-generated API reference for constructor parameters and methods. ``` -------------------------------- ### Run SimpleGP with grammar and fitness function Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Runs the Genetic Engine with the extracted grammar and placeholder fitness function. Configures a tree-based representation, population size of 10, and 50 maximum evaluations. ```python alg = SimpleGP( grammar=g, fitness_function=fitness_function, minimize=True, representation="treebased", population_size=10, max_evaluations=50) (b, bf) = alg.search() print(bf, b) ``` -------------------------------- ### Usage of metahandlers with annotations Source: https://github.com/alcides/geneticengine/blob/main/docs/source/metahandlers/index.md Uses IntRange, FloatRange, ListSizeBetween, VarRange, and StringSizeBetween to restrict base types. ```python @dataclass class Container(Parent): age : Annotated[int, IntRange[0, 200]] height : Annotated[float, FloatRange[0.10, 2.5]] children : Annotated[List[Container], ListSizeBetween[1,30]] var_name : Annotated[str, VarRange[["x", "y", "z"]]] dna : Annotated[str, StringSizeBetween(50, 80, ["a", "c", "t", "g"]] ``` -------------------------------- ### Generate random grammar and target individual with create_arbitrary_grammar Source: https://github.com/alcides/geneticengine/blob/main/docs/source/synthetic_problems.md Generate a random grammar with create_arbitrary_grammar, build a Grammar object with extract_grammar, and create a random target individual using TreeBasedRepresentation and MaxDepthDecider. The seed controls reproducibility; the returned nodes are dynamically created classes and root is the designated root non-terminal. ```python from geneticengine.grammar.grammar import extract_grammar from geneticengine.grammar.synthetic_grammar import create_arbitrary_grammar from geneticengine.random.sources import NativeRandomSource from geneticengine.representations.tree.initializations import MaxDepthDecider from geneticengine.representations.tree.treebased import TreeBasedRepresentation # 1) Generate a random grammar nodes, root = create_arbitrary_grammar( seed=0, non_terminals_count=3, recursive_non_terminals_count=2, productions_per_non_terminal=lambda rd: 2, non_terminals_per_production=lambda rd: 1, ) # 2) Build a Grammar object G = extract_grammar(nodes, root) # 3) Create a random target individual (phenotype) from this grammar r = NativeRandomSource(0) rep = TreeBasedRepresentation(G, decider=MaxDepthDecider(r, G, G.get_min_tree_depth())) G_target = rep.create_genotype(r, depth=8) P_target = rep.genotype_to_phenotype(G_target) print(P_target) ``` -------------------------------- ### Extract grammar with grammar-expansion depthing (expansion_depthing=True) Source: https://github.com/alcides/geneticengine/blob/main/docs/source/grammars.md Creates a grammar where depth increases each time a grammar production rule is expanded, as done in PonyGE2. Note that reading distance to terminal on actual objects may not reflect the whole tree depth. ```python grammar = extract_grammar([A, B], Root, expansion_depthing=True) ``` -------------------------------- ### Run genetic search with SimpleGP Source: https://github.com/alcides/geneticengine/blob/main/docs/source/index.md Extracts the grammar from the defined classes and runs a genetic search using SimpleGP. The search minimizes the fitness function with a population size of 200 and up to 10000 evaluations, printing the best fitness and individual. ```python grammar = extract_grammar([Literal, Plus], MyExpr) alg = SimpleGP( grammar=grammar, fitness_function=fitness_function, minimize=True, population_size=200, max_evaluations=10000, ) (b, bf) = alg.search() print(bf, b) ``` -------------------------------- ### Simple integer type in Python Source: https://github.com/alcides/geneticengine/blob/main/docs/source/metahandlers/index.md No description ```python class I: value: int ``` -------------------------------- ### Basic fitness function with compile placeholder Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Defines a placeholder compile function and a fitness function that applies the compiled program to each line of the dataset, computes predictions, and returns the mean squared error against the last column. The placeholder returns 0 for all instances, resulting in a constant fitness of 3.5. ```python def compile(p, line): pass # Not implemented yet def fitness_function(n: Scalar): regressor = lambda l: compile(n, l) y_pred = [regressor(line) for line in dataset] y = [line[-1] for line in dataset] r = mean_squared_error(y, y_pred) return r ``` -------------------------------- ### ParallelStep Source: https://github.com/alcides/geneticengine/blob/main/docs/source/genetic_operators.md Combinator step that applies multiple operations in parallel with specified weights. ```APIDOC ## ParallelStep ### Description Combinator step that applies multiple operations in parallel with specified weights. It is agnostic to population size and can be used inside other combinator steps. ### Class `geneticengine.algorithms.gp.operators.combinators.ParallelStep` ### Usage Refer to the auto-generated API reference for constructor parameters and methods. ``` -------------------------------- ### BNF integer representation Source: https://github.com/alcides/geneticengine/blob/main/docs/source/metahandlers/index.md No description ```BNF ::=

| -

::=

::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 ``` -------------------------------- ### GenericMutationStep Source: https://github.com/alcides/geneticengine/blob/main/docs/source/genetic_operators.md Generic mutation step that allows different representations to introduce their own custom mutators. ```APIDOC ## GenericMutationStep ### Description Generic mutation step. The operator parameter allows different representations to introduce their own custom mutators. ### Class `geneticengine.algorithms.gp.operators.mutation.GenericMutationStep` ### Usage Refer to the auto-generated API reference for constructor parameters and methods. ``` -------------------------------- ### Output of the genetic algorithm run Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Shows the final lines of the output from the genetic algorithm run, displaying the best fitness at generation 199 and the best fitness value. ```text BEST at 199 / 200 is 0.69 0.6882625764219203 ``` -------------------------------- ### Extract grammar with tree depthing (expansion_depthing=False) Source: https://github.com/alcides/geneticengine/blob/main/docs/source/grammars.md Creates a grammar where the maximum depth of an individual is the depth of its tree representation. This is the default mode for backwards compatibility with PonyGE2. ```python grammar = extract_grammar([A, B], Root, expansion_depthing=False) ``` -------------------------------- ### SequenceStep Source: https://github.com/alcides/geneticengine/blob/main/docs/source/genetic_operators.md Combinator step that applies a sequence of operations sequentially. ```APIDOC ## SequenceStep ### Description Combinator step that applies a sequence of operations sequentially. It is agnostic to population size and can be used inside other combinator steps. ### Class `geneticengine.algorithms.gp.operators.combinators.SequenceStep` ### Usage Refer to the auto-generated API reference for constructor parameters and methods. ``` -------------------------------- ### NoveltyStep Source: https://github.com/alcides/geneticengine/blob/main/docs/source/genetic_operators.md Novelty step that promotes novelty in the population. ```APIDOC ## NoveltyStep ### Description Novelty step that promotes novelty in the population. ### Class `geneticengine.algorithms.gp.operators.novelty.NoveltyStep` ### Usage Refer to the auto-generated API reference for constructor parameters and methods. ``` -------------------------------- ### LexicaseSelection Source: https://github.com/alcides/geneticengine/blob/main/docs/source/genetic_operators.md Generates a selection operator that uses Lexicase Selection. ```APIDOC ## LexicaseSelection ### Description Generates a selection operator that uses Lexicase Selection [^1]. ### Class `geneticengine.algorithms.gp.operators.selection.LexicaseSelection` ### Usage Refer to the auto-generated API reference for constructor parameters and methods. ### References [^1]: T. Helmuth, L. Spector and J. Matheson, "Solving Uncompromising Problems With Lexicase Selection," in IEEE Transactions on Evolutionary Computation, vol. 19, no. 5, pp. 630-643, Oct. 2015. ``` -------------------------------- ### Define grammar with dataclasses and abstract base class Source: https://github.com/alcides/geneticengine/blob/main/docs/source/index.md Defines the language of expressions supporting plus and integer literals. The abstract class MyExpr specifies the interface, while dataclasses Plus and Literal implement the grammar. Override __str__ for a more readable tree representation. ```python class MyExpr(ABC): def eval(self): ... @dataclass class Plus(MyExpr): left: MyExpr right: MyExpr def eval(self): return self.left.eval() + self.right.eval() @dataclass class Literal(MyExpr): value: int def eval(self): return self.value ``` -------------------------------- ### Reformatted grammar rules Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Reformatted version of the extracted grammar, showing the production rules in a typical GGGP format. ```text Scalar -> Value(float) Scalar -> ScalarVar([0...2]) Scalar -> Add(Scalar, Scalar) Scalar -> Mean(Vectorial) Vectorial -> VectorialVar([2...4]) Vectorial -> CumulativeSum(Vectorial) ``` -------------------------------- ### GenericCrossoverStep Source: https://github.com/alcides/geneticengine/blob/main/docs/source/genetic_operators.md Generic crossover step that allows different representations to introduce their own custom crossover operators. ```APIDOC ## GenericCrossoverStep ### Description Generic crossover step. The operator parameter allows different representations to introduce their own custom crossover operators. ### Class `geneticengine.algorithms.gp.operators.crossover.GenericCrossoverStep` ### Usage Refer to the auto-generated API reference for constructor parameters and methods. ``` -------------------------------- ### Define terminal nodes with dataclasses and IntRange Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Defines terminal nodes for scalar literals, scalar features, and vectorial features. Uses dataclasses for automatic constructors and Annotated with IntRange to restrict random index generation. ```python @dataclass class Value(Scalar): value: float @dataclass class ScalarVar(Scalar): index: Annotated[int, IntRange(0, 1)] @dataclass class VectorialVar(Vectorial): index: Annotated[int, IntRange(2, 3)] ``` -------------------------------- ### Alternative fitness function using translate and eval Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Provides an alternative approach where the tree is translated to a Python code string and then evaluated using eval to create a callable regressor. The translate function handles Value, ScalarVar, VectorialVar, Add, Mean, and CumulativeSum nodes, and raises NotImplementedError for others. ```python def translate(p): if isinstance(p, Value): return str(p.value) elif isinstance(p, ScalarVar) or isinstance(p, VectorialVar): return "line[{}]".format(p.index) elif isinstance(p, Add): return "({} + {})".format(translate(p.left), translate(p.right)) elif isinstance(p, Mean): return "np.mean({})".format(translate(p.arr)) elif isinstance(p, CumulativeSum): return "np.cumsum({})".format(translate(p.arr)) else: raise NotImplementedError(str(p)) def fitness_function_alternative(n: Scalar): code = "lambda line: {}".format(translate(n)) regressor = eval(code) y_pred = [regressor(line) for line in dataset] y = [line[-1] for line in dataset] r = mean_squared_error(y, y_pred) return r ``` -------------------------------- ### TournamentSelection Source: https://github.com/alcides/geneticengine/blob/main/docs/source/genetic_operators.md Selection operator that uses tournament selection. ```APIDOC ## TournamentSelection ### Description Selection operator that uses tournament selection. ### Class `geneticengine.algorithms.gp.operators.selection.TournamentSelection` ### Usage Refer to the auto-generated API reference for constructor parameters and methods. ``` -------------------------------- ### Define placeholder fitness function Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md A placeholder fitness function that assigns the same fitness (0) to all individuals, turning the problem into a random search. Useful for debugging the representation. ```python def fitness_function(n): return 0 ``` -------------------------------- ### Define weighted grammar classes with @weight decorator Source: https://github.com/alcides/geneticengine/blob/main/docs/source/grammars.md Assigns probabilities to grammar productions using the @weight decorator. OptionA is selected with 10% probability and OptionB with 90%. The classes inherit from a base class R, which is not defined in the snippet. ```python class Root(ABC): pass @weight(0.1) class OptionA(R): " This option will be selected with 10% of probability " pass @weight(0.9) class OptionB(R): " This option will be selected with 90% of probability " pass ``` -------------------------------- ### Proper compile function with type-based recursion Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Implements a recursive compile function that pattern matches on node types (Value, ScalarVar, VectorialVar, Add, Mean, CumulativeSum) and computes the value for a given dataset line. Uses numpy functions where needed and raises NotImplementedError for unknown types. ```python def compile(p, line): if isinstance(p, Value): return p.value elif isinstance(p, ScalarVar) or isinstance(p, VectorialVar): return line[p.index] elif isinstance(p, Add): return compile(p.left, line) + compile(p.right, line) elif isinstance(p, Mean): return np.mean(compile(p.arr, line)) elif isinstance(p, CumulativeSum): return np.cumsum(compile(p.arr, line)) else: raise NotImplementedError(str(p)) ``` -------------------------------- ### Define abstract base classes for scalar and vectorial types Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Defines abstract base classes for scalar and vectorial types. These classes are not instantiable and serve as type markers for the genetic representation. ```python from abc import ABC class Scalar(ABC): pass class Vectorial(ABC): pass ``` -------------------------------- ### ElitismStep Source: https://github.com/alcides/geneticengine/blob/main/docs/source/genetic_operators.md Elitism step that preserves the best individuals in the population. ```APIDOC ## ElitismStep ### Description Elitism step that preserves the best individuals in the population. ### Class `geneticengine.algorithms.gp.operators.elitism.ElitismStep` ### Usage Refer to the auto-generated API reference for constructor parameters and methods. ``` -------------------------------- ### ExclusiveParallelStep Source: https://github.com/alcides/geneticengine/blob/main/docs/source/genetic_operators.md Combinator step that applies multiple operations in parallel exclusively. ```APIDOC ## ExclusiveParallelStep ### Description Combinator step that applies multiple operations in parallel exclusively. It is agnostic to population size and can be used inside other combinator steps. ### Class `geneticengine.algorithms.gp.operators.combinators.ExclusiveParallelStep` ### Usage Refer to the auto-generated API reference for constructor parameters and methods. ``` -------------------------------- ### Define Mean non-terminal for vectorial to scalar conversion Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Defines a non-terminal that converts a vectorial expression into a scalar one by taking the mean. ```python @dataclass class Mean(Scalar): arr: Vectorial ``` -------------------------------- ### Define CumulativeSum non-terminal for vectorial operations Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Defines a non-terminal that takes a vectorial expression and returns another vectorial expression, representing a cumulative sum. ```python @dataclass class CumulativeSum(Vectorial): arr: Vectorial ``` -------------------------------- ### Define fitness function for expression evaluation Source: https://github.com/alcides/geneticengine/blob/main/docs/source/index.md Fitness function that measures how close the expression's evaluation is to 42. Used by the search algorithm to minimize (or maximize) the given function. ```python def fitness_function(e:MyExpr) -> int return abs(42 - e.eval()) ``` -------------------------------- ### Define Add non-terminal for scalar addition Source: https://github.com/alcides/geneticengine/blob/main/docs/source/tutorial.md Defines a non-terminal node representing the sum of two scalar expressions. The operands can be any scalar terminal or non-terminal. ```python @dataclass class Add(Scalar): right: Scalar left: Scalar ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.