Skip to content

Functions

Every decorator and free function the framework exposes, grouped by role. Classes live in Classes; the packages themselves are described in Modules.

Declaration decorators

The two ways to declare a model (declare function-style, template class-style), the Operator Module decorator, and the vectorized-objective decorator.

declare

declare(**kwargs: Any) -> typing.Callable[[AlgorithmFunction], FunctionOptimizerModel]

Turn a function into a model (the function-style API).

The decorated function receives (args, epoch, ctx) and runs the whole optimization inside its body. Parameters are declared with cm.Argument and bound by calling the returned model.

Parameters:

Name Type Description Default
**kwargs Any

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

{}

Returns:

Type Description
Callable[[AlgorithmFunction], FunctionOptimizerModel]

A decorator wrapping the function in a FunctionOptimizerModel.

Examples:

::

@cm.declare(x=cm.Argument[int, (0, 3), 2])
def my_algorithm(args, epoch, ctx): ...

model = my_algorithm(x=1)

template

template(model: type[ModelProtocol]) -> TemplateOptimizerModel

Turn a class into a model (the class-style API).

The class must define initialize(self, ctx) and evolve(self, e, ctx); fields are declared with cm.Argument / cm.Variable / cm.Constant. cm.Constant fields are read-only and never bound by the constructor. Kernels declared on the class receive the model's compile options (numba/parallel/fastmath/cache) at instantiation, and prepare=True compiles them right away.

Parameters:

Name Type Description Default
model type[ModelProtocol]

The class to wrap.

required

Returns:

Type Description
TemplateOptimizerModel

A model wrapping the class.

Raises:

Type Description
TypeError

If model is not a class.

Examples:

::

@cm.template
class MyAlgorithm:
    a: cm.Argument[int, (1, 100)]

    def initialize(self, ctx) -> None: ...
    def evolve(self, e, ctx) -> None: ...

module

The module decorator: a reusable Operator Module (Ruby-style mixin).

module

module(cls: type[_ModuleT]) -> type[_ModuleT]

Mark cls as a reusable Operator Module that models can mix in.

A class decorated with @cm.module behaves like a Ruby module: it groups metaheuristic operators — cm.precompile / cm.vectorize / cm.reduce kernels, plain helper methods and cm.Argument / cm.Variable / cm.Constant fields — so several @cm.template models can inherit the same behavior. Note that @cm.module returns a class, not a Python module.

The decorator keeps the class identity and materializes its cm.Constant annotations, so a constant is reachable (MyOps.P) even before any model includes the mixin. Mixin application is ordinary inheritance; name collisions resolve through the normal MRO, with the leftmost base winning.

Parameters:

Name Type Description Default
cls type[_ModuleT]

The Operator Module class to mark.

required

Returns:

Type Description
type[_ModuleT]

The same class, with its cm.Constant fields materialized.

Raises:

Type Description
TypeError

If cls is not a class (for example a @cm.template model instance, which is not reusable as a mixin).

Examples:

::

@cm.module
class Selection:
    pressure: cm.Constant[float, 1.5]

    @cm.vectorize
    def clamp(x: cm.Array, lo: cm.Scalar, hi: cm.Scalar):
        return min(max(x, lo), hi)

@cm.template
class GA(Selection):
    def evolve(self, e, ctx) -> None:
        ...  # can use self.pressure and self.clamp(...)

vectorized_target

vectorized_target(target: Target) -> VectorizedTarget

Declare target as able to evaluate a whole (pop, ndim) block.

The wrapped callable receives a 2-D array and must return one value per row, so np.sum(x**2, axis=1) replaces a per-row comprehension. The result is identical to the row-by-row evaluation, only dispatched once.

Examples:

::

def sphere(x):           # x: (pop, ndim) -> (pop,)
    return np.sum(x**2, axis=1)

model.solve(cm.vectorized_target(sphere), bounds, 100, 40)

Kernel decorators

Numba kernel decorators, re-exported at the top level, so cmenpy.precompile and cmenpy.compile.precompile are the same object.

precompile

numba.njit kernel decorators (precompile and the deprecated jit).

vectorize

The cm.vectorize decorator (numba @vectorize targets).

reduce

The cm.reduce decorator (numba guvectorize) and the Contract marker.

Contract

Signature marker for reduce, e.g. Contract[[...], out].

Each input/output is a cast spec (Array / Scalar) or a plain dtype. A plain dtype is shorthand for Array[dtype, "n"]; ... is a scalar of default float dtype. Array[dtype] is a whole-array argument with a private dimension, and Array[dtype, "m,n"] names its dimensions::

Contract[[float, float, ..., ..., ...], float]          # (n),(n),(),(),()->(n)
Contract[[float, Array[float]], float]                   # (n),(k)->(n)
Contract[[Array[float, "m,n"], Array[float, "n,k"]],
         Array[float, "m,k"]]                            # (m,n),(n,k)->(m,k)

jit

Deprecated cm.jit alias of cm.precompile.

jit

jit(*args: Any, fastmath: bool = False, parallel: bool = False, **kwargs: Any) -> typing.Any

Deprecated alias of precompile.

Signature markers

Typing markers that appear in kernel signatures: the Array/Scalar spec markers and the Contract signature marker for reduce.

Array module-attribute

Array = _ArraySpec()

Scalar module-attribute

Scalar = _ScalarSpec()

Contract

Signature marker for reduce, e.g. Contract[[...], out].

Each input/output is a cast spec (Array / Scalar) or a plain dtype. A plain dtype is shorthand for Array[dtype, "n"]; ... is a scalar of default float dtype. Array[dtype] is a whole-array argument with a private dimension, and Array[dtype, "m,n"] names its dimensions::

Contract[[float, float, ..., ..., ...], float]          # (n),(n),(),(),()->(n)
Contract[[float, Array[float]], float]                   # (n),(k)->(n)
Contract[[Array[float, "m,n"], Array[float, "n,k"]],
         Array[float, "m,k"]]                            # (m,n),(n,k)->(m,k)

Builders and factories

The helpers that turn a declaration into a runnable model, and the small factories for bounds and buffers.

declare_from_func

declare_from_func(func: AlgorithmFunction, **kwargs: Any) -> FunctionOptimizerModel

Bind func to a fresh FunctionOptimizerModel built from kwargs.

Parameters:

Name Type Description Default
func AlgorithmFunction

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

required
kwargs Any

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

{}

Returns:

Type Description
FunctionOptimizerModel

The model wrapping func.

Raises:

Type Description
TypeError

If any field is a cm.Constant. Constants are a class-style feature (@cm.template / @cm.module) and are never constructor-bound, so they have no meaning in the function style.

declare_from_class

declare_from_class(cls: type[ModelProtocol]) -> TemplateOptimizerModel

Wrap cls in a TemplateOptimizerModel with a dynamic __init__.

The generated __init__ extracts the compile options (numba/ parallel/fastmath/cache), reads the class type hints (Annotated metadata carries ranges and defaults), validates the arguments and stores them as instance attributes before delegating to the original __init__.

numba controls whether the class kernels are compiled: False runs them as pure Python/NumPy, True demands compilation (ImportError without numba), and leaving it out compiles when numba is available. prepare forces compilation at construction: prepare=True compiles (or reports) every kernel during __init__ — the equivalent of calling model.prepare() immediately — while prepare=False (the default) keeps compilation lazy.

cm.Constant fields are materialized as read-only class descriptors by install_constants and skipped by the generated __init__: they are never constructor-bound, so passing one raises TypeError.

Parameters:

Name Type Description Default
cls type[ModelProtocol]

The class to wrap; must define initialize and evolve.

required

Returns:

Type Description
TemplateOptimizerModel

The model wrapping cls.

Raises:

Type Description
TypeError

If a cm.Constant field is passed to the constructor.

build_context_manager

build_context_manager(f: Target, bounds: Bounds | SequenceStructure[ScalarType], epochs: int, pop_size: int, pop_range: tuple[int, int] | None, seed: int | None, debug: bool, sense: SenseType) -> MainContextManager

Validate the population size and build a MainContextManager.

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

Initial population size.

required
pop_range tuple[int, int] | None

(min, max) allowed population sizes.

required
seed int | None

Random seed.

required
debug bool

Record per-epoch history.

required
sense SenseType

"min" (default) or "max".

required

Returns:

Type Description
MainContextManager

The wired per-run resource holder.

Raises:

Type Description
IndexError

If pop_size falls outside pop_range.

create_bounds

create_bounds(bounds: SequenceStructure[ScalarType] | Bounds) -> Bounds

Coerce bounds into a Bounds, passing instances through.

Parameters:

Name Type Description Default
bounds SequenceStructure[ScalarType] | Bounds

Either an already-built Bounds or a sequence of (low, up) pairs.

required

Returns:

Type Description
Bounds

A Bounds instance wrapping the input.

init_buffer

init_buffer(n_pop: int, ndim: int) -> NDArrayType

Allocate a (n_pop, ndim + 1) buffer filled with NaN.

Parameters:

Name Type Description Default
n_pop int

Number of rows (population capacity).

required
ndim int

Number of solution dimensions (the +1 column holds fitness).

required

Returns:

Type Description
NDArrayType

The freshly allocated NaN buffer.

Introspection

kernels

Collecting the numba signatures of the kernels declared on a class.

kernels

kernels(cls: type[Any], compile_options: dict[str, Any] | None = None) -> dict[str, list[str]]

Return the numba kernels declared on cls and its bases.

Names are resolved through the MRO, so an operator mixin inherited by a @cm.template model is reported too, and a subclass redefinition wins over the base entry.

prepare

Kernel preparation and signature introspection helpers (cm.prepare).

Casting

Explicit casting helper for population views and array-like values.

cast

cast(value: Any, dtype: DTypeLike | None = None, *, layout: Literal['A', 'C', 'F'] = 'A') -> typing.Any

Cast a cmenpy view or array-like to an ndarray with a dtype and layout.

Buffer views (pop.X/pop.F) are unwrapped through their explicit to_numpy conversion, so cm.cast never relies on NumPy's implicit __array__ cast.

Parameters:

Name Type Description Default
value Any

A cmenpy buffer view, an array, a list, or a scalar.

required
dtype DTypeLike | None

Target dtype; None keeps the original one.

None
layout Literal['A', 'C', 'F']

Storage order for arrays. "A" (default) leaves the array as it is; "C"/"F" return a contiguous array, which is what a typed cm.Array kernel signature expects.

'A'

Returns:

Type Description
Any

An ndarray (or a NumPy scalar when value is a scalar and a

Any

dtype is requested).

Examples:

::

x = cm.cast(pop.X[:n], self.dtype)
block = cm.cast(pop.X, float, layout="C")

Comparators

Sense-aware fitness comparators used by selection operators.

is_best

is_best(ab: AB[Any, Any], sense: SenseType = 'min') -> npt.NDArray[np.intp]

Indices where the first element of the pair beats the second.

Parameters:

Name Type Description Default
ab AB[Any, Any]

A (new, old) pair of fitness arrays (or scalars) to compare.

required
sense SenseType

"min" (default) or "max"; selects the direction of "better".

'min'

Returns:

Type Description
NDArray[intp]

Integer indices where new is better than old.

is_worst

is_worst(ab: AB[Any, Any], sense: SenseType = 'min') -> npt.NDArray[np.intp]

Indices where the first element of the pair is worse than the second.

Parameters:

Name Type Description Default
ab AB[Any, Any]

A (new, old) pair of fitness arrays (or scalars) to compare.

required
sense SenseType

"min" (default) or "max"; selects the direction of "worse".

'min'

Returns:

Type Description
NDArray[intp]

Integer indices where new is worse than old.

best_index

best_index(values: ArrayLike, sense: SenseType = 'min') -> int

Index of the best value in values.

Parameters:

Name Type Description Default
values ArrayLike

Fitness values to scan.

required
sense SenseType

"min" (default) or "max".

'min'

Returns:

Type Description
int

Index of the minimum ("min") or maximum ("max") value.

worst_index

worst_index(values: ArrayLike, sense: SenseType = 'min') -> int

Index of the worst value in values.

Parameters:

Name Type Description Default
values ArrayLike

Fitness values to scan.

required
sense SenseType

"min" (default) or "max".

'min'

Returns:

Type Description
int

Index of the maximum ("min") or minimum ("max") value.