Genetic Programming¶
deap_er.gp
¶
USER_DISPATCH_SIGNATURE = '(op: int64, sp: int64, stack: float64[:, ::1], columns: float64[:, ::1], constants: float64[::1], scratch: float64[::1]) -> int64'
module-attribute
¶
Signature every consumer dispatch kernel must have.
The interpreter keeps one stack of column-length rows. sp is the
number of occupied rows, so the top operand is stack[sp - 1] and a
kernel of arity n reads stack[sp - n] through stack[sp - 1],
writes its result into stack[sp - n], and returns sp - n + 1::
stack[sp - 1] <- top operand (n_rows values)
stack[sp - 2] <- second operand
...
stack[sp - n] <- first operand, and where the result goes
stack[sp] <- free scratch row
constants is the tape constant pool, scratch is one spare row
of n_rows values that a kernel may clobber freely, and stack[sp]
is always allocated and free to use as well. Builtin rolling primitives
fold their window length into the instruction, but a consumer primitive
receives every argument on the stack, so a window arrives as a
broadcast row and can be read from stack[sp - 1][0].
BUILTIN_OPCODES = {'vadd': Opcode.ADD, 'vsub': Opcode.SUB, 'vmul': Opcode.MUL, 'vdiv': Opcode.DIV, 'vneg': Opcode.NEG, 'vabs': Opcode.ABS, 'vlog': Opcode.LOG, 'vsqrt': Opcode.SQRT, 'vsin': Opcode.SIN, 'vcos': Opcode.COS, 'vgt': Opcode.GT, 'vlt': Opcode.LT, 'vge': Opcode.GE, 'vle': Opcode.LE, 'veq': Opcode.EQ, 'vand': Opcode.AND, 'vor': Opcode.OR, 'vnot': Opcode.NOT, 'vwhere': Opcode.WHERE, 'delay': Opcode.DELAY, 'diff': Opcode.DIFF, 'rolling_sum': Opcode.ROLL_SUM, 'rolling_mean': Opcode.ROLL_MEAN, 'rolling_std': Opcode.ROLL_STD, 'rolling_min': Opcode.ROLL_MIN, 'rolling_max': Opcode.ROLL_MAX, 'ema': Opcode.EMA, 'rolling_corr': Opcode.ROLL_CORR, 'rolling_cov': Opcode.ROLL_COV, 'rolling_beta': Opcode.ROLL_BETA, 'ts_rank': Opcode.TS_RANK, 'ts_argmax': Opcode.TS_ARGMAX, 'ts_argmin': Opcode.TS_ARGMIN}
module-attribute
¶
Opcode of every primitive registered by the builtin kits.
USER_BASE = 1000
module-attribute
¶
First opcode value reserved for consumer-supplied kernels.
Array
¶
Type tag for a one-dimensional float64 column.
Used as a strongly typed genetic programming type. Values that flow through nodes tagged with it are NumPy arrays, never instances of this class.
Mask
¶
Type tag for a one-dimensional boolean condition.
Comparison and logic primitives return this tag. It keeps
conditions out of arithmetic positions and gives where a
well-defined first argument.
Window
¶
Type tag for a positive integer window length.
Rolling and delay primitives take one argument of this tag. No primitive returns it, so a window is always a leaf and can be lowered to an immediate operand.
Opcode
¶
Bases: IntEnum
Instruction set of the tree stack machine.
Every value below USER_BASE is owned by this library. Consumers
bind their own kernels to values at or above USER_BASE.
Tape(opcodes, operands, constants, columns, depth, fill)
dataclass
¶
Flat, picklable form of a compiled expression tree.
Instructions are in postfix order. operands[i] is the column
index of a COL_LOAD, the constant pool index of a CONST,
the window length of a rolling instruction, and -1 otherwise.
Attributes:
| Name | Type | Description |
|---|---|---|
opcodes |
ndarray
|
Instruction stream as |
operands |
ndarray
|
Immediate operand of each instruction as |
constants |
ndarray
|
Constant pool as |
columns |
int
|
Number of columns the tape expects. |
depth |
int
|
Peak stack depth reached while running the tape. |
fill |
float
|
Fill used by the protected instructions. |
Ephemeral()
¶
Bases: Terminal, ABC
Terminal whose value is sampled when the instance is created.
Abstract base class. Subclasses must define a static method named
func.
Sample func and initialize as a non-symbolic terminal.
Source code in deap_er/private/programming/primitives/primitive_nodes.py
func()
abstractmethod
staticmethod
¶
Produce a new ephemeral value.
Subclasses must override this static method.
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the subclass does not define |
Source code in deap_er/private/programming/primitives/primitive_nodes.py
Primitive(name, args, ret_type, weight=1.0)
¶
Function node in a GP expression.
Formats as a Python call when given formatted child expressions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the primitive. |
required |
args
|
list[type]
|
Argument types of the primitive. |
required |
ret_type
|
type
|
Return type of the primitive. |
required |
weight
|
float
|
Relative sampling weight. Must be greater than 0. |
1.0
|
Store the primitive name, argument types, and return type.
Source code in deap_er/private/programming/primitives/primitive_nodes.py
format(*args)
¶
Format this primitive as a Python call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
str
|
Formatted child expressions, one per argument. |
()
|
Returns:
| Type | Description |
|---|---|
str
|
The primitive applied to |
Source code in deap_er/private/programming/primitives/primitive_nodes.py
__eq__(other)
¶
Return whether other is a primitive with the same slots.
Source code in deap_er/private/programming/primitives/primitive_nodes.py
Terminal(terminal, symbolic, ret_type, call_zero=False)
¶
Leaf node in a GP expression.
A terminal is a value or a zero-arity function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
terminal
|
Any
|
Value or zero-arity function stored in the leaf. |
required |
symbolic
|
bool
|
If True, format the value with |
required |
ret_type
|
type
|
Return type of the terminal. |
required |
Store terminal as a named leaf of ret_type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
terminal
|
Any
|
Value or name stored in the leaf. |
required |
symbolic
|
bool
|
If True, format the value with |
required |
ret_type
|
type
|
Return type of the terminal. |
required |
call_zero
|
bool
|
If True, format as a zero-arity call |
False
|
Source code in deap_er/private/programming/primitives/primitive_nodes.py
PrimitiveSet(name, arity, prefix='ARG')
¶
Bases: PrimitiveSetTyped
Untyped primitive set.
Subclass of PrimitiveSetTyped that treats every type as
object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the primitive set. |
required |
arity
|
int
|
Number of input arguments. |
required |
prefix
|
str
|
Prefix used to name input arguments. |
'ARG'
|
Create an untyped set with arity inputs.
Source code in deap_er/private/programming/primitives/primitive_set.py
add_primitive(primitive, arity, name=None, *_, weight=1.0, **__)
¶
Add an untyped primitive of the given arity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
primitive
|
Callable[..., Any]
|
Callable to register. |
required |
arity
|
int
|
Number of arguments. Must be at least 1. |
required |
name
|
str | None
|
Optional name. Defaults to |
None
|
weight
|
float
|
Relative sampling weight. Must be greater than 0. |
1.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/primitives/primitive_set.py
add_terminal(terminal, name=None, *_, call_zero=False, **__)
¶
Add an untyped terminal to the set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
terminal
|
Any
|
Value or callable to register as a terminal. |
required |
name
|
str | None
|
Optional name. Defaults to |
None
|
call_zero
|
bool
|
If True, format a callable terminal as
|
False
|
Source code in deap_er/private/programming/primitives/primitive_set.py
add_ephemeral_constant(name, ephemeral, *_, **__)
¶
Add an untyped ephemeral constant to the set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of this ephemeral type. |
required |
ephemeral
|
Callable[..., Any]
|
Zero-arity callable that produces a value. |
required |
Source code in deap_er/private/programming/primitives/primitive_set.py
PrimitiveSetTyped(name, in_types, ret_type, prefix='ARG')
¶
Primitive set for strongly typed genetic programming.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the primitive set. |
required |
in_types
|
list[type]
|
Input types, one per argument. |
required |
ret_type
|
type
|
Return type of expressions built from this set. |
required |
prefix
|
str
|
Prefix used to name input arguments. |
'ARG'
|
Create an empty typed set and register one terminal per input.
Source code in deap_er/private/programming/primitives/primitive_set_typed.py
terminal_ratio
property
¶
Ratio of terminals to all primitives in the set.
add_primitive(primitive, in_types, ret_type, name=None, weight=1.0)
¶
Add a primitive to the set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
primitive
|
Callable[..., Any]
|
Callable to register. |
required |
in_types
|
list[type]
|
Argument types of the primitive. |
required |
ret_type
|
type
|
Type returned by the primitive. |
required |
name
|
str | None
|
Optional name. Defaults to |
None
|
weight
|
float
|
Relative sampling weight. Must be greater than 0. |
1.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/primitives/primitive_set_typed.py
add_terminal(terminal, ret_type, name=None, *, call_zero=False)
¶
Add a terminal to the set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
terminal
|
Any
|
Value or callable to register as a terminal. |
required |
ret_type
|
type
|
Type returned by the terminal. |
required |
name
|
str | None
|
Optional name. Defaults to |
None
|
call_zero
|
bool
|
If True, format a callable terminal as |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/primitives/primitive_set_typed.py
add_ephemeral_constant(name, ephemeral, ret_type)
¶
Add an ephemeral constant to the set.
An ephemeral is a zero-arity function that returns a random value. Each tree samples its own immutable value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of this ephemeral type. |
required |
ephemeral
|
Callable[..., Any]
|
Zero-arity callable that produces a value. |
required |
ret_type
|
type
|
Type returned by the ephemeral. |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in deap_er/private/programming/primitives/primitive_set_typed.py
add_adf(prim_set)
¶
Add an Automatically Defined Function (ADF) to the set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prim_set
|
PrimitiveSetTyped
|
Primitive set that defines the ADF name, inputs, and return type. |
required |
Source code in deap_er/private/programming/primitives/primitive_set_typed.py
rename_arguments(**kwargs)
¶
Rename input arguments using the given mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
str
|
Map of current argument names to new names. Names that are not current arguments are ignored. |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a new name is already an argument, or is already used by a primitive or terminal. |
Source code in deap_er/private/programming/primitives/primitive_set_typed.py
PrimitiveTree(content)
¶
Bases: list[Any]
Prefix-ordered tree of primitives and terminals.
A list subclass used by genetic programming operators. Every node
must expose an arity attribute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
Iterable[Any]
|
Primitives and terminals that form the tree. |
required |
Initialize the tree from content.
Source code in deap_er/private/programming/primitives/primitive_tree.py
height
property
¶
Height of the tree, which is the depth of the deepest node.
root
property
¶
Root node of the tree (the first element).
__deepcopy__(memo)
¶
Return a deep copy of this tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
memo
|
dict[int, Any]
|
Memo mapping used by |
required |
Returns:
| Type | Description |
|---|---|
PrimitiveTree
|
A new tree with copied contents and attributes. |
Source code in deap_er/private/programming/primitives/primitive_tree.py
__setitem__(key, val)
¶
Replace a node or subtree, preserving tree arity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Any
|
Index or slice of the node or subtree to replace. |
required |
val
|
Any
|
Replacement node or sequence of nodes. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If a slice starts past the end of the tree. |
ValueError
|
If the replacement would change the tree arity. |
Source code in deap_er/private/programming/primitives/primitive_tree.py
__str__()
¶
Return the tree as a Python expression string.
Source code in deap_er/private/programming/primitives/primitive_tree.py
from_string(string, prim_set)
classmethod
¶
Build a tree from a Python expression string.
prim_set must contain every primitive that appears in
string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string
|
str
|
Python expression to deserialize. |
required |
prim_set
|
PrimitiveSetTyped
|
Primitive set used to resolve names. |
required |
Returns:
| Type | Description |
|---|---|
PrimitiveTree
|
A tree populated with the deserialized primitives. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If a token is not a registered primitive
and is not a Python literal, if a primitive or
terminal type does not match the expected type, if
a token arrives after the tree is complete, or if
the stream still owes argument types. A |
Source code in deap_er/private/programming/primitives/primitive_tree.py
search_subtree(begin)
¶
Return the slice of the subtree rooted at begin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
begin
|
int
|
Index of the subtree root. |
required |
Returns:
| Type | Description |
|---|---|
slice
|
Slice covering that subtree. |
Source code in deap_er/private/programming/primitives/primitive_tree.py
SlimTree(head, deltas=None)
¶
SLIM geometric-semantic genotype: a head tree plus delta blocks.
This type exists only to back the SLIM inflate, deflate, and donor
operators. Standard GP should continue to use PrimitiveTree.
Initialize a SLIM individual.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
head
|
PrimitiveTree | list[Any]
|
Initial tree |
required |
deltas
|
list[PrimitiveTree] | None
|
Semantic delta blocks appended by inflate mutation. |
None
|
Source code in deap_er/private/programming/slim/slim_tree.py
from_tree(tree)
classmethod
¶
Wrap a standard tree as a SLIM head with no deltas.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
SlimTree | PrimitiveTree | list[Any]
|
Tree to use as the SLIM head. |
required |
Returns:
| Type | Description |
|---|---|
SlimTree
|
A new |
Source code in deap_er/private/programming/slim/slim_tree.py
__len__()
¶
__str__()
¶
Return a Python expression that sums head and delta blocks.
__deepcopy__(memo)
¶
Return a deep copy of this SLIM individual.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
memo
|
dict[int, Any]
|
Memo mapping used by |
required |
Returns:
| Type | Description |
|---|---|
SlimTree
|
A new |
Source code in deap_er/private/programming/slim/slim_tree.py
TapeFlags(all_nan, constant, hides_warmup)
dataclass
¶
Static certificates for a lowered tape.
skip_score
property
¶
Return whether scoring should skip interpret_tapes.
write_affine_scale(individual, intercept, slope, prim_set)
¶
Write Keijzer a + b * f(x) back onto a GP expression.
A PrimitiveTree is wrapped as add(a, mul(b, tree)) with
a and b as ephemeral leaves. A SlimTree wraps the head
the same way and wraps each existing delta as mul(b, delta),
so compile stays a + b * (head + sum(deltas)). Fitness and
compile-cache entries for the previous expression are invalidated.
This is the Lamarckian path next to
:func:~deap_er.gp.tune_ephemerals; Darwinian callers use
:func:~deap_er.tools.affine_scale or
:func:~deap_er.tools.affine_case_errors for scoring only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
Any
|
|
required |
intercept
|
float
|
Fitted |
required |
slope
|
float
|
Fitted |
required |
prim_set
|
Any
|
Primitive set that must provide |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The same |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in deap_er/private/programming/affine_write.py
make_column_pset(names, name='MAIN')
¶
Build a typed primitive set with one Array input per column.
The resulting set expects and returns Array. Argument order is
the column order: pset.arguments[i] is names[i], and a
callable from compile_tree takes the columns as positional
arguments in that same order.
Register operators onto the set with add_numpy_primitives,
add_window_primitives, add_pair_window_primitives, and
add_ts_primitives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
names
|
Sequence[str]
|
Column names, in the order the columns are passed to
compiled trees. Each name must be a plain Python
identifier that is not a keyword and does not look like
the default |
required |
name
|
str
|
Name of the primitive set. |
'MAIN'
|
Returns:
| Type | Description |
|---|---|
PrimitiveSetTyped
|
A typed primitive set with one renamed input terminal per |
PrimitiveSetTyped
|
column. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/columnar.py
columnar_pset(names, *, name='MAIN', window=(2, 64), window_name='window', pair_windows=False, ts=False)
¶
Build a columnar primitive set with the usual kits registered.
This is make_column_pset plus the vectorized and causal-window
kits. Pair-window and time-series primitives are opt-in. A window
ephemeral is added when window is a bound pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
names
|
Sequence[str]
|
Column names, in the order compiled trees receive them. |
required |
name
|
str
|
Name of the primitive set. |
'MAIN'
|
window
|
tuple[int, int] | None
|
Inclusive |
(2, 64)
|
window_name
|
str
|
Ephemeral type name. Must be unique for a given bound pair across the process. |
'window'
|
pair_windows
|
bool
|
If True, also register |
False
|
ts
|
bool
|
If True, also register |
False
|
Returns:
| Type | Description |
|---|---|
PrimitiveSetTyped
|
A typed primitive set ready for |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/columnar_setup.py
evaluate_columnar(individuals, pset, matrix, target, *, cases=None, backend='opcode', parallel=False, empty=_DEFAULT_EMPTY, min_valid=None, reduce=True, static_filter=True)
¶
Score trees against one packed column matrix.
Unique programs are lowered once by str(tree). The batch is
run through interpret_tapes. Warmup nan samples are
dropped from the MSE, matching the columnar fitness contract.
Register the result as toolbox.evaluate_batch. When
static_filter is true, tape_flags may skip
interpret_tapes for identically nan, constant, or
warmup-hiding programs and write empty instead. That path is
what evaluate_invalid uses when evaluate_batch is this
helper; nevals still counts the assignment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individuals
|
Sequence[Any]
|
Trees to score. An empty sequence returns |
required |
pset
|
PrimitiveSetTyped
|
Primitive set used to lower each unique tree. |
required |
matrix
|
ndarray
|
Packed |
required |
target
|
ndarray
|
One-dimensional target series, length |
required |
cases
|
Sequence[tuple[int, int]] | ndarray | None
|
Optional half-open |
None
|
backend
|
str
|
Tape backend, |
'opcode'
|
parallel
|
bool
|
If True, run the Numba path with one workspace per thread. |
False
|
empty
|
float
|
Fitness used when a prediction has too few finite
samples, when |
_DEFAULT_EMPTY
|
min_valid
|
int | None
|
Minimum finite overlap required when |
None
|
reduce
|
bool
|
When |
True
|
static_filter
|
bool
|
When true, skip |
True
|
Returns:
| Type | Description |
|---|---|
list[tuple[float, ...]]
|
One fitness tuple per individual, in input order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/columnar_setup.py
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 | |
build_tree_graph(expr)
¶
Build a graph representation of a tree expression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
GPExprTypes
|
Tree expression to convert. |
required |
Returns:
| Type | Description |
|---|---|
GPGraph
|
Nodes, edges, and a mapping of node indices to labels. |
Source code in deap_er/private/programming/tree_graph.py
clear_compile_cache()
¶
Drop every compiled expression from the process-wide LRU cache.
Call this after mutating a primitive set so a later
compile_tree cannot return a lambda compiled against the
previous context. Also clears every live EvalCache so a
language mutation cannot keep stale fitness.
Source code in deap_er/private/programming/compilers.py
compile_adf_tree(expr, prim_sets)
¶
Compile a main tree together with its ADF trees.
The first element of expr is the main tree. The rest are
automatically defined functions that the main tree may call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
GPExprTypes
|
Sequence of expressions to compile, one per primitive
set. Each item may be a string, a |
required |
prim_sets
|
GPTypedSets
|
Primitive sets aligned with |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A callable if the main primitive set has one or more |
Any
|
arguments, otherwise the result of the evaluation. |
Source code in deap_er/private/programming/compilers.py
compile_tree(expr, prim_set, *, backend='python', dispatch=None)
¶
Evaluate expr against prim_set.
The default 'python' backend evaluates the expression as source
text. The 'opcode' backend lowers the tree to a flat tape and
runs it on a NumPy stack machine. The 'numba' backend runs the
same tape through a compiled interpreter and needs the numba
extra. Both tape backends require every primitive to carry an
opcode, and reject the tree while lowering when one does not.
Compiled results are cached, keyed by a structural tree key or
the source text, the argument names, the contents of the primitive
set, the backend, the dispatcher, and the promoted-library
generation. clear_compile_cache drops the table;
promote_subtree does that on every mutation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
GPExprTypes
|
Expression to compile. A string, a |
required |
prim_set
|
PrimitiveSetTyped
|
Primitive set that supplies the evaluation context. |
required |
backend
|
str
|
One of |
'python'
|
dispatch
|
Any
|
Compiled kernel that implements the consumer opcodes
of the |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A callable if |
Any
|
otherwise the result of the evaluation. |
Raises:
| Type | Description |
|---|---|
MemoryError
|
If evaluation exceeds the recursion limit. |
NameError
|
If |
ValueError
|
If the backend is unknown, or if a tape backend cannot lower the expression. |
Source code in deap_er/private/programming/compilers.py
static_limit(limiter, max_value)
¶
Return a decorator that rejects oversized GP offspring.
May wrap crossover or mutation. An offspring whose measurement
exceeds max_value is replaced by a randomly chosen parent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limiter
|
Callable[..., Any]
|
Callable that measures an individual. |
required |
max_value
|
int | float
|
Maximum allowed measurement. |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., Any]
|
A decorator for a GP operator registered on a Toolbox. |
Source code in deap_er/private/programming/tree_graph.py
cx_homologous(ind1, ind2)
¶
Exchange subtrees at the same root-to-node path when types match.
A crossover point is chosen uniformly in ind1 (never the root).
The same child-index path is resolved in ind2. When both nodes
share a return type, their subtrees are swapped. Otherwise the
operator falls back to random type-matched one-point crossover, the
same contract as :func:cx_one_point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ind1
|
GPIndividual
|
First individual to mate. Its crossover point anchors the homologous path. |
required |
ind2
|
GPIndividual
|
Second individual to mate. |
required |
Returns:
| Type | Description |
|---|---|
GPMates
|
The two individuals after subtree exchange. |
Source code in deap_er/private/programming/crossover.py
cx_one_point(ind1, ind2)
¶
Exchange a random subtree between two individuals.
A crossover point is chosen in each tree and the subtrees rooted there are swapped. Individuals shorter than two nodes are returned unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ind1
|
GPIndividual
|
First individual to mate. |
required |
ind2
|
GPIndividual
|
Second individual to mate. |
required |
Returns:
| Type | Description |
|---|---|
GPMates
|
The two individuals after subtree exchange. |
Source code in deap_er/private/programming/crossover.py
cx_one_point_leaf_biased(ind1, ind2, term_prob)
¶
Exchange a random subtree, biased toward terminals.
Same as one-point crossover, except each parent independently
selects a terminal as the crossover point with probability
term_prob.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ind1
|
GPIndividual
|
First individual to mate. |
required |
ind2
|
GPIndividual
|
Second individual to mate. |
required |
term_prob
|
float
|
Probability of choosing a terminal as the crossover point. |
required |
Returns:
| Type | Description |
|---|---|
GPMates
|
The two individuals after subtree exchange. |
Source code in deap_er/private/programming/crossover.py
cx_one_point_semantic(ind1, ind2, prim_set, matrix, *, valid=None, metric='euclidean')
¶
Exchange subtrees at a semantically close type-matched pair.
One shared return type is chosen at random. ind1 donates a
random crossover point of that type. ind2 donates the
type-matched node whose interpret_tape row is nearest to the
anchor subtree under metric. When every distance is infinite,
ind2's partner is chosen uniformly among its type-matched
candidates. Type-matched one-point (:func:~deap_er.gp.cx_one_point)
remains the default toolbox mate; this operator is for columnar runs
that already score interpret_tapes. Geometric semantic variation
is :func:~deap_er.gp.cx_semantic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ind1
|
GPIndividual
|
First individual to mate. |
required |
ind2
|
GPIndividual
|
Second individual to mate. |
required |
prim_set
|
PrimitiveSetTyped
|
Primitive set that can lower every subtree primitive. |
required |
matrix
|
ndarray
|
Packed |
required |
valid
|
ndarray | None
|
Optional per-row warmup mask of length |
None
|
metric
|
SemanticMetric
|
|
'euclidean'
|
Returns:
| Type | Description |
|---|---|
GPMates
|
The two individuals after subtree exchange. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a subtree cannot be lowered to a tape. |
Source code in deap_er/private/programming/cx_semantic_one_point.py
gen_full(prim_set, min_depth, max_depth, ret_type=None)
¶
Generate a full tree whose leaves share one depth.
The common leaf depth is drawn between min_depth and
max_depth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prim_set
|
PrimitiveSetTyped
|
Primitive set from which nodes are selected. |
required |
min_depth
|
int
|
Minimum depth of the random tree. |
required |
max_depth
|
int
|
Maximum depth of the random tree. |
required |
ret_type
|
Any | None
|
Return type of the generated tree. Defaults to
|
None
|
Returns:
| Type | Description |
|---|---|
list[Any]
|
A full tree as a list of primitives and terminals. |
Source code in deap_er/private/programming/generators.py
gen_grow(prim_set, min_depth, max_depth, ret_type=None)
¶
Generate a grown tree whose leaves may have different depths.
Each leaf depth lies between min_depth and max_depth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prim_set
|
PrimitiveSetTyped
|
Primitive set from which nodes are selected. |
required |
min_depth
|
int
|
Minimum depth of the random tree. |
required |
max_depth
|
int
|
Maximum depth of the random tree. |
required |
ret_type
|
Any | None
|
Return type of the generated tree. Defaults to
|
None
|
Returns:
| Type | Description |
|---|---|
list[Any]
|
A grown tree as a list of primitives and terminals. |
Source code in deap_er/private/programming/generators.py
gen_half_and_half(prim_set, min_depth, max_depth, ret_type=None)
¶
Generate a tree with either gen_grow or gen_full.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prim_set
|
PrimitiveSetTyped
|
Primitive set from which nodes are selected. |
required |
min_depth
|
int
|
Minimum depth of the random tree. |
required |
max_depth
|
int
|
Maximum depth of the random tree. |
required |
ret_type
|
Any | None
|
Return type of the generated tree. Defaults to
|
None
|
Returns:
| Type | Description |
|---|---|
list[Any]
|
Either a full tree or a grown tree, as a list of primitives |
list[Any]
|
and terminals. |
Source code in deap_er/private/programming/generators.py
generate(prim_set, min_depth, max_depth, condition, ret_type=None)
¶
Grow a tree as a depth-first list of primitives and terminals.
Each branch grows until condition is true. A branch also stops
early when its type has terminals but no primitives, which is how
a strongly typed set expresses a leaf-only type such as a rolling
window length. The list can be passed to PrimitiveTree to
build a tree object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prim_set
|
PrimitiveSetTyped
|
Primitive set from which nodes are selected. |
required |
min_depth
|
int
|
Minimum depth of the random tree. |
required |
max_depth
|
int
|
Maximum depth of the random tree. |
required |
condition
|
Callable[..., bool]
|
Callable |
required |
ret_type
|
Any | None
|
Return type of the generated tree. Defaults to
|
None
|
Returns:
| Type | Description |
|---|---|
list[Any]
|
A tree as a flat list of primitives and terminals, in |
list[Any]
|
depth-first order. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If |
Source code in deap_er/private/programming/generators.py
harm(toolbox, population, generations, cx_prob, mut_prob, hof=None, stats=None, verbose=False, **kwargs)
¶
Evolve a GP population with HARM bloat control.
Default parameter values are recommended for most use cases.
Requires mate, mutate, select, evaluate, clone,
and map on toolbox.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
toolbox
|
Toolbox
|
Toolbox with the evolution operators. |
required |
population
|
list[GPIndividual]
|
Individuals to evolve. Replaced in place. |
required |
generations
|
int
|
Number of generations to run. |
required |
cx_prob
|
float
|
Probability of mating two individuals. |
required |
mut_prob
|
float
|
Probability of mutating an individual. |
required |
hof
|
EvoRecords | None
|
Optional HallOfFame or ParetoFront to update. |
None
|
stats
|
EvoStats | None
|
Optional Statistics or MultiStatistics to compile. |
None
|
verbose
|
bool
|
If True, print the logbook stream each generation. |
False
|
**kwargs
|
Any
|
HARM size-control knobs. Keyword-only. Accepted keys:
|
{}
|
Returns:
| Type | Description |
|---|---|
EvoAlgoResult
|
The final population and the logbook. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in deap_er/private/programming/harm/harm.py
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 | |
tree_to_infix(expr)
¶
Return a tree as an infix expression string.
Known arithmetic and logic names become infix operators. Other
primitives stay in prefix name(args) form.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Any
|
Prefix-ordered tree of primitives and terminals. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The expression in infix notation. |
Source code in deap_er/private/programming/infix.py
assign_ephemerals(individual, values)
¶
Write repaired values onto numeric leaves, replacing each node.
Window coordinates are rounded to int and clamped to the
ephemeral's inclusive legal range, or to >= 1 for a literal
Window terminal. Nodes are replaced so a shallow clone does
not alias values back onto the source tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
Any
|
|
required |
values
|
Sequence[float]
|
Vector aligned with |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/ephemeral_leaves.py
extract_ephemerals(individual)
¶
Copy numeric-leaf values into a vector in walk order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
Any
|
|
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A length- |
Source code in deap_er/private/programming/ephemeral_leaves.py
numeric_leaves(individual)
¶
Return numeric-leaf locations in documented walk order.
A numeric leaf is an Ephemeral or a Terminal whose
ret is Window. Order is prefix list order. A SlimTree
walks head, then each delta, each in prefix order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
Any
|
|
required |
Returns:
| Type | Description |
|---|---|
list[LeafLoc]
|
|
Source code in deap_er/private/programming/ephemeral_leaves.py
tune_ephemerals(individual, strategy, evaluate=None, n_gen=5, *, evaluate_batch=None, clone=None)
¶
Polish numeric leaves with a short boxed CMA run.
Extracts ephemeral floats and Window ints, runs n_gen
generate / update steps on strategy, writes the
repaired centroid back, then invalidates fitness, the compile
cache, and matching EvalCache keys for the previous
expression. Evaluation is the caller's
evaluate on clones, or evaluate_batch on a pack of clones.
Provide one of those callables; when both are set, the batch path
is used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
Any
|
|
required |
strategy
|
Any
|
|
required |
evaluate
|
Callable[[Any], Any] | None
|
|
None
|
n_gen
|
int
|
Inner CMA generations. Default |
5
|
evaluate_batch
|
Callable[[list[Any]], Any] | None
|
Optional |
None
|
clone
|
Callable[[Any], Any] | None
|
Individual copier. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The same |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/memetic.py
tune_ephemerals_budget(individual, strategy, evaluate=None, *, n_gen=None, evaluate_batch=None, clone=None, n_evals=None, nevals_used=0, exams=None, held_out=None, held_out_evaluate=None, held_out_evaluate_batch=None)
¶
Polish numeric leaves under a memetic and evaluation leash.
Caps inner n_gen to :data:~deap_er.gp.MEMETIC_MAX_N_GEN and,
when n_evals is set, to the remaining evaluation budget. Defaults
to :data:~deap_er.gp.MEMETIC_DEFAULT_N_GEN inner generations.
When a caller-marked held-out exam is available from held_out or
exams, trials are judged with held_out_evaluate or
held_out_evaluate_batch instead of the train evaluate path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
Any
|
|
required |
strategy
|
Any
|
|
required |
evaluate
|
Callable[[Any], Any] | None
|
|
None
|
n_gen
|
int | None
|
Requested inner generations. Defaults to
:data: |
None
|
evaluate_batch
|
Callable[[list[Any]], Any] | None
|
Optional |
None
|
clone
|
Callable[[Any], Any] | None
|
Individual copier passed through to
:func: |
None
|
n_evals
|
int | None
|
Optional evaluation budget for the outer run. |
None
|
nevals_used
|
int
|
Evaluations already charged to the run. |
0
|
exams
|
Any
|
Optional exam pool whose |
None
|
held_out
|
CaseExam | None
|
Optional held-out exam that overrides a pool marker. |
None
|
held_out_evaluate
|
Callable[[Any], Any] | None
|
Held-out judge when a held-out exam exists. |
None
|
held_out_evaluate_batch
|
Callable[[list[Any]], Any] | None
|
Batch held-out judge when a held-out exam exists. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
|
int
|
budget is already spent or no numeric leaves exist. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a held-out exam is marked but no held-out judge is given, or if neither train nor held-out evaluation is available. |
Source code in deap_er/private/programming/memetic_budget.py
cap_tune_n_gen(strategy, n_gen, *, n_evals=None, nevals_used=0, max_n_gen=MEMETIC_MAX_N_GEN)
¶
Cap inner tune generations to a memetic leash and optional budget.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strategy
|
Any
|
|
required |
n_gen
|
int
|
Requested inner generations. |
required |
n_evals
|
int | None
|
Optional evaluation budget. When set, the return
value never exceeds what |
None
|
nevals_used
|
int
|
Evaluations already charged to the run. |
0
|
max_n_gen
|
int
|
Hard ceiling on inner generations. Defaults to
:data: |
MEMETIC_MAX_N_GEN
|
Returns:
| Type | Description |
|---|---|
int
|
A non-negative generation count. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/memetic_defaults.py
estimate_tune_ephemerals_evals(strategy, n_gen)
¶
Estimate how many evaluations a memetic tune would spend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
strategy
|
Any
|
|
required |
n_gen
|
int
|
Inner CMA generations. |
required |
Returns:
| Type | Description |
|---|---|
int
|
|
Source code in deap_er/private/programming/memetic_defaults.py
mut_ephemeral(individual, mode='all')
¶
Resample one or all ephemeral constants in the tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
GPIndividual
|
GP tree to mutate. |
required |
mode
|
str
|
|
'all'
|
Returns:
| Type | Description |
|---|---|
GPMutant
|
A one-element tuple containing the mutated individual. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/mutation.py
mut_insert(individual, prim_set)
¶
Insert a new primitive branch at a random position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
GPIndividual
|
GP tree to mutate. |
required |
prim_set
|
PrimitiveSetTyped
|
Primitive set used to choose the inserted branch. |
required |
Returns:
| Type | Description |
|---|---|
GPMutant
|
A one-element tuple containing the mutated individual. |
Source code in deap_er/private/programming/mutation.py
mut_node_replacement(individual, prim_set)
¶
Replace a random node with a compatible node from prim_set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
GPIndividual
|
GP tree to mutate. |
required |
prim_set
|
PrimitiveSetTyped
|
Primitive set to sample the replacement from. |
required |
Returns:
| Type | Description |
|---|---|
GPMutant
|
A one-element tuple containing the mutated individual. |
Source code in deap_er/private/programming/mutation.py
mut_shrink(individual)
¶
Replace a random branch with one of its arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
GPIndividual
|
GP tree to mutate. |
required |
Returns:
| Type | Description |
|---|---|
GPMutant
|
A one-element tuple containing the mutated individual. |
Source code in deap_er/private/programming/mutation.py
mut_uniform(individual, expr, prim_set)
¶
Replace a random subtree with an expression from expr.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
GPIndividual
|
GP tree to mutate. |
required |
expr
|
Callable[..., Any]
|
Callable that returns a random subtree. |
required |
prim_set
|
PrimitiveSetTyped
|
Primitive set passed to |
required |
Returns:
| Type | Description |
|---|---|
GPMutant
|
A one-element tuple containing the mutated individual. |
Source code in deap_er/private/programming/mutation.py
bind_tape(tape, dispatch=None)
¶
Bind a tape to the compiled interpreter.
The interpreter is compiled once per process and once more for each
distinct dispatcher, never per tree. It is single threaded on
purpose: parallelize across individuals through toolbox.map
rather than inside a tree.
Every compiled tape shares one process-wide workspace, so the returned callable must not be run from several threads at once. The result it returns is a fresh array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tape
|
Tape
|
Tape produced by |
required |
dispatch
|
Any
|
Compiled kernel implementing the opcodes at or above
|
None
|
Returns:
| Type | Description |
|---|---|
Callable[..., ndarray]
|
A callable that takes one array per column, or a single |
Callable[..., ndarray]
|
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If the |
ValueError
|
If the tape expects no columns, or if it holds consumer opcodes but no dispatcher was given. |
Source code in deap_er/private/programming/numba/numba_ops.py
numba_available()
¶
Report whether the optional Numba dependency is importable.
Returns:
| Type | Description |
|---|---|
bool
|
True when the |
Source code in deap_er/private/programming/numba/numba_ops.py
warmup_numba(*, parallel=False, dispatch=None)
¶
Compile the Numba tape interpreter for this process.
Runs a trivial column-load tape so the interpreter and the serial
batch kernel are specialized before the first real evaluation.
When NUMBA_CACHE_DIR is unset, a writable directory under the
user's cache (~/.cache/deap-er/numba, or
$XDG_CACHE_HOME/deap-er/numba) is used so spawned workers with
a different working directory can reload the interpreter from disk
instead of recompiling it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parallel
|
bool
|
If True, also specialize the |
False
|
dispatch
|
Any
|
Consumer kernel to specialize. |
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If the |
Source code in deap_er/private/programming/numba/numba_ops.py
vabs(value)
¶
Take the elementwise absolute value of a series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Operand. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The elementwise absolute value. |
vadd(left, right)
¶
Add two series elementwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
Left operand. |
required |
right
|
Any
|
Right operand. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The elementwise sum. |
vcos(value)
¶
Take the elementwise cosine of a series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Operand in radians. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The elementwise cosine. |
vdiv(left, right, fill=DEFAULT_FILL)
¶
Divide two series elementwise, protecting against zero divisors.
Positions where finite operands produced a non-finite quotient are
replaced by fill. A non-finite value that came from an operand
is preserved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
Numerator. |
required |
right
|
Any
|
Denominator. |
required |
fill
|
float
|
Value substituted for a fabricated non-finite result. |
DEFAULT_FILL
|
Returns:
| Type | Description |
|---|---|
Any
|
The protected elementwise quotient. |
Source code in deap_er/private/programming/numpy/numpy_arith.py
vlog(value, fill=DEFAULT_FILL)
¶
Take the natural logarithm of a series, protecting the domain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Operand. |
required |
fill
|
float
|
Value substituted for a fabricated non-finite result. |
DEFAULT_FILL
|
Returns:
| Type | Description |
|---|---|
Any
|
The protected elementwise logarithm. |
Source code in deap_er/private/programming/numpy/numpy_arith.py
vmul(left, right)
¶
Multiply two series elementwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
Left operand. |
required |
right
|
Any
|
Right operand. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The elementwise product. |
vneg(value)
¶
Negate a series elementwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Operand to negate. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The elementwise negation. |
vsin(value)
¶
Take the elementwise sine of a series.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Operand in radians. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The elementwise sine. |
vsqrt(value, fill=DEFAULT_FILL)
¶
Take the square root of a series, protecting the domain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Operand. |
required |
fill
|
float
|
Value substituted for a fabricated non-finite result. |
DEFAULT_FILL
|
Returns:
| Type | Description |
|---|---|
Any
|
The protected elementwise square root. |
Source code in deap_er/private/programming/numpy/numpy_arith.py
vsub(left, right)
¶
Subtract two series elementwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
Left operand. |
required |
right
|
Any
|
Right operand. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The elementwise difference. |
vand(left, right)
¶
Combine two masks elementwise with logical and.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
Left mask. |
required |
right
|
Any
|
Right mask. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A boolean mask. |
veq(left, right)
¶
Compare two series elementwise with ==.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
Left operand. |
required |
right
|
Any
|
Right operand. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A boolean mask. |
vge(left, right)
¶
Compare two series elementwise with >=.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
Left operand. |
required |
right
|
Any
|
Right operand. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A boolean mask. |
vgt(left, right)
¶
Compare two series elementwise with >.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
Left operand. |
required |
right
|
Any
|
Right operand. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A boolean mask. |
vle(left, right)
¶
Compare two series elementwise with <=.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
Left operand. |
required |
right
|
Any
|
Right operand. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A boolean mask. |
vlt(left, right)
¶
Compare two series elementwise with <.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
Left operand. |
required |
right
|
Any
|
Right operand. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A boolean mask. |
vnot(value)
¶
Invert a mask elementwise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Mask to invert. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A boolean mask. |
vor(left, right)
¶
Combine two masks elementwise with logical or.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
Left mask. |
required |
right
|
Any
|
Right mask. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A boolean mask. |
vwhere(condition, on_true, on_false)
¶
Select elementwise between two series.
This is how a program turns a condition into a value without a
Python if.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition
|
Any
|
Mask that selects the branch. |
required |
on_true
|
Any
|
Values taken where the mask is true. |
required |
on_false
|
Any
|
Values taken where the mask is false. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The selected series. |
Source code in deap_er/private/programming/numpy/numpy_logic.py
add_numpy_primitives(prim_set, *, fill=DEFAULT_FILL)
¶
Register the vectorized primitive kit on a typed primitive set.
Adds arithmetic, protected division and domain-limited unary
operations, comparisons that return Mask, mask logic, and
vwhere. The constants True and False are registered as
Mask terminals so tree generation can terminate a mask branch.
The chosen fill is bound into the protected primitives, where
infer_fill can read it back so the other backends reproduce the
same protection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prim_set
|
PrimitiveSetTyped
|
Typed primitive set built by |
required |
fill
|
float
|
Value substituted for a non-finite result of a protected operation that was computed from finite operands. |
DEFAULT_FILL
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a primitive name collides with an argument of
|
Source code in deap_er/private/programming/numpy/numpy_ops.py
bind_numba_opcode(name, opcode)
¶
Bind a primitive name to a consumer-supplied opcode.
The binding is used only while lowering a tree. It is never read inside the interpreter loop. Persist the bindings alongside a run: replaying a checkpointed tree against different bindings decodes the tree into different instructions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of a primitive registered on the primitive set. |
required |
opcode
|
int
|
Opcode value, at or above |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the opcode is below |
Source code in deap_er/private/programming/tape.py
interpret_tape(tape, columns)
¶
Run a tape over column inputs.
Evaluates through the same functions as the default backend, so the two agree by construction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tape
|
Tape
|
Tape produced by |
required |
columns
|
Sequence[Any] | ndarray
|
One array per column, in the order the primitive set
declares them, or one packed |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The result of the expression. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the column count does not match the tape, if the tape holds an instruction the interpreter does not know, or if the tape underflows or leaves no result. |
Source code in deap_er/private/programming/opcodes.py
lower_tree(expr, prim_set, *, fill=None)
¶
Lower an expression tree to a flat instruction tape.
Only primitives with a builtin opcode or a binding made through
bind_numba_opcode can be lowered. Everything else fails here
rather than at evaluation time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
GPExprTypes
|
Expression to lower. A |
required |
prim_set
|
PrimitiveSetTyped
|
Primitive set the expression was built from. |
required |
fill
|
float | None
|
Fill for the protected instructions. Read back from
|
None
|
Returns:
| Type | Description |
|---|---|
Tape
|
The lowered tape. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a primitive has no opcode, if a window argument is not an integer leaf, if a terminal is neither a column nor a number, or if the tree is empty, holds unreachable nodes, or does not balance the evaluation stack. |
Source code in deap_er/private/programming/tape_lower.py
numba_opcodes()
¶
Return the consumer opcode bindings made so far.
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
A copy of the name to opcode map, suitable for storing with a |
dict[str, int]
|
checkpoint. |
promote_subtree(prim_set, expr, index=0, *, max_library=32, prefix='promo', weight=1.0)
¶
Lift a complete typed subtree into prim_set as a primitive.
The caller fires this helper. It does not run inside ea_*.
Formals are the set's argument terminals that appear in the
subtree, in prim_set.arguments order. Constants and
ephemerals stay baked into the body. Nested promoted names are
expanded before the body is stored, so evicting an inner name
does not leave USER_BASE in later tapes. On a columnar set
the name is bound at or above USER_BASE and lower_tree
expands the body so tapes stay on builtin opcodes. Promotion
clears the compile cache and every live EvalCache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prim_set
|
PrimitiveSetTyped
|
Set that receives the new primitive. |
required |
expr
|
PrimitiveTree | Sequence[Any]
|
Prefix tree holding the subtree. |
required |
index
|
int
|
Root index of the subtree to lift. |
0
|
max_library
|
int
|
Maximum number of promoted names to keep. |
32
|
prefix
|
str
|
Prefix of the generated name ( |
'promo'
|
weight
|
float
|
Sampling weight of the new primitive. |
1.0
|
Returns:
| Type | Description |
|---|---|
str
|
The generated primitive name. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If |
TypeError
|
If a node type does not match its parent slot. |
ValueError
|
If |
Source code in deap_er/private/programming/promote.py
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 | |
promoted_names(prim_set)
¶
Return currently registered promoted names, oldest first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prim_set
|
PrimitiveSetTyped
|
Primitive set that may hold a promoted library. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
Promoted names still on the set. Empty when none were added. |
Source code in deap_er/private/programming/promote_store.py
register_gp(toolbox, pset, *, individual=None, min_depth=1, max_depth=2, mut_min_depth=0, mut_max_depth=2, height_limit=17, backend=None, select=True, contestants=3)
¶
Register the standard tree-GP operators on toolbox.
Wires the aliases every prefix-tree run needs and that callers
commonly omit: clone_individual instead of deepcopy,
compile_tree, half-and-half initialization, one-point
crossover, uniform mutation, and a height static_limit.
Does not register evaluate or evaluate_batch — fitness
stays on the caller.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
toolbox
|
Toolbox
|
Toolbox to mutate. |
required |
pset
|
PrimitiveSetTyped
|
Primitive set used for init, compile, and mutation. |
required |
individual
|
type | None
|
Optional individual type. When given, registers
|
None
|
min_depth
|
int
|
Minimum depth for half-and-half initialization. |
1
|
max_depth
|
int
|
Maximum depth for half-and-half initialization. |
2
|
mut_min_depth
|
int
|
Minimum depth of the subtree grown by mutation. |
0
|
mut_max_depth
|
int
|
Maximum depth of the subtree grown by mutation. |
2
|
height_limit
|
int | None
|
Height cap applied to |
17
|
backend
|
str | None
|
Optional |
None
|
select
|
bool | Callable[..., Any]
|
If True, register tournament selection. If False,
leave |
True
|
contestants
|
int
|
Tournament size when |
3
|
Returns:
| Type | Description |
|---|---|
Toolbox
|
The same |
Source code in deap_er/private/programming/register_gp.py
cx_semantic(ind1, ind2, prim_set, min_depth=2, max_depth=6, gen_func=gen_grow)
¶
Mate two individuals by a semantic crossover.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ind1
|
list[Any]
|
First individual to mate. |
required |
ind2
|
list[Any]
|
Second individual to mate. |
required |
prim_set
|
PrimitiveSetTyped
|
Primitive set used to build the random tree. |
required |
min_depth
|
int
|
Minimum depth of the random tree. |
2
|
max_depth
|
int
|
Maximum depth of the random tree. |
6
|
gen_func
|
Callable[..., Any]
|
Tree generator. Defaults to |
gen_grow
|
Returns:
| Type | Description |
|---|---|
tuple[list[Any], list[Any]]
|
The two individuals after crossover. |
Source code in deap_er/private/programming/semantic.py
mut_semantic(individual, prim_set, min_depth=2, max_depth=6, gen_func=None, mut_step=None)
¶
Mutate an individual by a semantic mutation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
list[Any]
|
Individual to mutate. |
required |
prim_set
|
PrimitiveSetTyped
|
Primitive set used to build the random trees. |
required |
min_depth
|
int
|
Minimum depth of each random tree. |
2
|
max_depth
|
int
|
Maximum depth of each random tree. |
6
|
gen_func
|
Callable[..., Any] | None
|
Tree generator. Defaults to |
None
|
mut_step
|
float | None
|
Mutation step. Drawn uniformly from |
None
|
Returns:
| Type | Description |
|---|---|
tuple[list[Any]]
|
A one-element tuple containing the mutated individual. |
Source code in deap_er/private/programming/semantic.py
cx_slim_donor(ind1, ind2, prim_set, *, best_donor=True)
¶
Mate two SLIM individuals by donor crossover (XODn / XOBDn).
One delta block moves from the donor parent to the receiver.
Offspring sizes stay close to the parents because one block is
removed and one is added. When best_donor is True and both
parents have valid fitness, the fitter parent donates (XOBDn);
otherwise the donor is chosen uniformly (XODn). When the donor
has no delta blocks, the parents are returned unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ind1
|
SlimTree
|
First parent |
required |
ind2
|
SlimTree
|
Second parent |
required |
prim_set
|
PrimitiveSetTyped
|
Primitive set checked for required semantic operators. |
required |
best_donor
|
bool
|
Prefer the fitter parent as donor when fitness is valid on both parents. |
True
|
Returns:
| Type | Description |
|---|---|
tuple[SlimTree, SlimTree]
|
The two parents after crossover. |
Source code in deap_er/private/programming/slim/slim_ops.py
mut_slim(individual, prim_set, *, inflate_prob=0.3, min_depth=2, max_depth=6, gen_func=None, mut_step=None)
¶
Apply inflate or deflate mutation with fixed probability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
SlimTree
|
SLIM genotype to mutate in place. |
required |
prim_set
|
PrimitiveSetTyped
|
Primitive set used by inflate mutation. |
required |
inflate_prob
|
float
|
Probability of inflate mutation. Deflate is used otherwise. |
0.3
|
min_depth
|
int
|
Minimum depth of random trees for inflate. |
2
|
max_depth
|
int
|
Maximum depth of random trees for inflate. |
6
|
gen_func
|
Callable[..., Any] | None
|
Tree generator for inflate. Defaults to |
None
|
mut_step
|
float | None
|
Mutation step for inflate. Drawn uniformly from
|
None
|
Returns:
| Type | Description |
|---|---|
tuple[SlimTree]
|
A one-element tuple containing the mutated individual. |
Source code in deap_er/private/programming/slim/slim_ops.py
mut_slim_deflate(individual)
¶
Remove a random delta block (SLIM deflate mutation).
The head tree is never removed. When there are no delta blocks, the individual is returned unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
SlimTree
|
SLIM genotype to mutate in place. |
required |
Returns:
| Type | Description |
|---|---|
tuple[SlimTree]
|
A one-element tuple containing the mutated individual. |
Source code in deap_er/private/programming/slim/slim_ops.py
mut_slim_inflate(individual, prim_set, min_depth=2, max_depth=6, gen_func=None, mut_step=None)
¶
Append a geometric semantic delta block (SLIM inflate mutation).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
SlimTree
|
SLIM genotype to mutate in place. |
required |
prim_set
|
PrimitiveSetTyped
|
Primitive set used to build the random trees. |
required |
min_depth
|
int
|
Minimum depth of each random tree. |
2
|
max_depth
|
int
|
Maximum depth of each random tree. |
6
|
gen_func
|
Callable[..., Any] | None
|
Tree generator. Defaults to |
None
|
mut_step
|
float | None
|
Mutation step. Drawn uniformly from |
None
|
Returns:
| Type | Description |
|---|---|
tuple[SlimTree]
|
A one-element tuple containing the mutated individual. |
Source code in deap_er/private/programming/slim/slim_ops.py
compile_slim_tree(slim, prim_set, *, backend='python', dispatch=None)
¶
Compile a SLIM individual for evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slim
|
SlimTree
|
SLIM genotype to compile. |
required |
prim_set
|
PrimitiveSetTyped
|
Primitive set that supplies the evaluation context. |
required |
backend
|
str
|
One of |
'python'
|
dispatch
|
Any
|
Compiled kernel for the |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A callable when |
Any
|
otherwise the evaluated scalar for the expression. |
Source code in deap_er/private/programming/slim/slim_tree.py
suffix_rescore(tapes, matrix, prefix, *, n_new=None, lookback=None, backend='opcode', dispatch=None, parallel=False)
¶
Rescore lookback + n_new trailing rows onto a cached prefix.
After an append-only vstack, pass the grown packed matrix and
the scores from before the append. The helper keeps those prefix
columns (new rows are the present) and writes only the last
n_new outputs of a suffix interpret_tapes call. The full
series matches a one-shot interpret_tapes on matrix,
including warmup nan s.
A lookback smaller than :func:tape_lookback is rejected so a
short suffix cannot silently drop history. ema is IIR: the
helper scores the full pack so the recurrence matches the oracle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tapes
|
Iterable[Tape]
|
Tapes in output-row order. A one-shot iterable is consumed once. |
required |
matrix
|
Any
|
Grown packed |
required |
prefix
|
ndarray
|
Cached scores of shape |
required |
n_new
|
int | None
|
Rows appended after |
None
|
lookback
|
int | None
|
History rows to keep in front of the new block.
Defaults to the max :func: |
None
|
backend
|
str
|
Forwarded to :func: |
'opcode'
|
dispatch
|
Any
|
Forwarded to :func: |
None
|
parallel
|
bool
|
Forwarded to :func: |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A new |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/suffix_rescore.py
interpret_tapes(tapes, matrix, *, backend='opcode', dispatch=None, parallel=False)
¶
Run many tapes over one packed column matrix.
The result has one row per tape and one column per sample. It is a
new array: it does not alias matrix or the interpreter
workspace. Cache unique programs by str(tree). A stringified
Window leaf is an int; from_string restores that tag,
but an ephemeral class identity is not part of the text.
The 'opcode' backend unpacks the matrix columns once and runs
the NumPy stack machine with common-subexpression elimination
across the batch. The 'numba' backend uses the same CSE plan
on the serial path; parallel=True keeps the compiled per-tape
loop. parallel=True is not available on the opcode backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tapes
|
Iterable[Tape]
|
Tapes produced by |
required |
matrix
|
Any
|
Packed |
required |
backend
|
str
|
Either |
'opcode'
|
dispatch
|
Any
|
Compiled kernel that implements the consumer opcodes
of the |
None
|
parallel
|
bool
|
If True, run the Numba path with one workspace per
thread. Requires |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A C-contiguous |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the backend is unknown, if |
ImportError
|
If |
Source code in deap_er/private/programming/tape_batch.py
bounds_from_matrix(matrix)
¶
Return empirical (low, high) bounds for each matrix column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray | Sequence[Sequence[float]]
|
Packed |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/tape_interval.py
tape_flags(tape, column_bounds, *, n_rows)
¶
Return static certificates for a tape before scoring.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tape
|
Tape
|
Tape produced by |
required |
column_bounds
|
ndarray | Sequence[tuple[float, float]]
|
Per-column |
required |
n_rows
|
int
|
Row count of the matrix the tape would run on. |
required |
Returns:
| Type | Description |
|---|---|
TapeFlags
|
Flags for identically |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/tape_interval.py
tape_interval(tape, column_bounds)
¶
Return a conservative output interval for a tape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tape
|
Tape
|
Tape produced by |
required |
column_bounds
|
ndarray | Sequence[tuple[float, float]]
|
Per-column |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the tape is malformed or holds a consumer opcode. |
Source code in deap_er/private/programming/tape_interval.py
tape_skip_score(tape, column_bounds, *, n_rows)
¶
Return whether evaluate_columnar should skip scoring a tape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tape
|
Tape
|
Tape produced by |
required |
column_bounds
|
ndarray | Sequence[tuple[float, float]]
|
Per-column |
required |
n_rows
|
int
|
Row count of the matrix the tape would run on. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/programming/tape_interval.py
tape_lookback(tape)
¶
Return the causal lookback bound of a tape.
Walks the postfix tape and composes per-opcode lookbacks: windowed instructions add their bound to the child, and pointwise instructions take the max of their arguments. The result is the shortest prefix of earlier rows that a legal suffix rescore must keep as history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tape
|
Tape
|
Tape produced by |
required |
Returns:
| Type | Description |
|---|---|
int
|
The program's lookback in rows. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the tape underflows, leaves no result, or holds a consumer opcode. |
Source code in deap_er/private/programming/tape_lookback.py
add_window_ephemeral(prim_set, name, low, high)
¶
Register a random window length as an ephemeral constant.
Each tree samples its own immutable window length from the closed
interval [low, high]. The sampler is memoized by name, because
a primitive set rejects two ephemerals that share a name but not a
function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prim_set
|
PrimitiveSetTyped
|
Typed primitive set to register on. |
required |
name
|
str
|
Name of this ephemeral type. Must be unique across every primitive set in the process. |
required |
low
|
int
|
Smallest window length that may be sampled. At least 1. |
required |
high
|
int
|
Largest window length that may be sampled. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the bounds are invalid, or if |
Source code in deap_er/private/programming/window_ops.py
add_window_primitives(prim_set)
¶
Register the causal window primitive kit on a typed primitive set.
Every primitive takes an Array and a Window and returns an
Array. All of them are causal: an output sample is a function
of that sample and earlier ones only, and samples without enough
history are nan rather than zero, so a consumer can mask the
warmup instead of trading on fabricated values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prim_set
|
PrimitiveSetTyped
|
Typed primitive set built by |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a primitive name collides with an argument of
|
Source code in deap_er/private/programming/window_ops.py
ema(value, window)
¶
Take a causal exponential moving average of a series.
The recurrence is y[t] = a * x[t] + (1 - a) * y[t - 1] with
a = 2 / (window + 1), seeded so that y equals x at the
first finite sample. The first window - 1 samples after that
seed are reported as nan to match the rolling primitives. A
nan inside the series propagates to every later sample.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Series to filter. |
required |
window
|
Any
|
Span of the average. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The exponential moving average. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1. |
Source code in deap_er/private/programming/window_ops.py
add_pair_window_primitives(prim_set)
¶
Register the two-input causal window kit on a typed primitive set.
Every primitive takes two Array arguments and a Window and
returns an Array. All of them are causal: an output sample is a
function of that sample and earlier ones only, and samples without
enough history are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prim_set
|
PrimitiveSetTyped
|
Typed primitive set built by |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a primitive name collides with an argument of
|
Source code in deap_er/private/programming/window_pair.py
rolling_beta(left, right, window)
¶
Take the OLS slope of left on right over a trailing window.
The slope is the population covariance divided by the population
variance of right. A window where right is constant is
nan. The first window - 1 samples are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
Dependent series. |
required |
right
|
Any
|
Independent series. |
required |
window
|
Any
|
Trailing window length. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The rolling beta of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1, or if the operands are not one-dimensional series of the same length. |
Source code in deap_er/private/programming/window_pair.py
rolling_corr(left, right, window)
¶
Take the population correlation of two series over a trailing window.
The window is [t - window + 1, t] inclusive. A window where
either series has zero variance is nan. The first
window - 1 samples are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
First series. |
required |
right
|
Any
|
Second series. |
required |
window
|
Any
|
Trailing window length. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The rolling correlation. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1, or if the operands are not one-dimensional series of the same length. |
Source code in deap_er/private/programming/window_pair.py
rolling_cov(left, right, window)
¶
Take the population covariance of two series over a trailing window.
The window is [t - window + 1, t] inclusive and the divisor is
the window length. The first window - 1 samples are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
left
|
Any
|
First series. |
required |
right
|
Any
|
Second series. |
required |
window
|
Any
|
Trailing window length. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The rolling covariance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1, or if the operands are not one-dimensional series of the same length. |
Source code in deap_er/private/programming/window_pair.py
rolling_max(value, window)
¶
Take the maximum of a trailing window of a series.
The window is [t - window + 1, t] inclusive. A window that
holds a nan reduces to nan. The first window - 1
samples are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Series to reduce. |
required |
window
|
Any
|
Trailing window length. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The rolling maximum. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1. |
Source code in deap_er/private/programming/window_roll.py
rolling_mean(value, window)
¶
Average a trailing window of a series.
The window is [t - window + 1, t] inclusive. The first
window - 1 samples are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Series to reduce. |
required |
window
|
Any
|
Trailing window length. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The rolling mean. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1. |
Source code in deap_er/private/programming/window_roll.py
rolling_min(value, window)
¶
Take the minimum of a trailing window of a series.
The window is [t - window + 1, t] inclusive. A window that
holds a nan reduces to nan. The first window - 1
samples are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Series to reduce. |
required |
window
|
Any
|
Trailing window length. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The rolling minimum. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1. |
Source code in deap_er/private/programming/window_roll.py
rolling_std(value, window)
¶
Take the population standard deviation of a trailing window.
The window is [t - window + 1, t] inclusive and the divisor is
the window length. The first window - 1 samples are nan.
Each window is centered on its own mean before squaring, so the
result stays accurate however far the samples sit from zero. The
windows are centered in row blocks, which keeps peak memory
proportional to the block rather than to the whole series. A window
that holds an infinity is nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Series to reduce. |
required |
window
|
Any
|
Trailing window length. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The rolling standard deviation. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1. |
Source code in deap_er/private/programming/window_roll.py
rolling_sum(value, window)
¶
Sum a trailing window of a series.
The window is [t - window + 1, t] inclusive. The first
window - 1 samples are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Series to reduce. |
required |
window
|
Any
|
Trailing window length. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The rolling sum. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1. |
Source code in deap_er/private/programming/window_roll.py
delay(value, window)
¶
Shift a series into the past by window samples.
y[t] is x[t - window]. The first window samples have no
past to read and are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Series to shift. |
required |
window
|
Any
|
Number of samples to shift by. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The shifted series. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1. |
Source code in deap_er/private/programming/window_shift.py
diff(value, window)
¶
Subtract a delayed copy of a series from itself.
y[t] is x[t] - x[t - window]. The first window samples
are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Series to difference. |
required |
window
|
Any
|
Number of samples to look back. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The differenced series. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1. |
Source code in deap_er/private/programming/window_shift.py
add_ts_primitives(prim_set)
¶
Register the causal time-series unary kit on a typed primitive set.
Every primitive takes an Array and a Window and returns an
Array. All of them are causal: an output sample is a function
of that sample and earlier ones only, and samples without enough
history are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prim_set
|
PrimitiveSetTyped
|
Typed primitive set built by |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a primitive name collides with an argument of
|
Source code in deap_er/private/programming/window_ts.py
ts_argmax(value, window)
¶
Take how many samples ago the trailing-window maximum occurred.
The window is [t - window + 1, t] inclusive. 0 means the
current sample is the maximum. A tie keeps the most recent
maximum. A window that holds a nan is nan. The first
window - 1 samples are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Series to search. |
required |
window
|
Any
|
Trailing window length. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The age of the window maximum. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1. |
Source code in deap_er/private/programming/window_ts.py
ts_argmin(value, window)
¶
Take how many samples ago the trailing-window minimum occurred.
The window is [t - window + 1, t] inclusive. 0 means the
current sample is the minimum. A tie keeps the most recent
minimum. A window that holds a nan is nan. The first
window - 1 samples are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Series to search. |
required |
window
|
Any
|
Trailing window length. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The age of the window minimum. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1. |
Source code in deap_er/private/programming/window_ts.py
ts_rank(value, window)
¶
Take the percentile rank of the current sample in a trailing window.
The window is [t - window + 1, t] inclusive. The value is the
1-based average rank of x[t] among those samples, scaled by
(rank - 1) / (window - 1). A unique window low is 0.0, a
unique window high is 1.0, and an all-tie window is 0.5.
A window of 1 is nan. A window that holds a nan is
nan. The first window - 1 samples are nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Series to rank. |
required |
window
|
Any
|
Trailing window length. At least 1. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The rolling percentile rank. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the window length is less than 1. |
Source code in deap_er/private/programming/window_ts.py
affine_scale(predicted, target, *, valid=None)
¶
Fit Keijzer intercept and slope for a + b * f(x).
Least-squares a and b are computed on the same scorable
samples :func:~deap_er.tools.case_errors uses: an optional
valid= mask intersected with the finite check on both series.
Darwinian callers apply a + b * predicted only when writing
fitness or case errors; the tree is unchanged.
A series with no scorable samples returns the identity
(0.0, 1.0). A constant prediction returns an intercept-only
shift (mean(target) - mean(predicted), 1.0).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predicted
|
ndarray
|
Predicted series |
required |
target
|
ndarray
|
Target series, same length as |
required |
valid
|
ndarray | None
|
Optional per-sample mask. Same contract as
:func: |
None
|
Returns:
| Type | Description |
|---|---|
tuple[float, float]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the inputs are not aligned one-dimensional
arrays, or if |
Source code in deap_er/private/various/affine_scale.py
semantic_descriptors(matrix, *, kind='moments', valid=None, target=None, ranges=None, basis=None, center=None, empty=float('inf'), individuals=None, trust_matrix=False)
¶
Dispatch a semantic pack to moments, solve bits, or a projection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray | Sequence[Sequence[float]]
|
Semantic pack of shape |
required |
kind
|
DescriptorKind
|
|
'moments'
|
valid
|
ndarray | None
|
Optional per-row warmup mask of length |
None
|
target
|
ndarray | None
|
Target series. Required for |
None
|
ranges
|
Sequence[tuple[int, int]] | ndarray | None
|
Case bounds. Required for |
None
|
basis
|
ndarray | None
|
Projection matrix. Required for |
None
|
center
|
ndarray | None
|
Optional center passed to :func: |
None
|
empty
|
float
|
Empty-case MSE for |
float('inf')
|
individuals
|
Sequence[Any] | None
|
Optional population used by |
None
|
trust_matrix
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Descriptor array whose width depends on |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/semantic_descriptors.py
semantic_moments(matrix, *, valid=None, individuals=None, trust_matrix=False)
¶
Return per-individual mean, population std, min, and max.
Moments use samples where valid (broadcast) and the row are
finite. An empty row is all-NaN. A single sample has std = 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray | Sequence[Sequence[float]]
|
Semantic pack of shape |
required |
valid
|
ndarray | None
|
Optional per-row warmup mask of length |
None
|
individuals
|
Sequence[Any] | None
|
Optional population used by |
None
|
trust_matrix
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Descriptor array of shape |
Source code in deap_er/private/various/semantic_descriptors.py
semantic_solve_bits(matrix, target, ranges, *, valid=None, empty=float('inf'), individuals=None, trust_matrix=False)
¶
Return one solved-case bit per individual and case.
A case is solved when its MSE is isclose to 0 with
abs_tol=1e-12, matching :func:~deap_er.tools.sample_informed_cases.
Segment bounds and valid= follow :func:~deap_er.tools.case_errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray | Sequence[Sequence[float]]
|
Predicted pack of shape |
required |
target
|
ndarray
|
Target series of length |
required |
ranges
|
Sequence[tuple[int, int]] | ndarray
|
Case bounds accepted by :func: |
required |
valid
|
ndarray | None
|
Optional per-row warmup mask of length |
None
|
empty
|
float
|
MSE used when a case has no scorable samples. |
float('inf')
|
individuals
|
Sequence[Any] | None
|
Optional population used by |
None
|
trust_matrix
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Float |
Source code in deap_er/private/various/semantic_descriptors.py
semantic_distance(query, matrix, *, metric='euclidean', valid=None)
¶
Return finite-mask distances from query to each packed row.
Only coordinates that are finite on both sides and marked valid
enter the distance. An empty overlap, or a zero cosine norm, is
+inf. A one-dimensional matrix is treated as a single row
and still returns a length-1 array (not a Python float) so the
return type stays ndarray for the type checker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
ndarray | Sequence[float]
|
Semantic row of length |
required |
matrix
|
ndarray | Sequence[Sequence[float]] | Sequence[float]
|
Pack of shape |
required |
metric
|
SemanticMetric
|
|
'euclidean'
|
valid
|
ndarray | None
|
Optional per-row warmup mask of length |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Distances of length |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes do not match or |
Source code in deap_er/private/various/semantic_neighbors.py
semantic_nearest(query, matrix, *, k=1, metric='euclidean', valid=None, individuals=None, trust_matrix=False)
¶
Return the lowest-index nearest neighbors of query.
Infinite distances are skipped. Ties keep the lowest pack index.
individuals is trust-alignment only: the return value is always
integer pack indices, never the individual objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
ndarray | Sequence[float]
|
Semantic row of length |
required |
matrix
|
ndarray | Sequence[Sequence[float]]
|
Pack of shape |
required |
k
|
int
|
Maximum number of neighbors to return. |
1
|
metric
|
SemanticMetric
|
|
'euclidean'
|
valid
|
ndarray | None
|
Optional per-row warmup mask of length |
None
|
individuals
|
Sequence[Any] | None
|
Optional population used by |
None
|
trust_matrix
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Neighbor indices in increasing distance order, length at most |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/semantic_neighbors.py
semantic_pca_basis(matrix, n_dims, *, valid=None, target=None)
¶
Return a thin-SVD basis and column center for :func:semantic_project.
Columns outside valid (and non-finite target samples) are
dropped before centering. Unused rows of the returned basis and
center are zero.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray | Sequence[Sequence[float]]
|
Semantic pack of shape |
required |
n_dims
|
int
|
Number of components to keep. |
required |
valid
|
ndarray | None
|
Optional per-row warmup mask of length |
None
|
target
|
ndarray | None
|
Optional target whose non-finite samples are dropped. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/semantic_project.py
semantic_project(matrix, basis, *, valid=None, target=None, center=None, individuals=None, trust_matrix=False)
¶
Project a semantic pack through a caller-supplied basis.
Columns outside valid (and non-finite target samples) are
zeroed so warmup does not enter the product. A row that is still
non-finite on a kept column yields a non-finite descriptor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray | Sequence[Sequence[float]]
|
Semantic pack of shape |
required |
basis
|
ndarray
|
Projection matrix of shape |
required |
valid
|
ndarray | None
|
Optional per-row warmup mask of length |
None
|
target
|
ndarray | None
|
Optional target whose non-finite samples are dropped. |
None
|
center
|
ndarray | None
|
Optional length- |
None
|
individuals
|
Sequence[Any] | None
|
Optional population used by |
None
|
trust_matrix
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Descriptor array of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/semantic_project.py
semantic_random_basis(n_rows, n_dims)
¶
Return a Gaussian random-projection basis.
Columns are scaled by 1 / sqrt(n_dims). Draws use the process
:data:~deap_er.tools.rng.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_rows
|
int
|
Number of semantic coordinates (rows of the pack). |
required |
n_dims
|
int
|
Number of projected dimensions. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Basis of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |