Classes¶
Every class the framework exposes, grouped by the layer it belongs to. Decorators and free functions live in Functions; the packages themselves are described in Modules.
Optimizers¶
BaseOptimizer ¶
Bases: ABC
Abstract base every optimizer model satisfies.
Defines the solve contract, the __call__ configuration
hook, the alias name, and the tracker history.
tracker
abstractmethod
property
¶
Per-epoch history (empty before the first solve).
solve
abstractmethod
¶
solve(f: Target, bounds: Bounds | SequenceStructure[ScalarType], epochs: int, pop_size: int, pop_range: tuple[int, int] | None = None, debug: bool = False, sense: SenseType = 'min') -> tuple[float, NDArrayType]
Run the optimization and return the best (fitness, solution).
FunctionOptimizerModel ¶
Bases: BaseOptimizer
Model built by @cm.declare from a function.
The wrapped function receives (args, epoch, ctx) and drives the
whole run. Bind parameters by calling the model, then solve.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alias
|
str
|
Display name; overwritten by the function name on |
'Optimizer'
|
seed
|
int | None
|
Random seed forwarded to the run. |
None
|
**kwargs
|
Any
|
|
{}
|
Attributes:
| Name | Type | Description |
|---|---|---|
alias |
str
|
The model name. |
tracker |
list[EpochHistory]
|
Per-epoch history (empty before the first |
Initialize the model state (alias, arguments, seed, debug, sense).
define ¶
Bind func as the run driver, building the solve closure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
AlgorithmFunction
|
The |
required |
Returns:
| Type | Description |
|---|---|
FunctionOptimizerModel
|
The model itself, for chaining. |
solve ¶
solve(f: Target, bounds: Bounds | SequenceStructure[ScalarType], epochs: int, pop_size: int, pop_range: tuple[int, int] | None = None, debug: bool = False, sense: SenseType = 'min') -> tuple[float, NDArrayType]
Run the optimization and return the best (fitness, solution).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
Target
|
The objective callable. |
required |
bounds
|
Bounds | SequenceStructure[ScalarType]
|
The search space (or bounds sequence). |
required |
epochs
|
int
|
Total number of epochs. |
required |
pop_size
|
int
|
Population size. |
required |
pop_range
|
tuple[int, int] | None
|
|
None
|
debug
|
bool
|
Record per-epoch history. |
False
|
sense
|
SenseType
|
|
'min'
|
Returns:
| Type | Description |
|---|---|
tuple[float, NDArrayType]
|
The best fitness and the best solution vector found. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If no function was bound via |
TemplateOptimizerModel ¶
Bases: BaseOptimizer
Model built by @cm.template from a class.
The class supplies initialize/evolve; compile options
(numba/parallel/fastmath/cache) are set at instantiation
and propagate to the class's numba kernels. prepare=True compiles
them eagerly at construction instead of on first use.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cls_model
|
type[ModelProtocol]
|
The wrapped class implementing |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
alias |
str
|
The wrapped class name. |
model_class |
type[ModelProtocol]
|
The wrapped class. |
compile_options |
dict[str, bool]
|
Resolved compile options of the model. |
tracker |
list[EpochHistory]
|
Per-epoch history (empty before the first |
Initialize the model state around the wrapped class.
compile_options
property
¶
Compile options (numba/parallel/fastmath/cache).
prepare ¶
Return the numba kernels declared on the wrapped class.
Kernels compile on first use; this hook forces compilation with the
model's compile options and reports their signatures. Kernels running
uncompiled (numba=False or numba not installed) report the
"<python>" marker. Pass prepare=True at construction to run
this automatically during instantiation.
solve ¶
solve(f: Target, bounds: Bounds | SequenceStructure[ScalarType], epochs: int, pop_size: int, pop_range: tuple[int, int] | None = None, debug: bool = False, sense: SenseType = 'min', prepare: bool = False) -> tuple[float, NDArrayType]
Run the optimization and return the best (fitness, solution).
Calls initialize once, then evolve per epoch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
Target
|
The objective callable. |
required |
bounds
|
Bounds | SequenceStructure[ScalarType]
|
The search space (or bounds sequence). |
required |
epochs
|
int
|
Total number of epochs. |
required |
pop_size
|
int
|
Population size. |
required |
pop_range
|
tuple[int, int] | None
|
|
None
|
debug
|
bool
|
Record per-epoch history. |
False
|
sense
|
SenseType
|
|
'min'
|
prepare
|
bool
|
Force compilation of the class's kernels before running. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[float, NDArrayType]
|
The best fitness and the best solution vector found. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the model was not instantiated first. |
Field markers¶
Argument ¶
Declare a tunable, range-checked model field.
Argument is a subscript-only marker that builds a
typing.Annotated type understood by @cm.declare /
@cm.template. It is never instantiated — only subscripted on a class
annotation. Supported forms::
Argument[type] # required, no range/default
Argument[type, default] # with a default value
Argument[type, (min, max)] # range-checked, required
Argument[type, (min, max), default]
The subscript accepts target_type (the field's type), optionally a
(min_val, max_val) range, and optionally a default_val. An
unsupported form raises TypeError.
Constant ¶
Declare a fixed, read-only field for templates and operator mixins.
Constant is a subscript-only marker that builds a typing.Annotated
type understood by @cm.template and @cm.module. The declared value
is installed as a class-level descriptor, so it is visible as
self.name/Cls.name but is never a constructor parameter::
Constant[type, value] # a fixed value checked once at declaration
Constants work the same way on a @cm.template model and on a
@cm.module mixin, where every implementing model inherits them.
Variable ¶
Declare a free internal-state field (no range check, no default).
Variable is a subscript-only marker for model state that is not a
tunable parameter::
w: cm.Variable[np.ndarray]
It wraps target_type (the field's declared type) in
typing.Annotated metadata marking it as delayed-init state.
Population¶
The swarm handle and everything layered on top of the kernel buffer: stream operators, matrix views and the roster/iteration bases.
PopulationSwarm ¶
Bases: StreamOperations, BufferMatrixOperations, BaseIterator, DynamicBase
Main handle over a KernelBuffer.
A swarm layers a readable/writable matrix view (X/F), stream
operators (compute/assign/access/extract/swap),
ranking (best/worst/sort) and roster management
(insert/remove/free_space) on top of the flat buffer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
KernelBuffer
|
The buffer backing this population. |
required |
Examples:
::
pop = cm.PopulationSwarm(ctx.buff)
pop.compute << ctx.rng.uniform(bounds.low, bounds.up,
(pop.size, bounds.ndim))
best_rows = pop.X[pop.sort][:3]
Compose the matrix views, operators, iterator and roster over buffer.
StreamOperations ¶
The compute/assign/access/extract/swap operators.
Each property returns a fresh operator bound to the buffer; they are
the verbs of the population DSL (pop.compute << values).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
KernelBuffer
|
The backing buffer. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
swap |
SwapOperation
|
Row swap writer. |
compute |
ComputeOperator
|
Write-and-score operator. |
assign |
AssignOperator
|
Raw row writer (no scoring). |
extract |
ExtractOperation
|
Solution-column reader. |
access |
AccessOperator
|
Whole-row reader. |
Initialize the operators over buffer.
ComputeOperator ¶
Bases: VectorizableOperator
Write-and-score operator: pop.compute << rows / pop.compute[idx] << rows.
Writing through compute inserts the solutions and evaluates them
against the objective. The evaluation counter is charged one function
evaluation per row scored: the whole active block costs its active rows, a
mask costs the rows it selects, a single row costs one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
KernelBuffer
|
The backing buffer. |
required |
Initialize the operator over buffer.
AssignOperator ¶
Bases: VectorizableOperator
Raw row writer (no scoring): pop.assign << rows / pop.assign[i] << row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
KernelBuffer
|
The backing buffer. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the assigned block's shape does not match the buffer. |
Initialize the writer over buffer.
AccessOperator ¶
Bases: ReaderOperator
Whole-row reader: pop.access[i], ~pop.access.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
KernelBuffer
|
The backing buffer. |
required |
Initialize the reader over buffer.
ExtractOperation ¶
Bases: ReaderOperator
Solution-column reader: pop.extract[i], ~pop.extract.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
KernelBuffer
|
The backing buffer. |
required |
Initialize the reader over buffer.
SwapOperation ¶
Bases: WriterOperator
Row swap writer: pop.swap[i] = row (moves the old row to the end).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
KernelBuffer
|
The backing buffer. |
required |
Initialize the writer over buffer.
ComputePipeline ¶
Bases: PipelineOperator
Per-selection compute target: pop.compute[idx] << rows.
The selection may be one row (pop.compute[3] or
pop.compute[pop.best]), several rows (a slice, an index array, a
boolean mask) or the active roster (pop.compute[~pop]). Each row
written through it spends exactly one evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
RowSelection
|
The rows to write and evaluate. |
required |
buffer
|
KernelBuffer
|
The backing buffer. |
required |
Bind the pipeline to the rows selected by idx.
AssignPipeline ¶
Bases: PipelineOperator
Per-row assign target: pop.assign[i] << row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
int
|
The row to write. |
required |
buffer
|
KernelBuffer
|
The backing buffer. |
required |
Bind the pipeline to row idx of buffer.
StreamOperator ¶
Bases: ABC
Base for operators bound to a fixed buffer shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
The |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
shape |
tuple[int, ...]
|
The buffer shape. |
Store the buffer shape the operator is bound to.
ReaderOperator ¶
WriterOperator ¶
VectorizableOperator ¶
PipelineOperator ¶
Bases: ABC
Per-row target of a << write (e.g. pop.compute[i] << row).
BufferMatrixOperations ¶
Exposes the F/X matrix views, idx ranking and size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
KernelBuffer
|
The backing buffer. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
F |
BufferMatrixFitness
|
Fitness-column view. |
X |
BufferMatrixSolutions
|
Solution-block view. |
idx |
BufferIndex
|
Best/worst/sort lookups. |
size |
int
|
Number of active individuals. |
Initialize the operations over buffer.
BufferMatrixFitness ¶
Bases: BufferMatrixAbstract, BufferMatrixAccess
Read view over the buffer's fitness column (column 0).
Supports pop.F[i], pop.F.to_numpy() (or cm.cast(pop.F)) for the
full column and ~pop.F for the active rows only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
KernelBuffer
|
The backing buffer. |
required |
Initialize the view over buffer.
BufferMatrixSolutions ¶
Bases: BufferMatrixAbstract, BufferMatrixAccess, BufferMatrixCompute
Read/write view over the solution columns (columns 1:).
Supports pop.X[i], pop.X.to_numpy() (or cm.cast(pop.X)),
~pop.X for the active rows, and the write-back pop.X << values
(which scores the block).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
KernelBuffer
|
The backing buffer. |
required |
Initialize the view over buffer.
BufferMatrixAbstract ¶
Bases: ABC
Abstract read interface shared by the F/X matrix views.
Subclasses must implement indexing, the explicit to_numpy conversion,
and __repr__/__str__ display. Implicit coercion through NumPy's
__array__ hook is deprecated; use cm.cast(...) or to_numpy().
BufferMatrixAccess ¶
Bases: ABC
Read access via ~ (the active rows of a matrix view).
BufferMatrixCompute ¶
Bases: ABC
Write-back via << (assign and score a block of solutions).
DynamicBase ¶
Roster management over the buffer: insert, remove, free space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
KernelBuffer
|
The buffer whose active rows are managed. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
free_space |
bool
|
|
Initialize the roster over buffer.
insert ¶
Insert a solution into the first free row and return its index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
NDArrayType
|
The solution to score and insert. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The index of the row the solution was inserted into. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the buffer has no free rows. |
BaseIterator ¶
Iteration and ranking over the population's active rows.
Iterating a population (or its ~ form) yields the active row
indices; best/worst/sort expose the sense-aware ranking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
KernelBuffer
|
The buffer to iterate. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
best |
intp
|
Row index of the best individual. |
worst |
intp
|
Row index of the worst individual. |
sort |
NDArray[intp]
|
Row indices ordered best-first. |
Initialize the iterator over buffer.
Buffer¶
The flat buffer that backs every population, plus the mask, size and ranking support types.
KernelBuffer ¶
Flat (pop_size, ndim + 1) store backing a population.
Column 0 holds fitness; columns 1: hold the solution vector. New
solutions are written with apply, which scores them against the
objective (whole-block when the target is vectorized, row-by-row
otherwise).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
KernelSize
|
Population size bounds. |
required |
bounds
|
Bounds
|
Search space (defines |
required |
target
|
TargetFunction
|
The wrapped objective used to score solutions. |
required |
sense
|
SenseType
|
|
required |
Attributes:
| Name | Type | Description |
|---|---|---|
shape |
tuple[int, ...]
|
Shape of the raw buffer. |
mask |
KernelMask
|
The active-row mask. |
raw |
NDArrayType
|
The underlying buffer array. |
idx |
BufferIndex
|
Best/worst/sort lookups over the fitness column. |
size |
KernelSize
|
The population size bounds. |
snapshot |
KernelBuffer
|
A fresh empty buffer with the same configuration. |
Initialize the buffer, mask and configuration. See class docstring.
snapshot
property
¶
A fresh empty buffer with the same size, bounds, target and sense.
apply ¶
Vectorizes the target function to evaluate and update the solutions matrix.
The internal buffer stores "fitness" in column 0 and "solutions" or "x"
from column 1 onwards. Supports updating a single row, a slice, a
list/array of indices, a boolean mask, or the entire active matrix if
idx is None.
Targets wrapped with cmenpy.target.vectorized_target score the whole
block with a single call; the others fall back to a row-by-row
evaluation. Either way the objective is charged exactly one evaluation
per row scored: an individually selected row is dispatched as a
one-row block, never as ndim separate entries, and a selection
that picks no rows scores nothing at all.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
NDArrayType
|
An array containing the new solution data to be inserted into the buffer. |
required |
idx
|
RowSelection | None
|
The row index, slice, or index mask to update. If None, defaults to the internal mask. |
None
|
KernelSize ¶
Population size bounds: current size clamped to [min, max].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int
|
Current population size. |
required |
min_size
|
int | None
|
Smallest allowed size; defaults to |
None
|
max_size
|
int | None
|
Largest allowed size; defaults to |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Attributes:
| Name | Type | Description |
|---|---|---|
max |
int
|
Largest allowed size (the buffer is allocated to this many rows). |
min |
int
|
Smallest allowed size. |
size |
int
|
Current size. |
Validate and store the population size bounds.
KernelMask ¶
Boolean active/passive mask over the buffer rows.
A row is active while it holds a live individual. The mask starts
with the first size.size rows active; deactivating a row (see
PopulationSwarm.remove) frees it for later insertion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
KernelSize
|
Supplies the total (max) row count and the initial active count. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
active |
int
|
Number of active rows. |
founds |
list[bool]
|
Copy of the mask as a plain list of booleans. |
Initialize the mask with the first size.size rows active.
BufferIndex ¶
Ranking and best/worst lookups over the buffer's fitness column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer
|
NDArrayType
|
The raw |
required |
mask
|
KernelMask
|
The active-row mask. |
required |
sense
|
SenseType
|
|
required |
Attributes:
| Name | Type | Description |
|---|---|---|
sort |
NDArray[intp]
|
Row indices ordered best-first (respecting |
best |
intp
|
Row index of the best individual. |
worst |
intp
|
Row index of the worst individual. |
Initialize the lookups over buffer and mask.
Objectives¶
Target ¶
Bases: Protocol
Protocol for an objective: a callable mapping a solution to a score.
TargetFunction ¶
Wraps an objective, counting NFE and enforcing an optional budget.
The wrapper scores solutions one individual at a time (evaluate) or a
whole block at once (evaluate_matrix), increments the function-evaluation
counter on every individual scored, and raises MaxNumberOfCalls once
max_nfe is spent. A single individual always costs exactly one
evaluation, whatever the shape of the objective underneath: a row written
to a vectorized target is dispatched as a one-row block.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
Target
|
The raw objective callable. |
required |
bounds
|
Bounds
|
The search space. |
required |
max_nfe
|
int | None
|
Evaluation budget; |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
nfe |
int
|
Evaluations spent so far. |
max |
float | int
|
The budget ( |
bounds |
Bounds
|
The search space. |
vectorized |
bool
|
Whether the target scores whole blocks. |
Wrap target, counting evaluations against the max_nfe budget.
evaluate ¶
Score a single individual, spending exactly one evaluation.
A plain target receives the solution vector as it is; a vectorized
target receives it as a (1, ndim) block and the single score is
unwrapped again, so one individual never costs ndim.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
NDArrayType
|
The solution vector, or a one-row |
required |
Returns:
| Type | Description |
|---|---|
NDArrayType | Any
|
The fitness of that individual. |
evaluate_matrix ¶
Score a whole (pop, ndim) block and return a (pop,) vector.
Spending is one evaluation per row of the block, so masked and index-selected blocks cost only what they actually score.
VectorizedTarget ¶
A target that maps a whole (pop, ndim) matrix to a (pop,) vector.
Marking a target as vectorized lets KernelBuffer.apply score a whole
population with a single call instead of np.apply_along_axis, which
spends one Python call per individual.
Wrap target so it is dispatched as a whole-block evaluator.
MaxNumberOfCalls ¶
Bases: Exception
Raised when a target's evaluation budget (max_nfe) is exceeded.
Search space¶
Bounds ¶
Search-space bounds: one (low, up) pair per dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bounds
|
SequenceStructure[ScalarType]
|
A sequence of |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
ndim |
int
|
Number of dimensions (length of the bounds sequence). |
low |
Any
|
Lower bound of the first dimension, convenient for vectorized sampling over a box-shaped space. |
up |
Any
|
Upper bound of the first dimension, convenient for vectorized sampling over a box-shaped space. |
Examples:
::
bounds = cm.Bounds([(-1, 1), (-2, 2), (0, 5)])
bounds.ndim # 3
bounds.low, bounds.up # -1, 1
Store the (low, up) pairs; the count defines ndim.
Runtime¶
The per-run machinery: the context handed to models, the epoch iterator, the history tracker and the seeded generator.
Context ¶
Context(f: Target, bounds: Bounds, buffer: KernelBuffer, generator: DefaultGenerator, sense: SenseType, epoch: int = 0, epochs: int = 0)
Read-only view of the run handed to initialize/evolve.
A fresh Context is built for every epoch. It exposes the search
space, the population buffer, the random generator, the optimization
sense, and the current/total epoch counters.
Attributes:
| Name | Type | Description |
|---|---|---|
target |
TargetFunction
|
The wrapped objective (counts NFE, enforces any budget). |
bounds |
Bounds
|
The search space ( |
buff |
KernelBuffer
|
The buffer backing the population. |
rng |
Generator
|
Seeded random generator. |
sense |
SenseType
|
|
epoch |
int
|
Current epoch index. |
epochs |
int
|
Total number of epochs. |
Wrap the run resources into a per-epoch view.
MainContextManager ¶
MainContextManager(f: Target, bounds: Bounds, epochs: int, size: KernelSize, seed: int | None = None, debug: bool = False, sense: SenseType = 'min')
Owns every per-run resource and builds the per-epoch Context.
This is the internal orchestrator created by solve. It wires the
objective, bounds, buffer, generator, tracker and epoch iterator
together and hands out Context views.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
Target
|
The objective callable. |
required |
bounds
|
Bounds
|
The search space. |
required |
epochs
|
int
|
Total number of epochs. |
required |
size
|
KernelSize
|
Population size (current, min, max). |
required |
seed
|
int | None
|
Random seed forwarded to the generator. |
None
|
debug
|
bool
|
Record per-epoch history. Default |
False
|
sense
|
SenseType
|
|
'min'
|
Attributes:
| Name | Type | Description |
|---|---|---|
epoch_it |
EpochIteration
|
The epoch iterator driving the run. |
buffer |
KernelBuffer
|
The population buffer. |
tracker |
Tracker
|
The per-epoch history recorder. |
Wire the objective, buffer, generator, tracker and epoch iterator.
EpochIteration ¶
Epoch counter you iterate over; tracks per-epoch CPU time and NFE.
An EpochIteration is the epoch argument passed to a
@cm.declare function (and the object behind ctx.epoch /
ctx.epochs). Iterating it yields 0 .. epochs - 1 and, when
debug is enabled, records a EpochHistory
snapshot after each epoch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
epochs
|
int
|
Total number of epochs; must be positive. |
required |
tracker
|
Tracker
|
Recorder populated each epoch when |
required |
target
|
TargetFunction
|
Objective wrapper used to read the function-evaluation count (NFE). |
required |
debug
|
bool
|
Record a history snapshot per epoch. Default |
False
|
Attributes:
| Name | Type | Description |
|---|---|---|
current |
int
|
Index of the epoch most recently yielded. |
max |
int
|
Total number of epochs. |
cpu_time |
float
|
Wall CPU time spent in the most recent epoch body. |
Validate and store the epoch count and recording resources.
Tracker ¶
Records per-epoch snapshots of the population buffer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buff
|
KernelBuffer
|
The buffer whose state is snapshotted on every |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
history |
list[EpochHistory]
|
Immutable copies of the tracked epochs, oldest first. |
Initialize the recorder over buff.
history
property
¶
Immutable copies of the tracked epochs, oldest first.
track ¶
Append an EpochHistory snapshot of epoch e.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
e
|
int
|
Epoch index. |
required |
timeit
|
float
|
CPU time spent in the epoch. |
required |
nfe
|
int
|
Function evaluations spent up to the end of the epoch. |
required |
EpochHistory
dataclass
¶
EpochHistory(epoch: int, best_idx: int, worst_idx: int, all: NDArrayType, timeit: int | float, nfe: int)
Immutable snapshot of one epoch (only recorded when debug=True).
Attributes:
| Name | Type | Description |
|---|---|---|
epoch |
int
|
Epoch index. |
best_idx |
int
|
Row index of the best individual at the end of the epoch. |
worst_idx |
int
|
Row index of the worst individual at the end of the epoch. |
all |
NDArrayType
|
Copy of the full population buffer (fitness in column 0). |
timeit |
int | float
|
CPU time spent in the epoch. |
nfe |
int
|
Function evaluations spent up to the end of the epoch. |
DefaultGenerator ¶
Seeded random generator handed to models as ctx.rng.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int | None
|
Seed for the underlying |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
rng |
Generator
|
The live random generator used for sampling. |
Create the underlying numpy.random.Generator from seed.
Protocols¶
The structural types models and kernels are checked against.
ModelProtocol ¶
Bases: Protocol
Protocol a @cm.template class must satisfy.
The class must implement initialize (seed the population once)
and evolve (advance one epoch).
AlgorithmFunction ¶
Bases: Protocol
Signature of a @cm.declare function: (args, epoch, ctx) -> None.
CallableFunction ¶
Bases: Protocol
Signature of a bound solve-style callable over a run.
Support types and aliases¶
Exception/argument holders raised or built by the declaration machinery, and the shared typing aliases.
FunctionParamsArguments ¶
Holds the declared cm.Argument fields and their bound values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_dict
|
dict[str, type[Any]]
|
Mapping of field name to declared type ( |
required |
Raises:
| Type | Description |
|---|---|
AttributeError
|
On loading a name that was never declared, or reading an uninitialized declared field. |
ExceptionValueParams
|
If a value falls outside its declared range. |
ExceptionTypeParams
|
If a value does not match its declared type. |
Store the declared field names and types.
load ¶
Bind values_dict into the declared fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values_dict
|
dict[str, Any]
|
Mapping of field name to value. |
required |
Raises:
| Type | Description |
|---|---|
AttributeError
|
If a name was never declared. |
ExceptionTypeParams ¶
Bases: Exception
Raised when an argument value does not match its declared type.
ExceptionValueParams ¶
Bases: Exception
Raised when an argument value falls outside its declared range.