### Install dependencies from requirements.txt Source: https://geneticengine.readthedocs.io/en/latest/_sources/tutorial.md.txt Installs the dependencies listed in requirements.txt as part of the tutorial setup. ```bash python -m pip install -r requirements.txt ``` -------------------------------- ### Run all examples with uv Source: https://geneticengine.readthedocs.io/en/latest/_sources/index.md.txt Runs all examples using uv to manage Python dependencies. Requires uv installed. ```bash ./run_examples.sh ``` -------------------------------- ### Run examples with Codon enabled Source: https://geneticengine.readthedocs.io/en/latest/_sources/index.md.txt Runs all examples with Codon enabled. Requires Codon installed; the script uses codon run -release when feasible and falls back to uv run python for unsupported third-party packages. ```bash CODON=1 ./run_examples.sh ``` -------------------------------- ### SimpleGP output example Source: https://geneticengine.readthedocs.io/en/latest/_sources/tutorial.md.txt Example output from the SimpleGP run, showing 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)) ``` -------------------------------- ### Initialize GengyList Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/solutions/tree/index.html Python built-in docstring example for GengyList, which extends list.Generic[T]. Initializes list. ```python class GengyList(list, Generic[T]): """Built-in mutable sequence.""" ``` -------------------------------- ### Grammar output example Source: https://geneticengine.readthedocs.io/en/latest/_sources/tutorial.md.txt Example output of the grammar extraction, showing the generated productions. ```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)]>. ``` -------------------------------- ### Example grammar with alternatives Source: https://geneticengine.readthedocs.io/en/latest/grammars.html Shows a simple grammar with two production rules. A can expand to 0 or B, and B can expand to 1 or 2. This illustrates how expansion depth is calculated. ```python A :== 0 | B B :== 1 | 2 ``` -------------------------------- ### Minimal example: create arbitrary grammar and target individual Source: https://geneticengine.readthedocs.io/en/latest/_sources/synthetic_problems.md.txt Generates a random grammar with create_arbitrary_grammar, builds a Grammar object, and creates a random target individual (phenotype) using TreeBasedRepresentation and MaxDepthDecider. ```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) ``` -------------------------------- ### Dependent metahandler example Source: https://geneticengine.readthedocs.io/en/latest/_sources/metahandlers/index.md.txt Shows how to use the Dependent metahandler to make a field depend on a previously generated field of the same class. ```python @dataclass class SimplePair: a: Annotated[int, IntRange(0, 3)] b: Annotated[int, Dependent("a", lambda a: IntRange(a, 4))] ``` -------------------------------- ### Grammar expansion example for depthing Source: https://geneticengine.readthedocs.io/en/latest/_sources/grammars.md.txt Example grammar used to illustrate grammar-expansion depthing. A tree with a single node 0 has depth 2 (A -> 0), while a tree with a single node 1 or 2 has depth 3 (A -> B -> 1 or 2). ```text A :== 0 | B B :== 1 | 2 ``` -------------------------------- ### Structural subtyping example Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/solutions/index.html Shows a class that structurally matches the Proto protocol and a function that accepts Proto. The call func(C()) passes static type checking. ```python class C: def meth(self) -> int: return 0 def func(x: Proto) -> int: return x.meth() func(C()) # Passes static type check ``` -------------------------------- ### py:method Grammar.get_weights Source: https://geneticengine.readthedocs.io/en/latest/_sources/autoapi/geneticengine/grammar/index.rst.txt Gets grammar weights. ```APIDOC ### py:method Grammar.get_weights ### Description Gets the current weights of the grammar. ### Method Signature ```python get_weights() ``` ### Returns - **list[float]** - The grammar weights. ``` -------------------------------- ### Usage of Protocol in a function Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/solutions/tree/index.html Example demonstrating how to use a Protocol class with structural subtyping. Includes a class C that satisfies the protocol and a function that accepts the protocol type. ```python class C: def meth(self) -> int: return 0 def func(x: Proto) -> int: return x.meth() func(C()) # Passes static type check ``` -------------------------------- ### Definition of TreeNode Protocol Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/solutions/tree/index.html Shown in the documentation for the TreeNode class, this example illustrates how to define a Protocol class with a method. Copy the syntax for creating custom protocols. ```python class Proto(Protocol): def meth(self) -> int: ... ``` -------------------------------- ### Define a custom genetic programming step with ParallelStep and SequenceStep Source: https://geneticengine.readthedocs.io/en/latest/_sources/genetic_operators.md.txt Shows how to combine elitism, novelty, selection, crossover, and mutation into a single step using ParallelStep and SequenceStep. The weights determine the proportion of each operation in the new generation. Note the example includes a trailing parenthesis that appears to be a typo in the source. ```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]) ) ``` -------------------------------- ### PonyGE2Grammar.to_geneticengine() Source: https://geneticengine.readthedocs.io/en/latest/_sources/autoapi/geneticengine/grammar/ponyge2/index.rst.txt Converts the parsed PonyGE2 grammar into the GeneticEngine node classes and starting symbol. ```APIDOC ## PonyGE2Grammar.to_geneticengine() ### Description Returns the generated node classes and starting symbol from the parsed PonyGE2 grammar. ### Returns - **tuple** - A tuple containing the generated node classes and the starting symbol. ### Example ```python from geneticengine.grammar.ponyge2 import parse_ponyge2_grammar grammar = parse_ponyge2_grammar(" ::= \n ::= x | y") nodes, start = grammar.to_geneticengine() ``` ``` -------------------------------- ### Generic Protocol class example Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/solutions/tree/index.html Shows how to define a generic Protocol class using type parameter T. Part of the TreeNode documentation. ```python class GenProto[T](Protocol): def meth(self) -> T: ... ``` -------------------------------- ### parse_ponyge2_grammar(source, *, ge_constants = None) Source: https://geneticengine.readthedocs.io/en/latest/_sources/autoapi/geneticengine/grammar/ponyge2/index.rst.txt Parses PonyGE2 BNF text or a grammar file into a GeneticEngine grammar structure. The first rule is the starting symbol, and terminals are converted to fixed string fields or integer ranges. ```APIDOC ## parse_ponyge2_grammar(source, *, ge_constants = None) ### Description Parses PonyGE2 BNF text or a grammar file. The first rule is the starting symbol. Ordinary terminals become fixed `VarRange` string fields. `GE_RANGE:n` becomes an integer field in `range(n)`; named ranges can be supplied through `ge_constants`. ### Parameters - **source** (str) - Required - The PonyGE2 BNF grammar text or path to a grammar file. - **ge_constants** (dict, optional) - Optional - Named ranges for `GE_RANGE` specifications. ### Returns - **PonyGE2Grammar** - The generated GeneticEngine structure for the PonyGE2 grammar. ### Example ```python from geneticengine.grammar.ponyge2 import parse_ponyge2_grammar grammar = parse_ponyge2_grammar(" ::= \n ::= x | y") ``` ``` -------------------------------- ### load_ponyge2_grammar Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/grammar/ponyge2/index.html Parses a PonyGE2 grammar file into a PonyGE2Grammar object. The first rule is the starting symbol. Ordinary terminals become fixed VarRange string fields, and GE_RANGE:n becomes an integer field in range(n). Named ranges can be supplied through ge_constants. ```APIDOC ## load_ponyge2_grammar(path, *, ge_constants=None) ### Description Parses a PonyGE2 grammar file. The first rule is the starting symbol. Ordinary terminals become fixed `VarRange` string fields. `GE_RANGE:n` becomes an integer field in `range(n)`; named ranges can be supplied through `ge_constants`. ### Parameters - **path** (str | pathlib.Path) - Required - Path to the PonyGE2 grammar file. - **ge_constants** (Mapping[str, int] | None) - Optional - Named ranges for `GE_RANGE` specifications. ### Returns - **PonyGE2Grammar** - The generated GeneticEngine structure for the PonyGE2 grammar. ### Example ```python from geneticengine.grammar.ponyge2 import load_ponyge2_grammar grammar = load_ponyge2_grammar("grammar.bnf") ``` ``` -------------------------------- ### Get number of enum members Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/grammar/metahandlers/lists/index.html Returns the number of members in the enum. The output is 3 for the example Color enum. ```python >>> len(Color) 3 ``` -------------------------------- ### StandardInitializer.initialize Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/algorithms/gp/operators/initializers/index.html Initializes a population where all individuals are created with full trees (maximum depth in all branches). ```APIDOC ## StandardInitializer.initialize ### Description All individuals are created with full trees (maximum depth in all branches). ### Method initialize ### Signature initialize(problem, representation, random, target_size, **kwargs) ### Parameters - **problem** (geneticengine.problems.Problem) - Required - The problem to solve. - **representation** (geneticengine.representations.api.Representation) - Required - The representation used for individuals. - **random** (geneticengine.random.sources.RandomSource) - Required - The random source for stochastic operations. - **target_size** (int) - Required - The target population size. - **kwargs** - Optional - Additional keyword arguments. ### Return Type Iterator[geneticengine.solutions.individual.PhenotypicIndividual] ``` -------------------------------- ### Initializers: StandardInitializer and InjectInitialPopulationWrapper Source: https://geneticengine.readthedocs.io/en/latest/_sources/genetic_operators.md.txt Population initializers for genetic algorithms. StandardInitializer creates an initial population, and InjectInitialPopulationWrapper allows injecting pre-existing programs into the initial population, with the remainder generated by a backup initializer. ```APIDOC ## StandardInitializer ### Description Standard population initializer that works across all representations. ### Class `geneticengine.algorithms.gp.operators.initializers.StandardInitializer` ## InjectInitialPopulationWrapper ### Description Allows passing a list of programs to include in the initial population. The remainder is selected via a backup initializer. ### Class `geneticengine.algorithms.gp.operators.initializers.InjectInitialPopulationWrapper` ### Usage When creating the wrapper, provide the list of programs and a backup initializer. ``` -------------------------------- ### load_ponyge2_grammar(path, *, ge_constants = None) Source: https://geneticengine.readthedocs.io/en/latest/_sources/autoapi/geneticengine/grammar/ponyge2/index.rst.txt Loads a PonyGE2 grammar from a file and parses it into a GeneticEngine grammar structure. ```APIDOC ## load_ponyge2_grammar(path, *, ge_constants = None) ### Description Parses a PonyGE2 grammar file into a GeneticEngine grammar structure. ### Parameters - **path** (str) - Required - Path to the PonyGE2 grammar file. - **ge_constants** (dict, optional) - Optional - Named ranges for `GE_RANGE` specifications. ### Returns - **PonyGE2Grammar** - The generated GeneticEngine structure for the PonyGE2 grammar. ### Example ```python from geneticengine.grammar.ponyge2 import load_ponyge2_grammar grammar = load_ponyge2_grammar("grammar.bnf") ``` ``` -------------------------------- ### iterate_individuals Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/algorithms/enumerative/index.html Iterates over all possible individuals from a grammar starting from a given symbol. ```APIDOC ## iterate_individuals ### Description Iterates over all possible individuals from a grammar starting from a given symbol. ### Parameters - **grammar** (geneticengine.grammar.grammar.Grammar) - Required - The grammar to iterate. - **starting_symbol** (type) - Required - The starting symbol type. ### Returns Generator[geneticengine.solutions.individual.ConcreteIndividual, Any, Any] ``` -------------------------------- ### iterate_grammar Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/algorithms/enumerative/index.html Iterates over all possible representations from a grammar starting from a given symbol. ```APIDOC ## iterate_grammar ### Description Iterates over all possible representations from a grammar starting from a given symbol. ### Parameters - **grammar** (geneticengine.grammar.grammar.Grammar) - Required - The grammar to iterate. - **starting_symbol** (type) - Required - The starting symbol type. - **generator_for_recursive** (Optional[Any]) - Optional - Generator for recursive cases. - **dependent_values** (Optional[dict[str, Any]]) - Optional - Dependent values. ### Returns A generator of representations. ``` -------------------------------- ### HalfAndHalfInitializer.initialize Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/algorithms/gp/operators/initializers/index.html Initializes a population by combining two initializers, one for each half of the population. ```APIDOC ## HalfAndHalfInitializer.initialize ### Description Combines two initializers, one for each half of the population. ### Method initialize ### Signature initialize(problem, representation, random, target_size, **kwargs) ### Parameters - **problem** (geneticengine.problems.Problem) - Required - The problem to solve. - **representation** (geneticengine.representations.api.Representation) - Required - The representation used for individuals. - **random** (geneticengine.random.sources.RandomSource) - Required - The random source for stochastic operations. - **target_size** (int) - Required - The target population size. - **kwargs** - Optional - Additional keyword arguments. ### Return Type Iterator[geneticengine.solutions.individual.PhenotypicIndividual] ``` -------------------------------- ### frange Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/algorithms/enumerative/index.html Generates a range of floating-point numbers from start to stop with a given step. ```APIDOC ## frange ### Description Generates a range of floating-point numbers from start to stop with a given step. ### Parameters - **start** (float) - Required - The starting value. - **stop** (float) - Required - The stopping value (exclusive). - **step** (float) - Required - The increment between values. ### Returns A generator of floating-point numbers. ``` -------------------------------- ### Grammar-expansion depthing with expansion_depthing=True Source: https://geneticengine.readthedocs.io/en/latest/_sources/grammars.md.txt Creates a grammar using grammar-expansion depthing, as in PonyGE2. Depth increases each time a grammar production rule is expanded. ```python grammar = extract_grammar([A, B], Root, expansion_depthing=True) ``` -------------------------------- ### time_for_initialization(budget) Source: https://geneticengine.readthedocs.io/en/latest/_sources/autoapi/geneticengine/algorithms/gp/adaptive/index.rst.txt Determines if there is time for initialization based on the given budget. This function is part of the adaptive module. ```APIDOC ## Function: time_for_initialization(budget) ### Description Checks whether there is time for initialization given the budget. ### Parameters - **budget** (type not specified) - Required - The budget for initialization. ### Returns - Boolean indicating if there is time for initialization. ``` -------------------------------- ### Population.__init__ Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/algorithms/gp/population/index.html Constructor for the Population class. Initializes a population with an iterator of individuals, a progress tracker, and an optional generation number. ```APIDOC ## Population.__init__ ### Description Constructor for the Population class. Initializes a population with an iterator of individuals, a progress tracker, and an optional generation number. ### Method `__init__(it, tracker, generation=-1)` ### Parameters - **it** (Iterator[PhenotypicIndividual]) - Required - Iterator of individuals. - **tracker** (ProgressTracker) - Required - Progress tracker for the algorithm. - **generation** (int) - Optional - Generation number, defaults to -1. ### Returns None ``` -------------------------------- ### Grammar Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/representations/stackgggp/index.html The Grammar class represents a grammar with starting symbol, alternatives, and methods for validation, registration, and analysis. ```APIDOC ## Grammar ### Description The Grammar class represents a grammar with a starting symbol, alternatives, and methods for validation, registration, and analysis. ### Constructor `Grammar(starting_symbol, considered_subtypes=None, expansion_depthing=False)` #### Parameters - **starting_symbol** (type) - Required - The starting symbol of the grammar. - **considered_subtypes** (list[type] | None) - Optional - List of considered subtypes. - **expansion_depthing** (bool) - Optional - Whether expansion depthing is enabled. ### Attributes - **starting_symbol** (type) - The starting symbol. - **alternatives** (dict[type, list[type]]) - Mapping from nonterminal to list of alternatives. - **distanceToTerminal** (dict[Any, int]) - Distance to terminal for each symbol. - **all_nodes** (set[type]) - Set of all node types. - **recursive_prods** (set[type]) - Set of recursive production types. - **terminals** (set[type]) - Set of terminal types. - **non_terminals** (set[type]) - Set of non-terminal types. - **abstract_dist_to_t** (dict[type, dict[type, int]]) - Abstract distance to terminal. - **considered_subtypes** (list) - Default: [] - **expansion_depthing** (bool) - Default: False ### Methods #### validate() Validates the grammar. #### register_alternative(nonterminal, nodetype) Registers a production A->B. Call multiple times with same A to register many possible alternatives. ##### Parameters - **nonterminal** (type) - Required - The nonterminal symbol. - **nodetype** (type) - Required - The node type. #### register_type(ty) Registers a type. ##### Parameters - **ty** (type) - Required - The type to register. #### __repr__() Returns a string representation of the grammar. #### get_all_symbols() Returns all symbols in the current grammar, including terminals. ##### Return type - tuple[set[type], set[type], set[type]] #### collect_types(ty) Collects types. ##### Parameters - **ty** (type) - Required - The type to collect. #### get_all_mentioned_symbols() Returns all mentioned symbols. ##### Return type - set[type] #### get_distance_to_terminal(ty) Returns the current distance to terminal of a given type. ##### Parameters - **ty** (type) - Required - The type. ##### Return type - int #### get_min_tree_depth() Returns the minimum depth a tree must have. #### get_max_node_depth() Returns the maximum minimum depth a node can have. #### preprocess() Computes distanceToTerminal via a fixpoint algorithm. ##### Return type - None #### get_weights() Returns weights. #### update_weights(learning_rate, extra_weights) Updates weights. #### is_reachable(t1, t2) Checks if t2 is reachable from t1. ##### Parameters - **t1** (Type) - Required - The source type. - **t2** (Type) - Required - The target type. ##### Return type - bool #### reaches_leaf(t, visited=None) Returns whether a given type reaches a leaf type, or None if it causes a loop. Loops should be ignored only if there is an alternative path. ##### Parameters - **t** (Type) - Required - The type to check. - **visited** (set | None) - Optional - Set of visited types. ##### Return type - bool | None #### usable_grammar() Returns a subset of the grammar that is actually reachable. ##### Return type - Grammar #### get_grammar_properties_summary() Returns a summary of grammar properties: a depth range (minimum depth and maximum depth), the number of Non-Terminal symbols, and production statistics including frequency of productions, number of recursive productions, per non-terminal alternatives, total productions, average productions per non-terminal, and average non-terminals per production. ##### Return type - GrammarSummary ``` -------------------------------- ### StackBasedGGGPRepresentation Source: https://geneticengine.readthedocs.io/en/latest/representations.html Represents the Stack-based Grammatical Evolution representation. It uses a list of integers to guide the generation of trees in the phenotype. ```APIDOC ## StackBasedGGGPRepresentation ### Description Represents the Stack-based Grammatical Evolution representation. It uses a list of integers to guide the generation of trees in the phenotype. ### Constructor `StackBasedGGGPRepresentation(grammar, gene_length=1024, failures_limit=100)` ### Parameters - **grammar** (geneticengine.grammar.grammar.Grammar) - Required - The grammar to use. - **gene_length** (int) - Optional - The length of the gene. Default is 1024. - **failures_limit** (int) - Optional - The limit of failures. Default is 100. ``` -------------------------------- ### GenericWrapper.get() Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/generic_utils/index.html The get method of the GenericWrapper class returns the wrapped value of type C. It is a method that can be called on an instance of GenericWrapper. ```APIDOC ## GenericWrapper.get() ### Description Returns the value of type C from the GenericWrapper instance. ### Method get() ### Parameters None ### Return Type C ### Example ```python wrapper = GenericWrapper(some_value) result = wrapper.get() ``` ``` -------------------------------- ### DynamicSGEDecider.choose_production_alternatives Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/representations/grammatical_evolution/dynamic_structured_ge/index.html Chooses a production alternative for a given type. ```APIDOC ## DynamicSGEDecider.choose_production_alternatives ### Description Chooses a production alternative for a given type. ### Method `choose_production_alternatives(ty, alternatives, ctx)` ### Parameters - **ty** (type) - Required - The type to choose for. - **alternatives** (list[type]) - Required - The list of alternative types. - **ctx** (geneticengine.solutions.tree.LocalSynthesisContext) - Required - The local synthesis context. ### Returns - type - The chosen alternative type. ``` -------------------------------- ### random_node Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/representations/tree/treebased/index.html Generates a random node in the tree representation using the given random source, grammar, starting symbol, and decider. ```APIDOC ## random_node(random, grammar, starting_symbol, decider) ### Description Generates a random node in the tree representation using the given random source, grammar, starting symbol, and decider. ### Parameters - **random** (geneticengine.random.sources.RandomSource) - Required - The random source used for generation. - **grammar** (geneticengine.grammar.grammar.Grammar) - Required - The grammar defining valid tree structures. - **starting_symbol** (type[Any]) - Required - The starting symbol for tree generation. - **decider** (geneticengine.representations.tree.initializations.SynthesisDecider) - Required - The decider used for synthesis decisions. ### Returns No explicit return type documented. ``` -------------------------------- ### Define an Enum with three members Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/grammar/metahandlers/lists/index.html Defines an enumeration with three members. This is the example used in the documentation for the VariationType class, which is an enum.Enum subclass. ```python >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 ``` -------------------------------- ### get_arguments(n) Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/grammar/utils/index.html Returns list of (argname, argtype) for a production node. ```APIDOC ## get_arguments(n) ### Description Returns list of (argname, argtype) for a production node. ### Parameters - **n** (Any) - Required - production ### Returns - list[tuple[str, type]] ``` -------------------------------- ### ParameterlessPopulationInitializer.initialize(problem, representation, random, target_size, **kwargs) Source: https://geneticengine.readthedocs.io/en/latest/_sources/autoapi/geneticengine/algorithms/gp/adaptive/index.rst.txt Initializes a population without requiring explicit population size parameters. This method is part of the ParameterlessPopulationInitializer class. ```APIDOC ## Method: initialize(problem, representation, random, target_size, **kwargs) ### Description Initializes a population for the given problem and representation. ### Parameters - **problem** (type not specified) - Required - The problem to solve. - **representation** (type not specified) - Required - The representation of individuals. - **random** (type not specified) - Required - Random number generator. - **target_size** (type not specified) - Required - The target population size. - **kwargs** - Optional - Additional keyword arguments. ### Returns - Initialized population. ``` -------------------------------- ### Extract grammar with extract_grammar Source: https://geneticengine.readthedocs.io/en/latest/_sources/tutorial.md.txt Extracts the grammar from the defined classes using extract_grammar, with Scalar as the starting type. Prints the grammar representation. ```python g = extract_grammar([Value, ScalarVar, VectorialVar, Mean, CumulativeSum], Scalar) print("Grammar: {}.".format(repr(g))) ``` -------------------------------- ### py:function extract_grammar Source: https://geneticengine.readthedocs.io/en/latest/_sources/autoapi/geneticengine/grammar/index.rst.txt The extract_grammar function constructs a complete Grammar from a set of nodes and a starting symbol for use in search algorithms. ```APIDOC ## py:function extract_grammar ### Description This function takes all productions of the grammar (nodes) and a starting symbol, and constructs a complete grammar that can be used for search algorithms such as Genetic Programming and Hill Climbing. ### Signature ```python extract_grammar(considered_subtypes, starting_symbol, expansion_depthing=False) ``` ### Parameters - **nodes** (list) - Required - A list of objects representing tree nodes. Make sure that any node can be produced by the starting symbol. - **starting_symbol** (object) - Required - The starting symbol of each tree. Ensures every generated tree by the returned grammar starts with this symbol. Make sure the starting symbol can produce any object of nodes. - **considered_subtypes** (type) - Required - The considered subtypes parameter. - **expansion_depthing** (bool) - Optional - Default is False. ### Returns - **Grammar** - The constructed grammar. ``` -------------------------------- ### EvaluateStep.iterate Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/algorithms/gp/operators/evaluation/index.html Documentation for the EvaluateStep class and its iterate method. ```APIDOC ## EvaluateStep.iterate ### Description Evaluates the complete population. ### Method iterate ### Parameters - **problem** (geneticengine.problems.Problem) - Required - The problem to evaluate. - **evaluator** (geneticengine.evaluation.Evaluator) - Required - The evaluator used to evaluate individuals. - **representation** (geneticengine.representations.api.Representation) - Required - The representation of the individuals. - **random** (geneticengine.random.sources.RandomSource) - Required - The random source. - **population** (Iterator[geneticengine.solutions.individual.PhenotypicIndividual]) - Required - The population to evaluate. - **target_size** (int) - Required - The target size of the population. - **generation** (int) - Required - The current generation number. ### Returns - Iterator[geneticengine.solutions.individual.PhenotypicIndividual] - The evaluated population. ``` -------------------------------- ### is_metahandler(ty) Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/grammar/utils/index.html Returns if type is a metahandler. AnnotatedType[int, IntRange(3,10)] is an example of a Metahandler. Verification is done using the __metadata__, which is the first argument of Annotated. ```APIDOC ## is_metahandler(ty) ### Description Returns if type is a metahandler. AnnotatedType[int, IntRange(3,10)] is an example of a Metahandler. Verification is done using the __metadata__, which is the first argument of Annotated. ### Parameters - **ty** (type) - Required ### Returns - bool ``` -------------------------------- ### GenericPopulationInitializer.initialize Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/representations/common/index.html Initializes a population for any representation. This method is part of the GenericPopulationInitializer class and is used to generate an initial population of individuals for a given problem and representation. ```APIDOC ## GenericPopulationInitializer.initialize ### Description Initializes a population for any representation. This method is part of the GenericPopulationInitializer class and is used to generate an initial population of individuals for a given problem and representation. ### Method initialize ### Signature initialize(problem, representation, random, target_size) ### Parameters - **problem** (geneticengine.problems.Problem) - Required - The problem to solve. - **representation** (geneticengine.representations.api.Representation) - Required - The representation to use. - **random** (geneticengine.random.sources.RandomSource) - Required - The random source for generation. - **target_size** (int) - Required - The desired population size. ### Return Type Iterator[geneticengine.solutions.individual.PhenotypicIndividual] ### Description of Return An iterator of PhenotypicIndividual objects representing the initial population. ``` -------------------------------- ### Run genetic search with SimpleGP Source: https://geneticengine.readthedocs.io/en/latest/_sources/index.md.txt Sets up and runs a genetic programming search using SimpleGP. Extracts the grammar from the defined classes, configures the algorithm with the fitness function and parameters, then prints the best fitness and best 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) ``` -------------------------------- ### DynamicSGEDecider.choose_options Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/representations/grammatical_evolution/dynamic_structured_ge/index.html Chooses an option from a list of alternatives. ```APIDOC ## DynamicSGEDecider.choose_options ### Description Chooses an option from a list of alternatives. ### Method `choose_options(alternatives, ctx)` ### Parameters - **alternatives** (list[T]) - Required - The list of alternatives. - **ctx** (geneticengine.solutions.tree.LocalSynthesisContext) - Required - The local synthesis context. ### Returns - T - The chosen option. ``` -------------------------------- ### Define fitness function for expression evaluation Source: https://geneticengine.readthedocs.io/en/latest/_sources/index.md.txt Fitness function that evaluates an expression and returns the absolute difference from 42. Used by GeneticEngine to guide the search toward minimizing this value. ```python def fitness_function(e:MyExpr) -> int return abs(42 - e.eval()) ``` -------------------------------- ### geneticengine.solutions.individual Source: https://geneticengine.readthedocs.io/en/latest/autoapi/geneticengine/solutions/individual/index.html Documentation for the geneticengine.solutions.individual module, covering the Individual, ConcreteIndividual, PhenotypicIndividual classes and the IndividualNotEvaluatedException exception. ```APIDOC ## Class: Individual ### Description Abstract base class for individuals in genetic algorithms. Provides a standard way to create an ABC using inheritance. ### Constructor `Individual(_metadata=None)` #### Parameters - **metadata** (dict[str, Any] | None) - Optional metadata associated with the individual. ### Methods #### get_phenotype() - **Return type**: P - **Description**: Abstract method to obtain the phenotype of the individual. #### has_fitness(problem) - **Parameters**: - **problem** (geneticengine.problems.Problem) - The problem for which fitness is checked. - **Return type**: bool - **Description**: Checks whether the individual has a fitness value for the given problem. #### set_fitness(problem, fitness) - **Parameters**: - **problem** (geneticengine.problems.Problem) - The problem for which fitness is set. - **fitness** (geneticengine.problems.Fitness) - The fitness value to set. - **Description**: Sets the fitness value for the given problem. #### get_fitness(problem=None) - **Parameters**: - **problem** (geneticengine.problems.Problem | None) - The problem for which fitness is retrieved. If None, may return a default or raise an exception. - **Return type**: geneticengine.problems.Fitness - **Description**: Retrieves the fitness value for the given problem. ### Attributes - **fitness_store**: weakref.WeakKeyDictionary[geneticengine.problems.Problem, geneticengine.problems.Fitness] - Stores fitness values per problem. - **metadata**: dict[str, Any] - Metadata associated with the individual. ## Class: ConcreteIndividual ### Description Concrete implementation of an individual that directly holds an instance of the phenotype. ### Constructor `ConcreteIndividual(instance, metadata=None)` #### Parameters - **instance** (P) - The phenotype instance. - **metadata** (dict[str, Any] | None) - Optional metadata. ### Methods #### get_phenotype() - **Return type**: P - **Description**: Returns the phenotype instance. ### Attributes - **instance**: P - The phenotype instance. ## Class: PhenotypicIndividual ### Description Individual that derives its phenotype from a genotype using a representation. ### Constructor `PhenotypicIndividual(genotype, representation, metadata=None)` #### Parameters - **genotype** (G) - The genotype. - **representation** (geneticengine.representations.api.Representation[G, P]) - The representation used to convert genotype to phenotype. - **metadata** (dict[str, Any] | None) - Optional metadata. ### Methods #### get_phenotype() - **Return type**: P - **Description**: Computes and returns the phenotype from the genotype using the representation. #### __str__() - **Return type**: str - **Description**: Returns a string representation of the individual. ### Attributes - **genotype**: G - The genotype. - **representation**: geneticengine.representations.api.Representation[G, P] - The representation. - **phenotype**: P | None = None - Cached phenotype, initially None. ## Exception: IndividualNotEvaluatedException ### Description Exception raised when an individual has not been evaluated (i.e., no fitness set). Inherits from Exception. ### Constructor `IndividualNotEvaluatedException()` #### Parameters None. ## Module Attributes - **G** - Type variable for genotype. - **P** - Type variable for phenotype. ``` -------------------------------- ### Using with Genetic Programming: distance-based fitness Source: https://geneticengine.readthedocs.io/en/latest/_sources/synthetic_problems.md.txt Defines a fitness function using Levenshtein distance between stringified phenotypes and runs GeneticProgramming with an EvaluationBudget of 100. Assumes G and P_target are created as in the minimal example. ```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)) ``` -------------------------------- ### Run SimpleGP with grammar and fitness function Source: https://geneticengine.readthedocs.io/en/latest/_sources/tutorial.md.txt Runs the Genetic Engine with the extracted grammar and fitness function. Configures SimpleGP with tree-based representation, population size 10, and 50 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) ``` -------------------------------- ### mk_parser() Source: https://geneticengine.readthedocs.io/en/latest/_sources/autoapi/geneticengine/grammar/metahandlers/smt/parser/index.rst.txt Creates and returns a parser for the SMT DSL using the defined grammar. This function is the primary entry point for parsing SMT expressions. ```APIDOC ## mk_parser() ### Description Creates and returns a parser for the SMT DSL using the defined grammar. This function is the primary entry point for parsing SMT expressions. ### Function Signature `mk_parser()` ### Returns - **parser** (lark.Lark) - A configured Lark parser instance for the SMT DSL. ### Usage Example ```python from geneticengine.grammar.metahandlers.smt.parser import mk_parser parser = mk_parser() # Use parser to parse SMT expressions ``` ``` -------------------------------- ### Probabilistic grammar with @weight decorator Source: https://geneticengine.readthedocs.io/en/latest/_sources/grammars.md.txt Assigns probabilities to grammar productions using the @weight decorator. OptionA is selected with 10% probability and OptionB with 90%. The classes must extend the root class (here shown as R, but the example uses Root in the surrounding text). ```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 ``` -------------------------------- ### Simple integer class in Python Source: https://geneticengine.readthedocs.io/en/latest/_sources/metahandlers/index.md.txt Shows how to define a base type in Genetic Engine's STGP front-end, where only the base type needs to be specified. ```python class I: value: int ``` -------------------------------- ### geneticengine.algorithms.gp.operators.initializers Source: https://geneticengine.readthedocs.io/en/latest/_sources/autoapi/geneticengine/algorithms/gp/operators/initializers/index.rst.txt This module provides population initializers for genetic programming, including a combined initializer and a standard full-tree initializer. ```APIDOC ## HalfAndHalfInitializer ### Description Combines two initializers, one for each half of the population. ### Constructor - **initializer1** - The first initializer. - **initializer2** - The second initializer. ### Attributes - **initializer1** - The first initializer. - **initializer2** - The second initializer. ### Methods #### initialize(problem, representation, random, target_size, **kwargs) Initializes a population by combining two initializers, each responsible for half of the population. ##### Parameters - **problem** - The problem instance. - **representation** - The representation used for individuals. - **random** - The random number generator. - **target_size** - The desired population size. - **kwargs** - Additional keyword arguments. ##### Returns - The initialized population. ## StandardInitializer ### Description All individuals are created with full trees (maximum depth in all branches). ### Methods #### initialize(problem, representation, random, target_size, **kwargs) Initializes a population where all individuals are full trees. ##### Parameters - **problem** - The problem instance. - **representation** - The representation used for individuals. - **random** - The random number generator. - **target_size** - The desired population size. - **kwargs** - Additional keyword arguments. ##### Returns - The initialized population. ``` -------------------------------- ### GeneticProgramming(problem, budget, representation, random=None, tracker=None, population_size=100, population_initializer=None, step=None) Source: https://geneticengine.readthedocs.io/en/latest/_sources/autoapi/geneticengine/algorithms/gp/gp/index.rst.txt Represents the Genetic Programming algorithm. Defaults as given in A Field Guide to GP, p.17, by Poli and Mcphee. This class is a heuristic search algorithm that evolves solutions to a problem using genetic programming. ```APIDOC ## GeneticProgramming(problem, budget, representation, random=None, tracker=None, population_size=100, population_initializer=None, step=None) ### Description Represents the Genetic Programming algorithm. Defaults as given in A Field Guide to GP, p.17, by Poli and Mcphee. ### Constructor Parameters - **problem** (Problem) - Required - A SingleObjectiveProblem or a MultiObjectiveProblem problem. - **budget** (SearchBudget) - Required - how long to search for - **representation** (Representation) - Required - The individual representation used by the GP program. - **random** (RandomSource) - Optional - A RNG instance - **tracker** (ProgressTracker) - Optional - How to record the results of evaluations - **population_size** (int) - Optional - The population size (default = 200). - **population_initializer** (PopulationInitializer) - Optional - The method to generate new individuals. - **step** (GeneticStep) - Optional - The main structure of evolution. ### Attributes - **population_size** (int) - Default: 100 - **population_initializer** - No default provided - **step** - No default provided ### Methods #### perform_search() Performs the search. No parameters or return value documented. ``` -------------------------------- ### Using metahandlers in a dataclass Source: https://geneticengine.readthedocs.io/en/latest/_sources/metahandlers/index.md.txt Shows how to use metahandlers to restrict fields with ranges and sizes. Includes IntRange, FloatRange, ListSizeBetween, VarRange, and StringSizeBetween. ```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"])] ```