Skip to content

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.

alias abstractmethod property

alias: str

The model name.

tracker abstractmethod property

tracker: list[EpochHistory]

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

FunctionOptimizerModel(alias: str = 'Optimizer', seed: int | None = None, **kwargs: Any)

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 define.

'Optimizer'
seed int | None

Random seed forwarded to the run.

None
**kwargs Any

name=cm.Argument[...] field declarations.

{}

Attributes:

Name Type Description
alias str

The model name.

tracker list[EpochHistory]

Per-epoch history (empty before the first solve).

Initialize the model state (alias, arguments, seed, debug, sense).

alias property

alias: str

The model name.

tracker property

tracker: list[EpochHistory]

Per-epoch history (empty before the first solve).

define

define(func: AlgorithmFunction) -> FunctionOptimizerModel

Bind func as the run driver, building the solve closure.

Parameters:

Name Type Description Default
func AlgorithmFunction

The (args, epoch, ctx) -> None algorithm function.

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

(min, max) allowed population sizes.

None
debug bool

Record per-epoch history.

False
sense SenseType

"min" (default) or "max".

'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 define.

TemplateOptimizerModel

TemplateOptimizerModel(cls_model: type[ModelProtocol])

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 initialize/evolve.

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 solve).

Initialize the model state around the wrapped class.

alias property

alias: str

The wrapped class name.

model_class property

model_class: type[ModelProtocol]

The class wrapped by cmenpy.template.

tracker property

tracker: list[EpochHistory]

Per-epoch history (empty before the first solve).

compile_options property

compile_options: dict[str, bool]

Compile options (numba/parallel/fastmath/cache).

prepare

prepare() -> dict[str, list[str]]

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

(min, max) allowed population sizes.

None
debug bool

Record per-epoch history.

False
sense SenseType

"min" (default) or "max".

'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

PopulationSwarm(buffer: KernelBuffer)

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

StreamOperations(buffer: KernelBuffer)

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.

swap property

swap: SwapOperation

Row swap writer.

compute property

compute: ComputeOperator

Write-and-score operator.

assign property

assign: AssignOperator

Raw row writer (no scoring).

extract property

extract: ExtractOperation

Solution-column reader.

access property

access: AccessOperator

Whole-row reader.

ComputeOperator

ComputeOperator(buffer: KernelBuffer)

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

AssignOperator(buffer: KernelBuffer)

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

AccessOperator(buffer: KernelBuffer)

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

ExtractOperation(buffer: KernelBuffer)

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

SwapOperation(buffer: KernelBuffer)

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

ComputePipeline(idx: RowSelection, buffer: KernelBuffer)

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

AssignPipeline(idx: int, buffer: KernelBuffer)

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

StreamOperator(shape: tuple[int, ...])

Bases: ABC

Base for operators bound to a fixed buffer shape.

Parameters:

Name Type Description Default
shape tuple[int, ...]

The (rows, columns) shape of the backing buffer.

required

Attributes:

Name Type Description
shape tuple[int, ...]

The buffer shape.

Store the buffer shape the operator is bound to.

shape property

shape: tuple[int, ...]

The buffer shape.

ReaderOperator

ReaderOperator(shape: tuple[int, ...])

Bases: StreamOperator

Read-only operator: indexing, ~ (active rows) and >>.

WriterOperator

WriterOperator(shape: tuple[int, ...])

Bases: StreamOperator

Write-only operator: item assignment (op[i] = value).

VectorizableOperator

VectorizableOperator(shape: tuple[int, ...])

Bases: StreamOperator

Whole-block operator supporting << and per-row indexing.

PipelineOperator

Bases: ABC

Per-row target of a << write (e.g. pop.compute[i] << row).

BufferMatrixOperations

BufferMatrixOperations(buffer: KernelBuffer)

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.

F property

F: BufferMatrixFitness

Fitness-column view.

X property

X: BufferMatrixSolutions

Solution-block view.

idx property

idx: BufferIndex

Best/worst/sort lookups.

size property

size: int

Number of active individuals.

BufferMatrixFitness

BufferMatrixFitness(buffer: KernelBuffer)

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.

to_numpy

to_numpy() -> NDArrayType

Return the full fitness column as an ndarray.

BufferMatrixSolutions

BufferMatrixSolutions(buffer: KernelBuffer)

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.

to_numpy

to_numpy() -> NDArrayType

Return the full solution block as an ndarray.

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().

to_numpy abstractmethod

to_numpy() -> NDArrayType

Return the view as an ndarray.

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

DynamicBase(buffer: KernelBuffer)

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

True while at least one row is inactive (insertable).

Initialize the roster over buffer.

free_space property

free_space: bool

True while at least one row is inactive (insertable).

remove

remove(idx: int) -> None

Deactivate row idx and clear it to NaN.

insert

insert(x: NDArrayType) -> int

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

BaseIterator(buffer: KernelBuffer)

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.

best property

best: intp

Row index of the best individual.

worst property

worst: intp

Row index of the worst individual.

sort property

sort: NDArray[intp]

Row indices ordered best-first.

Buffer

The flat buffer that backs every population, plus the mask, size and ranking support types.

KernelBuffer

KernelBuffer(size: KernelSize, bounds: Bounds, target: TargetFunction, sense: SenseType)

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 ndim).

required
target TargetFunction

The wrapped objective used to score solutions.

required
sense SenseType

"min" or "max".

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.

shape property

shape: tuple[int, ...]

Shape of the raw buffer.

mask property

mask: KernelMask

The active-row mask.

raw property

raw: NDArrayType

The underlying buffer array.

idx property

idx: BufferIndex

Best/worst/sort lookups over the fitness column.

size property

size: KernelSize

The population size bounds.

snapshot property

snapshot: KernelBuffer

A fresh empty buffer with the same size, bounds, target and sense.

apply

apply(x: NDArrayType, idx: RowSelection | None = None) -> None

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

KernelSize(size: int, min_size: int | None = None, max_size: int | None = None)

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 size.

None
max_size int | None

Largest allowed size; defaults to size.

None

Raises:

Type Description
ValueError

If size falls outside [min_size, max_size].

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.

max property

max: int

Largest allowed size (the buffer is allocated to this many rows).

min property

min: int

Smallest allowed size.

size property

size: int

Current size.

KernelMask

KernelMask(size: KernelSize)

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.

active property

active: int

Number of active rows.

founds property

founds: list[bool]

Copy of the mask as a plain list of booleans.

BufferIndex

BufferIndex(buffer: NDArrayType, mask: KernelMask, sense: SenseType)

Ranking and best/worst lookups over the buffer's fitness column.

Parameters:

Name Type Description Default
buffer NDArrayType

The raw (pop, ndim + 1) buffer (fitness in column 0).

required
mask KernelMask

The active-row mask.

required
sense SenseType

"min" or "max"; selects the direction of "best".

required

Attributes:

Name Type Description
sort NDArray[intp]

Row indices ordered best-first (respecting sense).

best intp

Row index of the best individual.

worst intp

Row index of the worst individual.

Initialize the lookups over buffer and mask.

sort property

sort: NDArray[intp]

Row indices ordered best-first (respecting sense).

best property

best: intp

Row index of the best individual.

worst property

worst: intp

Row index of the worst individual.

Objectives

Target

Bases: Protocol

Protocol for an objective: a callable mapping a solution to a score.

TargetFunction

TargetFunction(target: Target, bounds: Bounds, max_nfe: int | None = None)

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 means unlimited.

None

Attributes:

Name Type Description
nfe int

Evaluations spent so far.

max float | int

The budget (inf when unlimited).

bounds Bounds

The search space.

vectorized bool

Whether the target scores whole blocks.

Wrap target, counting evaluations against the max_nfe budget.

nfe property

nfe: int

Evaluations spent so far.

max property

max: float | int

The budget (inf when unlimited).

bounds property

bounds: Bounds

The search space.

vectorized property

vectorized: bool

Whether the target scores whole blocks.

evaluate

evaluate(x: NDArrayType) -> NDArrayType | typing.Any

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 (1, ndim) block.

required

Returns:

Type Description
NDArrayType | Any

The fitness of that individual.

evaluate_matrix

evaluate_matrix(x: NDArrayType) -> NDArrayType

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

VectorizedTarget(target: Target)

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

Bounds(bounds: SequenceStructure[ScalarType])

Search-space bounds: one (low, up) pair per dimension.

Parameters:

Name Type Description Default
bounds SequenceStructure[ScalarType]

A sequence of (low, up) pairs, one per dimension. The number of pairs defines ndim.

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.

ndim cached property

ndim: int

Number of dimensions (length of the bounds sequence).

low property

low: Any

Lower bound of the first dimension.

up property

up: Any

Upper bound of the first dimension.

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 (low, up, ndim).

buff KernelBuffer

The buffer backing the population.

rng Generator

Seeded random generator.

sense SenseType

"min" or "max".

epoch int

Current epoch index.

epochs int

Total number of epochs.

Wrap the run resources into a per-epoch view.

target property

target: TargetFunction

The wrapped objective (counts NFE, enforces any budget).

bounds property

bounds: Bounds

The search space (low, up, ndim).

buff property

buff: KernelBuffer

The buffer backing the population.

rng property

rng: Generator

Seeded random generator.

sense property

sense: SenseType

"min" or "max".

epoch property

epoch: int

Current epoch index.

epochs property

epochs: int

Total number of epochs.

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.

False
sense SenseType

"min" (default) or "max".

'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.

epoch_it property

epoch_it: EpochIteration

The epoch iterator driving the run.

buffer property

buffer: KernelBuffer

The population buffer.

tracker property

tracker: Tracker

The per-epoch history recorder.

context

context() -> Context

Build the per-epoch Context view over the run's resources.

EpochIteration

EpochIteration(epochs: int, tracker: Tracker, target: TargetFunction, debug: bool = False)

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 debug is true.

required
target TargetFunction

Objective wrapper used to read the function-evaluation count (NFE).

required
debug bool

Record a history snapshot per epoch. Default False.

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.

current property

current: int

Index of the epoch most recently yielded.

max property

max: int

Total number of epochs.

cpu_time property

cpu_time: float

Wall CPU time spent in the most recent epoch body.

Tracker

Tracker(buff: KernelBuffer)

Records per-epoch snapshots of the population buffer.

Parameters:

Name Type Description Default
buff KernelBuffer

The buffer whose state is snapshotted on every track.

required

Attributes:

Name Type Description
history list[EpochHistory]

Immutable copies of the tracked epochs, oldest first.

Initialize the recorder over buff.

history property

history: list[EpochHistory]

Immutable copies of the tracked epochs, oldest first.

track

track(e: int, timeit: float, nfe: int) -> None

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

DefaultGenerator(seed: int | None = None)

Seeded random generator handed to models as ctx.rng.

Parameters:

Name Type Description Default
seed int | None

Seed for the underlying numpy.random.Generator. None seeds from OS entropy (non-deterministic).

None

Attributes:

Name Type Description
rng Generator

The live random generator used for sampling.

Create the underlying numpy.random.Generator from seed.

rng property

rng: Generator

The live random generator used for sampling.

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).

initialize

initialize(ctx: Context) -> None

Seed the population once before the first epoch.

evolve

evolve(e: int, ctx: Context) -> None

Advance the population one epoch (e is the epoch index).

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

FunctionParamsArguments(type_dict: dict[str, type[Any]])

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 (Annotated metadata carries the range/default).

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

load(values_dict: dict[str, Any]) -> None

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.

NDArrayType module-attribute

NDArrayType = npt.NDArray[np.number[typing.Any]]

ArrayFloatType module-attribute

ArrayFloatType = npt.NDArray[np.floating[typing.Any]]

ArrayIntegerType module-attribute

ArrayIntegerType = npt.NDArray[np.integer[typing.Any]]

ScalarType module-attribute

ScalarType = typing.TypeVar('ScalarType', bound=np.number[typing.Any])

SenseType module-attribute

SenseType = typing.Literal['min', 'max']