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 ¶
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
|
|
{}
|
Returns:
| Type | Description |
|---|---|
Callable[[AlgorithmFunction], FunctionOptimizerModel]
|
A decorator wrapping the function in a |
Examples:
::
@cm.declare(x=cm.Argument[int, (0, 3), 2])
def my_algorithm(args, epoch, ctx): ...
model = my_algorithm(x=1)
template ¶
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 |
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 ¶
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 |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
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 ¶
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)
Signature markers¶
Typing markers that appear in kernel signatures: the Array/Scalar spec
markers and the Contract signature marker for reduce.
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 ¶
Bind func to a fresh FunctionOptimizerModel built from kwargs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
AlgorithmFunction
|
The |
required |
kwargs
|
Any
|
|
{}
|
Returns:
| Type | Description |
|---|---|
FunctionOptimizerModel
|
The model wrapping |
Raises:
| Type | Description |
|---|---|
TypeError
|
If any field is a |
declare_from_class ¶
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 |
required |
Returns:
| Type | Description |
|---|---|
TemplateOptimizerModel
|
The model wrapping |
Raises:
| Type | Description |
|---|---|
TypeError
|
If a |
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
|
|
required |
seed
|
int | None
|
Random seed. |
required |
debug
|
bool
|
Record per-epoch history. |
required |
sense
|
SenseType
|
|
required |
Returns:
| Type | Description |
|---|---|
MainContextManager
|
The wired per-run resource holder. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If |
create_bounds ¶
Coerce bounds into a Bounds, passing instances through.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bounds
|
SequenceStructure[ScalarType] | Bounds
|
Either an already-built |
required |
Returns:
| Type | Description |
|---|---|
Bounds
|
A |
init_buffer ¶
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 |
Introspection¶
kernels ¶
Collecting the numba signatures of the kernels declared on a class.
kernels ¶
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
|
layout
|
Literal['A', 'C', 'F']
|
Storage order for arrays. |
'A'
|
Returns:
| Type | Description |
|---|---|
Any
|
An |
Any
|
|
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 ¶
Indices where the first element of the pair beats the second.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ab
|
AB[Any, Any]
|
A |
required |
sense
|
SenseType
|
|
'min'
|
Returns:
| Type | Description |
|---|---|
NDArray[intp]
|
Integer indices where |
is_worst ¶
Indices where the first element of the pair is worse than the second.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ab
|
AB[Any, Any]
|
A |
required |
sense
|
SenseType
|
|
'min'
|
Returns:
| Type | Description |
|---|---|
NDArray[intp]
|
Integer indices where |
best_index ¶
Index of the best value in values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ArrayLike
|
Fitness values to scan. |
required |
sense
|
SenseType
|
|
'min'
|
Returns:
| Type | Description |
|---|---|
int
|
Index of the minimum ( |