Utilities¶
various
¶
affine_case_errors
¶
affine_case_errors(predicted, target, ranges, *, valid=None, empty=float('inf'))
¶
Return Keijzer-scaled case errors without changing the tree.
Fits \(a + b\,f(x)\) with :func:~deap_er.tools.affine_scale on the
same valid= mask :func:~deap_er.tools.case_errors uses, applies
the scaled series, then reduces to one MSE per case. This is the
Darwinian default next to Lamarckian
:func:~deap_er.gp.write_affine_scale.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predicted
|
ndarray
|
Predicted series |
required |
target
|
ndarray
|
Target series, same length as |
required |
ranges
|
Sequence[tuple[int, int]] | ndarray
|
Case bounds forwarded to :func: |
required |
valid
|
ndarray | None
|
Optional per-sample mask forwarded to both helpers. |
None
|
empty
|
float
|
Value returned when a case has no scorable samples. |
float('inf')
|
Returns:
| Type | Description |
|---|---|
tuple[float, ...]
|
One MSE per case, in range order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the inputs are not aligned one-dimensional
arrays or if |
Source code in deap_er/private/various/affine_case_errors.py
affine_scale
¶
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
bin2float
¶
bin2float(min_, max_, n_bits)
¶
Return a decorator that decodes a binary individual to floats.
Each float uses n_bits bits and is mapped into
[min_, max_]. The decorated function receives the decoded
float array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_
|
float
|
Lower bound of each decoded value. |
required |
max_
|
float
|
Upper bound of each decoded value. |
required |
n_bits
|
int
|
Bits used to encode each float. |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., Any]
|
A decorator for an evaluation function. |
Source code in deap_er/private/various/bin2float.py
case_bounds
¶
ranges_from_mask(mask, length)
¶
Split a boolean mask into one half-open range per True run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
ndarray
|
One-dimensional |
required |
length
|
int
|
Expected mask length. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[int, int]]
|
Contiguous |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/case_bounds.py
normalize_case_ranges(ranges, length)
¶
Normalize ranges or a mask into validated half-open intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ranges
|
Sequence[tuple[int, int]] | ndarray
|
|
required |
length
|
int
|
Exclusive upper bound for endpoints, or the mask length. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[int, int]]
|
Validated |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a range or mask is invalid. |
Source code in deap_er/private/various/case_bounds.py
mask_from_ranges(ranges, length)
¶
Paint validated ranges onto a boolean mask of length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ranges
|
Sequence[tuple[int, int]] | ndarray
|
The same range or mask input as |
required |
length
|
int
|
Length of the returned mask. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A 1-D |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a range or mask is invalid. |
Source code in deap_er/private/various/case_bounds.py
case_errors
¶
case_intervals(ranges, length)
¶
Normalize case bounds to half-open [start, stop) intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ranges
|
Sequence[tuple[int, int]] | ndarray
|
Explicit |
required |
length
|
int
|
Length of the series the intervals index. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[int, int]]
|
Half-open intervals in caller order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a bound is invalid or a mask has the wrong shape or dtype. |
Source code in deap_er/private/various/case_errors.py
case_valid_mask(predicted, target, valid=None)
¶
Return the one-dimensional sample mask used by :func:case_errors.
An optional caller mask is intersected with the finite check on both
series. A True in valid that is non-finite on either series
stays out of the mask.
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. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
One-dimensional |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/case_errors.py
case_errors(predicted, target, ranges, *, valid=None, empty=float('inf'))
¶
Return one mean-squared error per case segment.
Each case is a half-open interval [start, stop) over aligned
predicted and target series. Only samples marked valid inside
the interval are scored. By default a sample is valid when both series
are finite at that index.
Pass an explicit valid mask when comparisons or vwhere can
hide a nan warmup while the prediction stays finite. That mask is
intersected with the finite check, so non-finite samples never enter
the MSE even when valid marks them True. Segment boundaries
stay on the caller; this helper does not split a series
chronologically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predicted
|
ndarray
|
Predicted series. |
required |
target
|
ndarray
|
Target series, same length as |
required |
ranges
|
Sequence[tuple[int, int]] | ndarray
|
A sequence of |
required |
valid
|
ndarray | None
|
Optional per-sample mask intersected with the finite check. Use it to drop trusted prefixes such as hidden warmup. |
None
|
empty
|
float
|
Value returned when a case has no scorable samples. |
float('inf')
|
Returns:
| Type | Description |
|---|---|
tuple[float, ...]
|
One MSE per case, in range order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the inputs are not aligned one-dimensional arrays, if range endpoints are invalid, or if a mask has the wrong shape or dtype. |
Source code in deap_er/private/various/case_errors.py
case_generalization
¶
CaseGeneralizationRecipe(pool, train_cases, held_cases, n_cases)
dataclass
¶
Wiring for the default case-structured generalization path.
Attributes:
| Name | Type | Description |
|---|---|---|
pool |
CaseExamPool
|
Train and held-out exams. |
train_cases |
tuple[int, ...]
|
Train catalog indices. |
held_cases |
tuple[int, ...]
|
Held-out catalog indices, or |
n_cases |
int
|
Catalog length. |
make_select(*, downsample=None, downsample_mode='informed')
¶
Return a lexicase selector on :attr:train_cases only.
Source code in deap_er/private/various/case_generalization.py
held_out_tail(n_cases, fraction=0.2)
¶
Return catalog indices for the last fraction of cases.
Chronological meaning stays on the caller. This helper only picks trailing catalog indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_cases
|
int
|
Catalog length. |
required |
fraction
|
float
|
Held-out share in |
0.2
|
Returns:
| Type | Description |
|---|---|
list[int]
|
Ascending held-out indices. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/case_generalization.py
train_head(n_cases, fraction=0.2)
¶
Return train catalog indices complementary to :func:held_out_tail.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_cases
|
int
|
Catalog length. |
required |
fraction
|
float
|
Held-out share in |
0.2
|
Returns:
| Type | Description |
|---|---|
list[int]
|
Ascending train indices. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/case_generalization.py
case_generalization_pool(n_cases, *, fraction=0.2, held_cases=None)
¶
Build a pool with one train exam and a caller-marked held-out exam.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_cases
|
int
|
Catalog length. |
required |
fraction
|
float
|
Held-out share when |
0.2
|
held_cases
|
Sequence[int] | None
|
Optional explicit held-out catalog indices. |
None
|
Returns:
| Type | Description |
|---|---|
CaseExamPool
|
A pool whose train exam excludes |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
IndexError
|
If a held-out index is out of range. |
Source code in deap_er/private/various/case_generalization.py
make_lexicase_train_select(pool, n_cases, *, downsample=None, downsample_mode='informed')
¶
Return a toolbox.select callable that runs lexicase on train cases.
Held-out catalog indices from pool.held_out are never passed to
lexicase. Chronological meaning stays on the caller.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pool
|
CaseExamPool
|
Exam pool with a train exam and optional |
required |
n_cases
|
int
|
Catalog length for |
required |
downsample
|
int | None
|
When set, cap the active case count each generation
via :func: |
None
|
downsample_mode
|
DownsampleMode
|
Downsample mode when |
'informed'
|
Returns:
| Type | Description |
|---|---|
Callable[[list[Individual], int], list[Individual]]
|
A selection callable |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the pool has no train exams. |
Source code in deap_er/private/various/case_generalization.py
case_generalization_recipe(n_cases, *, fraction=0.2, held_cases=None)
¶
Build the held-out pool and catalog indices for item 41.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_cases
|
int
|
Catalog length. |
required |
fraction
|
float
|
Held-out share when |
0.2
|
held_cases
|
Sequence[int] | None
|
Optional explicit held-out catalog indices. |
None
|
Returns:
| Type | Description |
|---|---|
CaseGeneralizationRecipe
|
A recipe with |
Source code in deap_er/private/various/case_generalization.py
case_halving
¶
CaseHalvingResult(survivors, nevals, stages_run)
dataclass
¶
Outcome of :func:evaluate_case_halving.
Attributes:
| Name | Type | Description |
|---|---|---|
survivors |
list[Individual]
|
Individuals that reached the final rung. |
nevals |
int
|
Case-eval units charged across all rungs. |
stages_run |
int
|
Number of rungs executed. |
case_eval_charge(n_individuals, n_cases)
¶
Return case-eval units for budget accounting.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_individuals
|
int
|
Individuals scored at one rung. |
required |
n_cases
|
int
|
Cases scored per individual. |
required |
Returns:
| Type | Description |
|---|---|
int
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If either count is negative. |
Source code in deap_er/private/various/case_halving.py
case_halving_stages(n_train_cases, *, eta=2, min_cases=1)
¶
Return successive-halving rung sizes up to n_train_cases.
Each rung uses the first stage_n entries of the caller's
train_cases list. Sizes grow geometrically by eta from
min_cases until the full train count is reached.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_train_cases
|
int
|
Number of train catalog indices. |
required |
eta
|
int
|
Elimination factor and geometric growth base. Must be
at least |
2
|
min_cases
|
int
|
Smallest rung size. Must be at least |
1
|
Returns:
| Type | Description |
|---|---|
tuple[int, ...]
|
Distinct ascending rung sizes ending at |
Raises:
| Type | Description |
|---|---|
ValueError
|
If inputs are invalid. |
Source code in deap_er/private/various/case_halving.py
subset_evaluate_cases(evaluate)
¶
Wrap a full-catalog evaluate for partial case scoring.
The wrapped callable still invokes evaluate on the full catalog.
For true cheap subsets, pass a custom evaluate_cases that calls
evaluate_columnar(..., cases=...) or an equivalent partial scorer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
evaluate
|
Callable[[Individual], Sequence[float]]
|
Full-catalog fitness callable. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[Individual, Sequence[int]], Sequence[float]]
|
|
Source code in deap_er/private/various/case_halving.py
evaluate_case_halving(individuals, evaluate_cases, train_cases, *, n_cases, eta=2, min_cases=1, weights=None, evaluate_full=None)
¶
Run successive halving on train catalog indices.
Intermediate rungs rank individuals on prefixes of train_cases
without writing fitness.values. The final rung assigns a
full-catalog fitness tuple of length n_cases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individuals
|
Sequence[Individual]
|
Candidates to score and filter. |
required |
evaluate_cases
|
Callable[[Individual, Sequence[int]], Sequence[float]]
|
|
required |
train_cases
|
Sequence[int]
|
Train catalog indices in caller order. |
required |
n_cases
|
int
|
Full catalog length for final |
required |
eta
|
int
|
Elimination factor between rungs. |
2
|
min_cases
|
int
|
Smallest rung size. |
1
|
weights
|
Sequence[float] | None
|
Optional per-catalog weights for ranking means. |
None
|
evaluate_full
|
Callable[[Individual], Sequence[float]] | None
|
Optional full-catalog scorer for the final
rung. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
CaseHalvingResult
|
Survivors, total case-eval charge, and rung count. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/case_halving.py
clone
¶
clone_individual(individual)
¶
Copy a sequence individual and its fitness without a full deepcopy.
Register this on a Toolbox when a shallow gene copy is enough:
toolbox.register("clone", tools.clone_individual). Falls back to
copy.deepcopy when the individual is a NumPy array or carries
extra state such as strategy, ps_, or history_index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
Individual
|
Individual to copy. |
required |
Returns:
| Type | Description |
|---|---|
Individual
|
An independent copy of |
Source code in deap_er/private/various/clone.py
constraints
¶
DeltaPenalty(feasibility, delta, distance=None)
¶
Decorator that penalizes fitness of invalid individuals.
Valid individuals keep the original fitness. Invalid ones receive
delta plus an optional distance penalty that grows as the
individual moves away from the valid region.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feasibility
|
Callable[..., Any]
|
Function that reports whether an individual is valid. |
required |
delta
|
NumOrSeq
|
Constant or sequence of constants used as the base penalty for an invalid individual. |
required |
distance
|
Callable[..., Any] | None
|
Optional function returning the distance between the individual and a valid point. |
None
|
See the class docstring.
Source code in deap_er/private/various/constraints.py
__call__(func)
¶
Wrap a fitness function with the delta penalty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
Fitness function to decorate. |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., Any]
|
A callable that returns the original fitness for valid |
Callable[..., Any]
|
individuals and the penalized fitness otherwise. |
Source code in deap_er/private/various/constraints.py
ClosestValidPenalty(validity, feasible, alpha, distance=None)
¶
Decorator that penalizes fitness of invalid individuals.
Valid individuals keep the original fitness. Invalid ones receive the fitness of the closest valid individual plus an optional weighted distance penalty that grows as the individual moves away from the valid region.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
validity
|
Callable[..., Any]
|
Function that reports whether an individual is valid. |
required |
feasible
|
Callable[..., Any]
|
Function that returns the closest feasible individual for an invalid one. |
required |
alpha
|
float
|
Multiplication factor on the distance between the valid and invalid individuals. |
required |
distance
|
Callable[..., Any] | None
|
Optional function returning the distance between the individual and a valid point. |
None
|
See the class docstring.
Source code in deap_er/private/various/constraints.py
__call__(func)
¶
Wrap a fitness function with the closest-valid penalty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
Fitness function to decorate. |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., Any]
|
A callable that returns the original fitness for valid |
Callable[..., Any]
|
individuals and the penalized fitness otherwise. |
Source code in deap_er/private/various/constraints.py
decorators
¶
Translation(vector)
¶
Decorator that translates an individual before evaluation.
The decorated function receives a plain list of translated values.
After decoration, func.translate updates the translation vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector
|
list[float]
|
Translation values. Must have the same length as the individual. |
required |
See the class docstring.
Source code in deap_er/private/various/decorators.py
__call__(func)
¶
Wrap an evaluation function with the translation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
Evaluation function to decorate. |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., Any]
|
A callable that translates the individual, then calls |
Callable[..., Any]
|
|
Source code in deap_er/private/various/decorators.py
translate(vector)
¶
Update the translation vector.
After decorating the evaluation function, this method is available on the function object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector
|
list[float]
|
The translation vector. |
required |
Source code in deap_er/private/various/decorators.py
Rotation(matrix)
¶
Decorator that rotates an individual before evaluation.
The decorated function receives a plain ndarray of rotated values.
After decoration, func.rotate updates the rotation matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray
|
Orthogonal N-by-N rotation matrix, where N is the length of the individual. |
required |
See the class docstring.
Source code in deap_er/private/various/decorators.py
__call__(func)
¶
Wrap an evaluation function with the rotation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
Evaluation function to decorate. |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., Any]
|
A callable that rotates the individual, then calls |
Callable[..., Any]
|
|
Source code in deap_er/private/various/decorators.py
rotate(matrix)
¶
Update the rotation matrix.
After decorating the evaluation function, this method is available on the function object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray
|
The rotation matrix. |
required |
Source code in deap_er/private/various/decorators.py
Scaling(factor)
¶
Decorator that scales an individual before evaluation.
The decorated function receives a plain list of scaled values.
After decoration, func.scale updates the scale factors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor
|
list[float]
|
Scale factors. Must have the same length as the individual. |
required |
See the class docstring.
Source code in deap_er/private/various/decorators.py
__call__(func)
¶
Wrap an evaluation function with the scaling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
Evaluation function to decorate. |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., Any]
|
A callable that scales the individual, then calls |
Callable[..., Any]
|
|
Source code in deap_er/private/various/decorators.py
scale(factor)
¶
Update the scale factors.
After decorating the evaluation function, this method is available on the function object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factor
|
list[float]
|
The scale factor. |
required |
Source code in deap_er/private/various/decorators.py
Noise(funcs)
¶
Decorator that adds noise to an evaluation result.
Each noise generator is called without arguments. After
decoration, func.add_noise updates the generators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
funcs
|
Callable[..., Any] | list[Callable[..., Any] | None]
|
Noise generator callables. A single callable is
applied to every result value. A list must match the
result length. A |
required |
See the class docstring.
Source code in deap_er/private/various/decorators.py
__call__(func)
¶
Wrap an evaluation function with noise on its result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[..., Any]
|
Evaluation function to decorate. |
required |
Returns:
| Type | Description |
|---|---|
Callable[..., Any]
|
A callable that calls |
Callable[..., Any]
|
result. The wrapper has an |
Source code in deap_er/private/various/decorators.py
add_noise(funcs)
¶
Update the noise generators.
After decorating the evaluation function, this method is available on the function object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
funcs
|
Callable[..., Any] | list[Callable[..., Any] | None]
|
The noise function or functions. |
required |
Source code in deap_er/private/various/decorators.py
eval_cache
¶
EvalCache(evaluate=None, evaluate_batch=None, *, matrix=None, key_fn=None)
¶
Fitness cache keyed by expression plus matrix identity / rows.
Wrap the caller's evaluate / evaluate_batch. A hit returns
the stored fitness tuple and does not call the wrapped callable.
The default expression key is tree structure via
expression_key, source text, or str(individual). Pass
key= (or keys= on a batch) to override.
Live instances register with the process-wide invalidation hook:
clear_compile_cache clears every cache; invalidate_compiled
drops keys for that expression. promote_subtree and
tune_ephemerals already call those helpers, so a language
mutation or ephemeral write-back cannot keep a stale fitness.
n_evals and logbook nevals still count every fitness
assignment through evaluate_invalid. A cache hit skips the
wrapped callable only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
evaluate
|
Callable[[Any], Any] | None
|
Optional |
None
|
evaluate_batch
|
Callable[[list[Any]], Any] | None
|
Optional |
None
|
matrix
|
Any
|
Evaluation matrix whose identity and row count join
the key. |
None
|
key_fn
|
Callable[[Any], Any] | None
|
Optional |
None
|
See the class docstring.
Source code in deap_er/private/various/eval_cache.py
cache_key(individual, caller_key=None)
¶
Build the key for individual on the current matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
Any
|
Individual or expression being scored. |
required |
caller_key
|
Any
|
Optional explicit key. Overrides |
None
|
Returns:
| Type | Description |
|---|---|
CacheKey
|
|
Source code in deap_er/private/various/eval_cache.py
evaluate(individual, *, key=None)
¶
Return cached fitness or pay evaluate on a miss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individual
|
Any
|
Individual to score. |
required |
key
|
Any
|
Optional caller key for this call. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The fitness tuple from the cache or from |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no |
Source code in deap_er/private/various/eval_cache.py
evaluate_batch(individuals, *, keys=None)
¶
Score a batch, calling evaluate_batch only for misses.
When evaluate_batch is omitted, each miss uses evaluate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individuals
|
Sequence[Any]
|
Individuals to score, in caller order. |
required |
keys
|
Sequence[Any] | None
|
Optional per-individual caller keys. |
None
|
Returns:
| Type | Description |
|---|---|
list[Any]
|
Fitness tuples aligned with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither wrapped callable is set. |
ValueError
|
If |
Source code in deap_er/private/various/eval_cache.py
invalidate(expr)
¶
Drop entries whose expression fragment names expr.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Any
|
|
required |
Returns:
| Type | Description |
|---|---|
int
|
The number of entries removed. |
Source code in deap_er/private/various/eval_cache.py
clear()
¶
clear_eval_caches()
¶
Drop every entry from each live :class:EvalCache.
clear_compile_cache calls this so promote_subtree (and any
other language mutation) cannot leave stale fitness next to a
dropped compile-cache table.
Source code in deap_er/private/various/eval_cache.py
invalidate_eval(expr)
¶
Drop matching expression keys from every live :class:EvalCache.
Uses the same fragment as invalidate_compiled: a structural
tree key, raw source text, or the historical lambda …: {expr}
form. tune_ephemerals reaches this through
invalidate_compiled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Any
|
Expression whose cached fitness should be evicted. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The number of cache entries removed across all live caches. |
Source code in deap_er/private/various/eval_cache.py
fitness_race
¶
RaceStopResult(survivors, nevals, rounds)
dataclass
¶
Outcome of :func:race_stop.
Attributes:
| Name | Type | Description |
|---|---|---|
survivors |
list[Individual]
|
Individuals that survived every racing round. |
nevals |
int
|
Evaluate or cache calls charged across all rounds. |
rounds |
int
|
Number of resample rounds executed. |
race_eval_charge(n_individuals, n_draws=1)
¶
Return evaluation units for one racing round.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_individuals
|
int
|
Survivors scored in the round. |
required |
n_draws
|
int
|
Draws per individual (default one). |
1
|
Returns:
| Type | Description |
|---|---|
int
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If either count is negative. |
Source code in deap_er/private/various/fitness_race.py
race_z_score(alpha)
¶
Map a significance level to an approximate normal critical value.
Source code in deap_er/private/various/fitness_race.py
score_draw(individual, evaluate, *, cache, key_fn, draw)
¶
Score one draw for individual through cache or evaluate.
Source code in deap_er/private/various/fitness_race.py
objective_score(values, objective, maximize)
¶
Return a scalar for ranking on one objective.
Source code in deap_er/private/various/fitness_race.py
sample_mean_std(samples, objective)
¶
Return the sample mean and standard error on one objective.
Source code in deap_er/private/various/fitness_race.py
maximize_first_objective(individuals)
¶
Return whether the first fitness objective is maximized.
Source code in deap_er/private/various/fitness_race.py
challenger_is_not_worse(challenger_mean, challenger_se, leader_mean, leader_se, *, z_score, maximize)
¶
Return whether a challenger is not confidently worse than the leader.
Source code in deap_er/private/various/fitness_race.py
keep_challenger_after_race(challenger_samples, leader_mean, leader_se, *, z_score, maximize)
¶
Return whether a challenger survives comparison with the leader.
Source code in deap_er/private/various/fitness_race.py
restore_min_survivors(kept, ranked, min_survivors)
¶
Add back ranked challengers until min_survivors is met.
Source code in deap_er/private/various/fitness_race.py
eliminate_losers(survivors, samples, *, aggregate, alpha, maximize, min_survivors)
¶
Drop challengers whose first objective is significantly worse.
Source code in deap_er/private/various/fitness_race.py
race_stop(individuals, evaluate, n_rounds, *, cache=None, key_fn=None, alpha=0.05, min_survivors=1, aggregate=resample_aggregate, write=False)
¶
Run an F-Race-shaped stop on noisy fitness draws.
Each round adds one resample per survivor. After the second round,
challengers whose first objective is significantly worse than the
current leader are dropped. Samples are tracked by id(individual);
clones share one history unless they are distinct objects.
Multi-objective racing uses objective zero only. evaluate stays
on the caller; this helper does not build a domain metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individuals
|
Sequence[Individual]
|
Candidates to race. |
required |
evaluate
|
Callable[[Individual], Sequence[float]]
|
One-draw fitness callable. |
required |
n_rounds
|
int
|
Maximum resample rounds. |
required |
cache
|
EvalCache | None
|
Optional :class: |
None
|
key_fn
|
Callable[[Individual], Any] | None
|
Optional per-individual cache key fragment. |
None
|
alpha
|
float
|
Significance level mapped to a normal critical value. |
0.05
|
min_survivors
|
int
|
Stop eliminating below this count. |
1
|
aggregate
|
Callable[[Sequence[Sequence[float]]], Sequence[float]]
|
Reduces each individual's draw list to one tuple. |
resample_aggregate
|
write
|
bool
|
When true, write the final aggregate to |
False
|
Returns:
| Type | Description |
|---|---|
RaceStopResult
|
Survivors, total evaluate calls, and rounds executed. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/fitness_race.py
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | |
fitness_resample
¶
noisy_draw_key(base, draw)
¶
Return a hashable :class:EvalCache caller key that includes the draw.
A noisy evaluate must vary the cache key per draw. Without a
per-draw key, EvalCache returns the first draw for every repeat.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
Any
|
Caller-owned expression or matrix identity fragment. |
required |
draw
|
int
|
Zero-based resample index. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Any, int]
|
|
Source code in deap_er/private/various/fitness_resample.py
resample_aggregate(samples)
¶
Average per-objective samples, skipping non-finite values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
samples
|
Sequence[Sequence[float]]
|
Fitness tuples from independent draws. |
required |
Returns:
| Type | Description |
|---|---|
tuple[float, ...]
|
Elementwise means across |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/fitness_resample.py
resample(ind, evaluate, n, *, cache=None, key=None, aggregate=resample_aggregate, write=True)
¶
Score one individual n times and aggregate the noisy draws.
Each repeat goes through cache when it is set. Pass
:func:noisy_draw_key (or an equivalent draw-specific key) so
independent draws do not share one cache entry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ind
|
Individual
|
Individual to score. |
required |
evaluate
|
Callable[[Individual], Sequence[float]]
|
Callable that returns one fitness tuple per draw. |
required |
n
|
int
|
Number of independent draws. Must be at least |
required |
cache
|
EvalCache | None
|
Optional :class: |
None
|
key
|
Any
|
Optional caller key fragment paired with each draw index. |
None
|
aggregate
|
Callable[[Sequence[Sequence[float]]], Sequence[float]]
|
Reduces draw tuples to one fitness tuple. |
resample_aggregate
|
write
|
bool
|
When true, assign the aggregate to |
True
|
Returns:
| Type | Description |
|---|---|
tuple[float, ...]
|
The aggregated fitness tuple. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/fitness_resample.py
hypervolume
¶
minimized_points(population)
¶
Return objective rows in minimization space (-wvalues).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
population
|
list[Any]
|
Individuals with a Fitness attribute. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A 2-D array of points, or shape |
ndarray
|
is empty. |
Source code in deap_er/private/various/hypervolume.py
has_fitness(obj)
¶
Return whether obj looks like an individual with Fitness.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
object
|
Value to inspect. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if |
Source code in deap_er/private/various/hypervolume.py
hypervolume(points, ref_point=None)
¶
Return the hypervolume of a point set or a population.
Minimization is assumed. An individual or a sequence of
individuals is converted via -wvalues. A bare point matrix
(no fitness) is used as-is. ref_point is in that same
space. Delegates to moocore.hypervolume.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
ndarray | list[Individual] | Individual
|
Minimized objective rows, one individual, or a population with Fitness. |
required |
ref_point
|
ndarray | list[float] | None
|
Reference point. Optional. If omitted, the worst value of each objective plus one is used. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
The hypervolume of the point set. |
Source code in deap_er/private/various/hypervolume.py
initializers
¶
init_repeat(container, func, size)
¶
Call func size times and store the results in container.
Use with a Toolbox to register a generator of filled containers, such as individuals or a population.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
container
|
Callable[..., Any]
|
Callable that takes an iterable and returns a collection. |
required |
func
|
Callable[..., Any]
|
Function called once per element. |
required |
size
|
int
|
Number of times to call |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A collection filled with |
Source code in deap_er/private/various/initializers.py
init_iterate(container, generator)
¶
Call generator and store its results in container.
generator must return an iterable. Use with a Toolbox to
register a generator of filled containers, as individuals or a
population.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
container
|
Callable[..., Any]
|
Callable that takes an iterable and returns a collection. |
required |
generator
|
Callable[..., Any]
|
Function that returns the iterable used to fill the container. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
A collection filled with the results of |
Source code in deap_er/private/various/initializers.py
init_cycle(container, funcs, size=1)
¶
Call each function in funcs size times and store all results.
Use with a Toolbox to register a generator of filled containers, as individuals or a population.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
container
|
Callable[..., Any]
|
Callable that takes an iterable and returns a collection. |
required |
funcs
|
Iterable[Callable[..., Any]]
|
Sequence of functions to call. |
required |
size
|
int
|
Number of times to iterate through |
1
|
Returns:
| Type | Description |
|---|---|
Any
|
A collection filled with the results of all function calls. |
Source code in deap_er/private/various/initializers.py
least_contrib
¶
least_contrib(population, ref_point=None)
¶
Return the index of the individual with the least hypervolume contribution.
Minimization is implicitly assumed. ref_point is interpreted in
that same space (after wvalues are negated). Delegates to
moocore.hv_contributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
population
|
list[Individual]
|
Non-dominated individuals, each with a Fitness attribute. |
required |
ref_point
|
list[float] | ndarray | None
|
Reference point for the hypervolume. Optional. If omitted, the worst value of each objective plus one is used. |
None
|
Returns:
| Type | Description |
|---|---|
int
|
The index of the individual with the least hypervolume |
int
|
contribution. The first index wins when contributions tie. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/least_contrib.py
metrics
¶
duplicate_count(population, key=None)
¶
Return how many individuals are duplicates of an earlier one.
Hashable keys use a set scan in O(n). Unhashable but sortable keys
use a sort in O(n log n). Keys that are neither hashable nor
mutually sortable fall back to list membership in O(n^2).
A NumPy array key is hashed by shape, dtype, and bytes so ndarray
individuals take the set path.
Hashable keys must satisfy Python's hash/equality contract: equal keys
must hash equally. The set path counts by hash bucket; equal keys with
unequal hashes are treated as distinct (unlike a pure == scan).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
population
|
list[Any]
|
Individuals to scan. |
required |
key
|
Any | None
|
Extracts the compared value. Defaults to the identity. |
None
|
Returns:
| Type | Description |
|---|---|
int
|
|
Source code in deap_er/private/various/metrics.py
nsga_diversity(population, first, last)
¶
Return the NSGA-II diversity metric of a Pareto front.
population is the front to score. first and last are
the extreme points of the optimal Pareto front, as in Deb's
original NSGA-II article. Each extreme may be an individual
(objectives from fitness.values) or a raw objective vector.
Smaller values indicate better spread. An empty front returns
1.0, the same value as a single point or a collapsed front.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
population
|
list[Individual]
|
Pareto front to evaluate. |
required |
first
|
Individual
|
First extreme point of the optimal Pareto front. |
required |
last
|
Individual
|
Last extreme point of the optimal Pareto front. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The diversity metric of the front. |
Source code in deap_er/private/various/metrics.py
nsga_convergence(population, optimal)
¶
Return the NSGA-II convergence metric of a Pareto front.
population is the front to score and optimal is the true
Pareto front, as in Deb's original NSGA-II article. Each reference
point may be an individual or a raw objective vector. Smaller
values indicate closer solutions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
population
|
list[Individual]
|
Pareto front to evaluate. |
required |
optimal
|
list[Individual]
|
Optimal Pareto front. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The convergence metric of the front. An empty population |
float
|
or empty |
Source code in deap_er/private/various/metrics.py
inv_gen_dist(ind1, ind2)
¶
Compute the inverted generational distance between two point sets.
IGD measures how well one approximation covers another in multi-objective optimization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ind1
|
Individual
|
First point set. |
required |
ind2
|
Individual
|
Second point set. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The average distance from each point in |
Any
|
nearest point in |
Any
|
returns |
Source code in deap_er/private/various/metrics.py
policy_observe
¶
policy_solve_bits_from_errors(errors)
¶
Build observation solve bits from :func:~deap_er.tools.case_errors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
errors
|
tuple[float, ...]
|
One MSE per case segment. |
required |
Returns:
| Type | Description |
|---|---|
tuple[int, ...]
|
|
Source code in deap_er/private/various/policy_observe.py
policy_solve_bits_from_fitness(values)
¶
Build observation solve bits from per-case fitness values.
Uses the same zero threshold as lexicase and
:func:~deap_er.tools.score_case_exams.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
tuple[float, ...]
|
One fitness value per catalog case. |
required |
Returns:
| Type | Description |
|---|---|
tuple[int, ...]
|
|
Source code in deap_er/private/various/policy_observe.py
policy_solve_bits_from_semantic_row(row)
¶
Coerce one row of :func:~deap_er.gp.semantic_solve_bits output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row
|
Sequence[float]
|
One individual's solve-bit row as a plain sequence. |
required |
Returns:
| Type | Description |
|---|---|
tuple[int, ...]
|
|
Source code in deap_er/private/various/policy_observe.py
policy_unsolved_count(solve_bits)
¶
Count cases not solved in a solve-bit tuple.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
solve_bits
|
Sequence[int]
|
Per-case |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of zeros in |
Source code in deap_er/private/various/policy_observe.py
policy_exam_scores(exams, elites, *, held_out=None)
¶
Reduce :func:~deap_er.tools.score_case_exams to train / held-out scalars.
Train exams are every exam in exams when it is a sequence. When
exams is a :class:~deap_er.records.CaseExamPool, train scores
use pool.exams and pool.held_out unless held_out overrides
the pool marker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exams
|
Sequence[CaseExam] | CaseExamPool
|
Train exams or a pool with an optional held-out exam. |
required |
elites
|
list[Individual]
|
Evaluated individuals that supply the case pack. |
required |
held_out
|
CaseExam | None
|
Optional held-out exam that overrides a pool marker. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
|
float | None
|
sum of train-exam difficulties and |
tuple[float, float | None]
|
held-out difficulty or |
Source code in deap_er/private/various/policy_observe.py
policy_promoted_library_size(prim_set)
¶
Return the promoted-library size for observation fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prim_set
|
PrimitiveSetTyped
|
Primitive set that may hold a promoted library. |
required |
Returns:
| Type | Description |
|---|---|
int
|
Number of names returned by :func: |
Source code in deap_er/private/various/policy_observe.py
policy_observe(*, solve_bits, train_score, held_out_score=None, archive=None, nevals=0, rows_seen=0, promoted_library_size=0, fitness_invalid=False, last_action_rejected=False)
¶
Build the fixed Push policy observation from summary inputs only.
Accepts reductions from :func:~deap_er.tools.case_errors,
:func:~deap_er.tools.score_case_exams,
:class:~deap_er.records.ArchiveStats, promoted-library counters,
and eval-budget tallies. Raw NumPy packs, column slices, and
matrix[t] are rejected at this boundary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
solve_bits
|
Sequence[int | float | bool]
|
Per-case |
required |
train_score
|
float
|
Sum of train-exam difficulty scores. |
required |
held_out_score
|
float | None
|
Held-out exam difficulty, or |
None
|
archive
|
ArchiveStats | None
|
Optional archive summary supplying coverage and
|
None
|
nevals
|
int
|
Evaluations consumed this step. |
0
|
rows_seen
|
int
|
Rows seen in the evaluation matrix so far. |
0
|
promoted_library_size
|
int
|
Count of promoted primitive names. |
0
|
fitness_invalid
|
bool
|
Whether the observed individual lacks valid fitness. |
False
|
last_action_rejected
|
bool
|
Whether the last policy action was rejected. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
One |
PolicyObservation
|
class: |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Source code in deap_er/private/various/policy_observe.py
rng
¶
RNG(seed=None)
¶
NumPy Generator facade with buffered uniform and integer streams.
random / uniform / take_floats pop leftover floats.
Scalar randint, randrange, choice, and integers pop
leftover uint64s. Other methods use the same Generator.
Sequences stay Python-indexed.
Create a generator, optionally seeded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int | None
|
Seed for the NumPy Generator. Optional; OS entropy if omitted. |
None
|
Source code in deap_er/private/various/rng.py
seed(seed=None)
¶
Reseed the generator and discard unused buffered values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int | None
|
Seed for a new NumPy Generator. Optional; OS entropy if omitted. |
None
|
Source code in deap_er/private/various/rng.py
get_state()
¶
Return the bit-generator state and unused buffers.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
Source code in deap_er/private/various/rng.py
set_state(state)
¶
Restore a state previously returned by get_state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict[str, Any]
|
Mapping from |
required |
Source code in deap_er/private/various/rng.py
random()
¶
Return the next uniform float in [0.0, 1.0).
Returns:
| Type | Description |
|---|---|
float
|
A Python float from the buffered stream. |
take_floats(count)
¶
Return count leftover uniforms, same stream as random.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
count
|
int
|
Number of floats. |
required |
Returns:
| Type | Description |
|---|---|
list[float]
|
Uniform floats in |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/rng.py
uniform(a, b)
¶
Return a uniform float in [a, b).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
float
|
Lower bound. |
required |
b
|
float
|
Upper bound. |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
randint(a, b)
¶
Return a random integer N such that a <= N <= b.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a
|
int
|
Inclusive lower bound. |
required |
b
|
int
|
Inclusive upper bound. |
required |
Returns:
| Type | Description |
|---|---|
int
|
An integer in the closed interval. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the interval is empty. |
Source code in deap_er/private/various/rng.py
randrange(start, stop=None, step=1)
¶
Return a random element from range(start, stop, step).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
int
|
Stop if |
required |
stop
|
int | None
|
Exclusive stop. Optional. |
None
|
step
|
int
|
Range step. Defaults to 1. |
1
|
Returns:
| Type | Description |
|---|---|
int
|
An integer from the equivalent |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the range is empty. |
Source code in deap_er/private/various/rng.py
choice(seq)
¶
Return one element of seq.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seq
|
Sequence[T]
|
Non-empty sequence. Indexed as a Python sequence. |
required |
Returns:
| Type | Description |
|---|---|
T
|
One element of |
Raises:
| Type | Description |
|---|---|
IndexError
|
If |
Source code in deap_er/private/various/rng.py
sample(population, k)
¶
Return k unique elements from population.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
population
|
Sequence[T]
|
Sequence to sample from. |
required |
k
|
int
|
Number of elements. May be passed by keyword. |
required |
Returns:
| Type | Description |
|---|---|
list[T]
|
A new list of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/rng.py
shuffle(x)
¶
Shuffle x in place.
Sequences of individuals are permuted by index. A 1-D ndarray is shuffled by the underlying Generator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
MutableSequence[Any] | ndarray
|
Mutable sequence or ndarray to shuffle. |
required |
Source code in deap_er/private/various/rng.py
gauss(mu, sigma)
¶
Return a sample from a Gaussian distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mu
|
float
|
Mean. |
required |
sigma
|
float
|
Standard deviation. |
required |
Returns:
| Type | Description |
|---|---|
float
|
A Python float from the normal distribution. |
Source code in deap_er/private/various/rng.py
standard_normal(size=None)
¶
Return samples from the standard normal distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int | tuple[int, ...] | None
|
Output shape. A single float is returned when omitted. |
None
|
Returns:
| Type | Description |
|---|---|
float | ndarray
|
A float, or an ndarray when |
Source code in deap_er/private/various/rng.py
integers(low, high=None, size=None, endpoint=False)
¶
Return random integers from the buffered or Generator path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
low
|
int
|
Inclusive lower bound, or exclusive high when |
required |
high
|
int | None
|
Exclusive upper bound unless |
None
|
size
|
int | tuple[int, ...] | None
|
Output shape. A single int is returned when omitted. |
None
|
endpoint
|
bool
|
If True, |
False
|
Returns:
| Type | Description |
|---|---|
int | ndarray
|
An int, or an ndarray when |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the interval is empty. |
Source code in deap_er/private/various/rng.py
rng_buf
¶
RngBuffers()
¶
Refillable uniform-float and raw-uint64 streams.
Allocate zeroed buffers that refill on the first pop.
Source code in deap_er/private/various/rng_buf.py
discard()
¶
pack()
¶
Copy leftover buffer arrays and their read indices.
Spent buffers (index at capacity) are exported as zeros so a checkpoint never carries uninitialized or discarded words.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
|
Source code in deap_er/private/various/rng_buf.py
unpack(state)
¶
Restore buffers from pack or a legacy uniform-only mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict[str, Any]
|
Mapping with |
required |
Source code in deap_er/private/various/rng_buf.py
next_float(gen)
¶
Pop the next uniform float in [0.0, 1.0).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gen
|
Generator
|
Generator used to refill an empty float buffer. |
required |
Returns:
| Type | Description |
|---|---|
float
|
A Python float from the leftover uniforms. |
Source code in deap_er/private/various/rng_buf.py
take_floats(gen, count)
¶
Pop count leftover uniforms, same stream as next_float.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gen
|
Generator
|
Generator used to refill an empty float buffer. |
required |
count
|
int
|
Number of floats. |
required |
Returns:
| Type | Description |
|---|---|
list[float]
|
Uniform floats in |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/rng_buf.py
next_u64(gen)
¶
Pop the next raw 64-bit word.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gen
|
Generator
|
Generator whose bit generator fills an empty buffer. |
required |
Returns:
| Type | Description |
|---|---|
int
|
A Python int in |
Source code in deap_er/private/various/rng_buf.py
offset(gen, start, span)
¶
Return start plus an unbiased integer in [0, span).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gen
|
Generator
|
Generator used to refill the uint64 buffer. |
required |
start
|
int
|
Inclusive origin of the interval. |
required |
span
|
int
|
Number of integers in the interval. |
required |
Returns:
| Type | Description |
|---|---|
int
|
An integer in |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
OverflowError
|
If |
Source code in deap_er/private/various/rng_buf.py
index(gen, n)
¶
Return an unbiased integer in [0, n).
Always consumes at least one uint64, including when n is 1.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gen
|
Generator
|
Generator used to refill the uint64 buffer. |
required |
n
|
int
|
Exclusive upper bound. Must be in |
required |
Returns:
| Type | Description |
|---|---|
int
|
An integer in the half-open interval. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
OverflowError
|
If |
Source code in deap_er/private/various/rng_buf.py
draw_integers(gen, buffers, low, high, size, endpoint)
¶
Draw a scalar int from the uint64 buffer, or a sized array from gen.
A sized draw discards leftover uint64s so later scalar ints refill from the advanced bit generator. Leftover uniforms are kept.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gen
|
Generator
|
Underlying NumPy Generator. |
required |
buffers
|
RngBuffers
|
Float and uint64 leftovers. |
required |
low
|
int
|
Inclusive lower bound, or exclusive high when |
required |
high
|
int | None
|
Exclusive upper bound unless |
required |
size
|
int | tuple[int, ...] | None
|
Output shape. A single int is returned when omitted. |
required |
endpoint
|
bool
|
If True, |
required |
Returns:
| Type | Description |
|---|---|
int | ndarray
|
An int, or an ndarray when |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the interval is empty. |
OverflowError
|
If the span exceeds 64 bits. |
Source code in deap_er/private/various/rng_buf.py
rng_spawn
¶
spawn_rng(seed, worker_id)
¶
Return an independent RNG derived from seed and worker_id.
Uses a NumPy SeedSequence child of the run seed. The process-wide
generator is not read or advanced, so a parent seeded with the same
value keeps its own stream. The same pair always yields the same
stream, regardless of which process draws it or when.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int | Sequence[int]
|
Run seed. The same value passed to |
required |
worker_id
|
int
|
Stable non-negative task index, not an OS pid. |
required |
Returns:
| Type | Description |
|---|---|
RNG
|
A new |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If |
Source code in deap_er/private/various/rng_spawn.py
bind_spawned_rng(seed, worker_id)
¶
Install spawn_rng(seed, worker_id) as the process-wide generator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int | Sequence[int]
|
Run seed. The same value passed to |
required |
worker_id
|
int
|
Stable non-negative task index. |
required |
Returns:
| Type | Description |
|---|---|
RNG
|
The process-wide |
Source code in deap_er/private/various/rng_spawn.py
call_spawned(payload)
¶
Bind a spawned stream, call func(item), then restore rng.
The process-wide generator is restored even if func raises, so an
in-process map does not leak a worker stream into the parent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
SpawnedPayload[T]
|
|
required |
Returns:
| Type | Description |
|---|---|
tuple[int, Any]
|
|
Source code in deap_er/private/various/rng_spawn.py
map_spawned(func, iterable, *, seed, map_func=map)
¶
Map func over iterable with one spawned stream per item.
Item i sees spawn_rng(seed, i) as the process-wide rng.
Results are returned in input order. map_func may complete
tasks in any order; only the worker_id on each result matters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable[[T], R]
|
Callable applied to each item. Library operators that
read |
required |
iterable
|
Iterable[T]
|
Inputs. Materialized once so ids are stable. |
required |
seed
|
int | Sequence[int]
|
Run seed shared with |
required |
map_func
|
Callable[..., Iterable[Any]]
|
|
map
|
Returns:
| Type | Description |
|---|---|
list[R]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/rng_spawn.py
semantic_descriptors
¶
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_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_mask
¶
as_semantic_matrix(matrix)
¶
Pack a semantic matrix as float64.
The result is two-dimensional. Layout follows NumPy asarray:
a Fortran-order input keeps its memory order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray | Sequence[Sequence[float]]
|
Caller-supplied |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A two-dimensional |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/semantic_mask.py
semantic_valid_mask(matrix, valid=None)
¶
Return the finite sample mask for a semantic matrix.
A one-dimensional valid is broadcast across individuals and
intersected with isfinite(matrix). A sample that is True in
valid but non-finite still stays out of the mask.
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
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Boolean mask with the same shape as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/semantic_mask.py
validate_semantic_matrix(matrix, individuals, *, trust_matrix=False)
¶
Check that a semantic pack is row-aligned with individuals.
Unlike lexicase, the series cannot be compared to fitness.values.
When trust_matrix is False, every individual must have a
valid fitness. When True, only the leading shape is checked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray | Sequence[Sequence[float]]
|
Semantic pack of shape |
required |
individuals
|
Sequence[Any] | None
|
Population the rows describe, or |
required |
trust_matrix
|
bool
|
When |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The packed |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/semantic_mask.py
packed_semantics(matrix, individuals, trust_matrix)
¶
Pack a semantic matrix, optionally checking individuals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix
|
ndarray | Sequence[Sequence[float]]
|
Semantic pack of shape |
required |
individuals
|
Sequence[Any] | None
|
Population the rows describe, or |
required |
trust_matrix
|
bool
|
When |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The packed |
Source code in deap_er/private/various/semantic_mask.py
semantic_column_keep(n_rows, valid, target)
¶
Return the shared column mask used by projection helpers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_rows
|
int
|
Number of semantic coordinates. |
required |
valid
|
ndarray | None
|
Optional per-row warmup mask of length |
required |
target
|
ndarray | None
|
Optional target whose non-finite samples are dropped. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
One-dimensional |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in deap_er/private/various/semantic_mask.py
semantic_neighbors
¶
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_project
¶
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 |
Source code in deap_er/private/various/semantic_project.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
sort_non_dominated
¶
sort_non_dominated(individuals, sel_count)
¶
Sort individuals into non-dominated Pareto fronts.
Uses moocore.pareto_rank on fitness.wvalues (higher is
better). Fronts are truncated once they hold at least
sel_count individuals. Individuals without a comparable
fitness (missing, invalid, or non-finite) are ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individuals
|
list[Individual]
|
Individuals to sort. |
required |
sel_count
|
int
|
Number of individuals to place into fronts. |
required |
Returns:
| Type | Description |
|---|---|
list[list[Individual]]
|
A list of Pareto fronts. The first element is the true |
list[list[Individual]]
|
Pareto front. An empty list if |
list[list[Individual]]
|
positive. A single empty front if no rankable individual |
list[list[Individual]]
|
remains and |
Source code in deap_er/private/various/sort_non_dominated.py
sorting_network
¶
SortingNetwork(dimension, connectors=None)
¶
A network of wires and comparators that sorts a sequence.
Wires run from left to right and carry one value each. A comparator connects two wires and swaps their values when the upper wire is greater than the lower wire.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dimension
|
int
|
Number of wires in the network. |
required |
connectors
|
list[tuple[int, int]] | None
|
Optional list of wire pairs connected by a comparator. |
None
|
See the class docstring.
Source code in deap_er/private/various/sorting_network.py
depth
property
¶
Returns the depth of the network.
length
property
¶
Returns the length of the network.
__iter__()
¶
__contains__(item)
¶
__getitem__(key)
¶
__setitem__(key, value)
¶
__delitem__(key)
¶
__len__()
¶
check_conflict(level, wire1, wire2)
staticmethod
¶
Return whether the wires conflict on the given level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
list[tuple[int, int]]
|
Comparators already present on the level. |
required |
wire1
|
int
|
Index of the first wire. |
required |
wire2
|
int
|
Index of the second wire. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the wires conflict, False otherwise. |
Source code in deap_er/private/various/sorting_network.py
add_connector(wire1, wire2)
¶
Add a comparator between the two wires.
Same-index wires are ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wire1
|
int
|
Index of the first wire. |
required |
wire2
|
int
|
Index of the second wire. |
required |
Source code in deap_er/private/various/sorting_network.py
sort(values)
¶
Sort values in place using this network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
list[Any]
|
Sequence to sort. Must have at least |
required |
Source code in deap_er/private/various/sorting_network.py
evaluate(cases=None)
¶
Count how many cases the network fails to sort.
When cases is omitted, every binary sequence of length
dimension is tested.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cases
|
Iterable[Iterable[Any]] | None
|
Sequences to sort and check. Optional. |
None
|
Returns:
| Type | Description |
|---|---|
int
|
The number of incorrectly sorted cases. |
Source code in deap_er/private/various/sorting_network.py
draw()
¶
Return an ASCII diagram of the network.
Returns:
| Type | Description |
|---|---|
str
|
A schematic of the wires and comparators. |
Source code in deap_er/private/various/sorting_network.py
structural_meta_case
¶
structural_meta_case_weights(columns=None)
¶
Return default lexicase signs for structural meta-case columns.
Bloat metrics default to minimize (-1). non_finite_fraction
defaults to maximize (+1) so lexicase prefers programs that are
not finite on every bar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
columns
|
Sequence[str] | None
|
Subset of :data: |
None
|
Returns:
| Type | Description |
|---|---|
tuple[float, ...]
|
One maximize/minimize sign per column. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a column name is unknown. |
Source code in deap_er/private/various/structural_meta_case.py
structural_meta_case_columns(individuals, *, prim_set=None, predicted=None, columns=None)
¶
Return cheap structural meta-case columns for a population.
Shape (len(individuals), len(columns)). Tree metrics need no
predicted. non_finite_fraction needs one row per
individual in predicted ((n_ind, n_rows) or a sequence of
1-D series). When predicted is missing, that column is filled
with numpy.nan.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
individuals
|
Sequence[Any]
|
Population whose genomes are |
required |
prim_set
|
PrimitiveSetTyped | None
|
Primitive set for |
None
|
predicted
|
ndarray | Sequence[Sequence[float]] | None
|
Optional per-individual output series. |
None
|
columns
|
Sequence[str] | None
|
Subset of :data: |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Structural scalars with one row per individual. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |