# Core API Signatures and docstrings for the modules most users touch. Generated directly from the sources at build time. ## clypto/optimizer/native/optimizer Engine root of ``LegacyOptimizer`` (``cy.Optimizer``). Source: [`clypto/optimizer/native/optimizer.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/native/optimizer.pyx) ### `NativeOptimizer` ```python class NativeOptimizer(self, parameters, sort_flag, name, mode) ``` #### `__init__(self, parameters, sort_flag, name, mode)` #### `termination(self)` #### `nf_counter(self)` Evaluations of the current (or last) ``solve()``. #### `parameters(self)` Current values of the registered hyper-parameters. #### `parameters(self, parameters)` Register hyper-parameter names (list/tuple) or override their values (dict). #### `set_parameters(self, names)` Register hyper-parameter names. #### `initialize_variables(self)` Set up algorithm state once the problem is bound (before the population exists). #### `initialize(self)` Hook to set up algorithm state once the problem is bound and population is initialized. #### `initialization(self)` Create the initial population. #### `before_main_loop(self)` #### `solve(self, problem, termination, starting_solutions, seed, debug, track_population, threads, before_iteration, after_iteration, metrics)` ## clypto/optimizer/native/legacy The engine of the collection (``cy.Optimizer``): the population is a :class:`Population` of agents. Source: [`clypto/optimizer/native/legacy.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/native/legacy.pyx) ### `_snapshot_agent(agent)` An independent copy of ``agent`` (``snapshot``): the solution vector is copied, the rest shared. ### `LegacyOptimizer` ```python class LegacyOptimizer(self, parameters, sort_flag, epoch, pop_size, **kwargs) ``` #### `__init__(self, parameters, sort_flag, epoch, pop_size, **kwargs)` #### `bounds(self)` The bounds of the bound problem (None before solve()). #### `pop_size(self)` The configured population size (``population.size()``). #### `pop_size(self, value)` #### `generate(self, agent, solution)` Hook the algorithm may override to lay extra per-agent state. #### `generate_agent(self, solution)` One initial agent, evaluated. Stateful algorithms override it to lay the per-agent state that used to live on their agent subclasses. #### `initialization(self)` Create the initial population: ``Population.fill`` generates through the factory. ## clypto/optimizer/native/problem The optimization problem: an objective over a :class:`Bounds` search space. Source: [`clypto/optimizer/native/problem.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/native/problem.pyx) ### `Problem` ```python class Problem(self, bounds, sense, obj_func, name, evaluator, obj_weights, vectorized, seed, decode, **kwargs) ``` ``Problem(bounds, sense="min", obj_func=f)``. ```text ``bounds`` is a :class:`Bounds`, one block or a list of blocks. ``vectorized=True``: ``obj_func`` takes an ``(n, n_dims)`` matrix and returns ``(n,)`` or ``(n, n_objs)``. ``evaluator`` is an optional nogil batch evaluator used by ``evaluate(X, parallel=True)``. ``obj_weights`` turn several objectives into one fitness (default: all ones). ``n_evals`` counts the evaluations (``evaluate_solution`` and ``evaluate``); ``solve()`` resets it, and ``optimizer.nf_counter`` reads it. ``` #### `__init__(self, bounds, sense, obj_func, name, evaluator, obj_weights, vectorized, seed, decode, **kwargs)` #### `coerce(problem, seed)` ``problem`` (a ``Problem`` or the dict of its arguments) seeded with ``seed``. #### `bounds(self)` #### `sense(self)` #### `name(self)` #### `evaluator(self)` #### `vectorized(self)` #### `decode(self)` #### `n_evals(self)` #### `n_evals(self, value)` #### `n_dims(self)` #### `seed(self)` #### `seed(self, seed)` #### `obj_weights(self)` The objective weights (materialized by the first ``n_objs`` access). #### `n_objs(self)` Number of objectives; the first access evaluates one random solution. #### `obj_func(self, x)` #### `encode_solution(self, values)` #### `decode_solution(self, x)` #### `correct_solution(self, x)` A valid solution, or ``(n, n_dims)`` matrix of them. #### `generate_solution(self, encoded)` #### `evaluate_solution(self, solution)` The objectives of one solution (counted). #### `fitness(self, objectives)` Fitness of each ``(k, n_objs)`` objective row, computed like ``Agent.fitness``. #### `evaluate(self, X, parallel, threads)` ``(fitness, objectives)`` of every row of ``X``: ``(k,)`` and ``(k, n_objs)``. ```text ``parallel=True`` with a nogil ``evaluator`` runs the rows on the OpenMP team fixed by the engine's ``solve`` (``threads`` 0 lets OpenMP decide); otherwise ``obj_func`` is called once per row, or once for the whole matrix when the problem is ``vectorized``. ``` ## clypto/optimizer/bounds Search-space blocks and the ``Bounds`` that concatenates them. Source: [`clypto/optimizer/bounds.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/bounds.pyx) ### `BaseBounds` ```python class BaseBounds(self, low, up, name) ``` One block of ``n_vars`` decision variables with its own random stream. #### `__init__(self, low, up, name)` #### `n_vars(self)` #### `seed(self)` #### `seed(self, seed)` #### `encode(self, value)` Values (decoded type) -> ``float64`` slice of the search vector. #### `correct(self, x)` A moved slice -> a valid slice. #### `decode(self, x)` Slice of the search vector -> values of ``value_type``. #### `generate(self)` Random values of ``value_type`` drawn from this block's stream. ### `NumberBounds` ```python class NumberBounds(self, value_type, low, up, n_vars, name) ``` ``n_vars`` numbers of ``value_type`` (``float``, ``int`` or ``bool``) in ``[low, up]``. ```text ``low``/``up`` are scalars (broadcast to ``n_vars``, default 1) or sequences. ``bool`` defaults to ``low=0, up=1``. ``` #### `__init__(self, value_type, low, up, n_vars, name)` #### `decode(self, x)` #### `generate(self)` ### `TransferBounds` ```python class TransferBounds(self, value_type, n_vars, tf_func, low, up, all_zeros, name) ``` ``n_vars`` binary values (``int`` 0/1 or ``bool``) moved on ``[low, up]``. ```text ``correct`` maps each coordinate through ``tf_func`` (a name from ``clypto.optimizer.transfer``) to the probability of a 1 and samples it. ``all_zeros=False`` forbids the all-zero vector. ``` #### `__init__(self, value_type, n_vars, tf_func, low, up, all_zeros, name)` #### `correct(self, x)` #### `decode(self, x)` #### `generate(self)` ### `StringBounds` ```python class StringBounds(self, valid_sets, name) ``` One label per variable, chosen from that variable's set (any hashable labels). ```text ``valid_sets`` is one set (one variable) or a sequence of sets (one each). ``` #### `__init__(self, valid_sets, name)` #### `encode(self, value)` #### `decode(self, x)` #### `generate(self)` ### `SequenceBounds` ```python class SequenceBounds(self, valid_sets, return_type, name) ``` One variable whose value is one of ``valid_sets`` (sequences), returned as ``return_type``. #### `__init__(self, valid_sets, return_type, name)` #### `decode(self, x)` ### `PermutationBounds` ```python class PermutationBounds(self, valid_set, name) ``` An ordering of ``valid_set``: random keys in ``[0, n - 1]``, decoded by ``argsort``. #### `__init__(self, valid_set, name)` #### `encode(self, value)` #### `decode(self, x)` #### `generate(self)` ### `Bounds` ```python class Bounds(self, *blocks) ``` The search space: blocks concatenated into one ``float64`` vector. ```text ``Bounds(block, [block, ...], ...)``; unnamed blocks are named ``x0``, ``x1``, ... by position, and names must be unique. ``low``/``up`` span the whole vector and ``dtype`` is always ``float64``. ``` #### `__init__(self, *blocks)` #### `n_dims(self)` #### `seed(self)` #### `seed(self, seed)` #### `encode(self, values)` One value (or sequence of values) per block -> search vector. #### `correct(self, x)` Valid search vector (or ``(n, n_dims)`` matrix of them). #### `decode(self, x)` Search vector (or 2D matrix of them) -> ``{name: value}`` (or list of them). #### `generate(self)` A random search vector (every block draws from its own stream). ## clypto/optimizer/native/population ``Population`` (the single, final container of agents) and the bounds-repair functions. Source: [`clypto/optimizer/native/population.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/native/population.pyx) ### `Population` ```python class Population(self, size, agents, factory) ``` Ordered, mutable sequence of agents, ranked by the bound problem's ``sense``. ```text ``size()`` is the configured number of agents (``pop_size``); ``len()`` is how many it holds right now. Slices, ``+``, ``sort()`` and ``greedy()`` give new populations of the same problem. ``fitness``/``solutions`` are arrays built from the agents; assigning ``solutions`` writes each row back to its agent. ``` #### `__init__(self, size, agents, factory)` #### `factory(self)` The agent factory of this population; assigning one re-binds the problem. #### `factory(self, factory)` #### `bind(self, problem, generator)` Attach the problem and the seeded generator, and drop the agents of a previous run. #### `spawn(self, agents)` A population bound to the same problem holding ``agents`` (a list is wrapped, not copied). #### `empty(self)` An empty population bound to the same problem, generator and settings. #### `snapshot(self)` A population of copies (``duplicate_agent``) of every agent. #### `copy(self)` Shallow copy: the same agent objects, bound to the same problem. #### `size(self)` The configured number of agents (``pop_size``). #### `resize(self, n)` #### `toarray(self)` The agents, as the live list (a typed ``for`` over it is a C loop). #### `sense(self)` #### `create_agent(self, solution)` A new, not yet evaluated agent at ``solution`` (random when ``None``); the factory owns it. #### `generate_agent(self, solution)` ``create_agent`` then evaluate it; the factory owns the per-agent state. #### `fill(self, starting)` Generate (through the factory) the ``size()`` agents, or one per ``starting`` solution. #### `add(self, solution)` Generate an agent (through the factory), append it and return it. #### `remove_at(self, index)` Remove and return ``agents[index]`` (negative indices follow the list rules). #### `generate(self, n, starting)` A population of ``n`` (default ``size()``) generated agents, or one per ``starting`` solution. #### `evaluate_solution(self, solution)` An evaluated plain :class:`Agent` at ``solution`` (a candidate; no random draws). #### `evaluate(self, agents, mode)` Evaluate ``agents`` (the batch step) and return them. ```text ``"sequential"`` evaluates only the agents not evaluated yet (an algorithm that evaluates one by one has done it already); ``"batch"``/``"parallel"`` evaluate every agent. The batch is one ``problem.evaluate(X)`` call, on OpenMP threads in ``"parallel"`` mode when the problem has a nogil evaluator (``self.threads`` fixes the team size, 0 lets OpenMP decide). ``` #### `insert(self, index, agent)` #### `append(self, agent)` #### `extend(self, agents)` #### `pop(self, index)` #### `popleft(self)` #### `remove(self, agent)` #### `clear(self)` #### `index(self, agent, *args)` #### `count(self, agent)` #### `reverse(self)` #### `fitness(self)` ``(n,)`` fitness of every agent. #### `solutions(self)` ``(n, n_dims)`` solution matrix. #### `solutions(self, values)` #### `argsort(self)` Positions best first (``np.argsort`` of the fitness, reversed when maximizing). #### `sort(self)` New population, best first. #### `selected(self, order)` The agents at ``order`` (positions of ``argsort``), as a plain list. #### `top(self, k)` The ``k`` best agents, best first (a partial ``sort()[:k]``). #### `bottom(self, k)` The ``k`` worst agents, worst first. #### `best(self)` The first agent of the best fitness (strictly better replaces; ties keep the first). #### `worst(self)` The first agent of the worst fitness (ties keep the first). #### `greedy(self, candidates, mode)` Per position, the candidate when better, else the current agent (``greedy_agents``, same ``mode`` rule). ### `population(size, range, cls)` An unbound population of ``size`` agents (``cls`` is ignored: the population is a single class). ### `population_with_factory(size, factory, range)` ``cy.population(size, factory)`` with the agent factory attached. ```text Pass both positionally (``cy.population_with_factory(pop_size, MyAgents(self))``) — a ``factory=`` keyword would make Cython fall back to a Python-space call. ``` ### `empty_snapshot(population)` An empty population of the same problem and state. ### `snapshot(population)` A population holding a copy (``duplicate_agent``) of every agent. ### `correct_solution(problem, solution)` Clip ``solution`` to the bounds, then apply the problem's own correction. ### `reset_solution(problem, generator, solution)` Redraw the out-of-bounds values of ``solution`` uniformly, then apply the problem's own correction. ```text The draw covers every dimension (one ``generator.uniform(low, up)`` call), as the clip-free MEALPY repair did. ``` ### `opposite_solution(problem, generator, agent, g_best)` Opposition-based candidate of ``agent`` around ``g_best``, corrected. ## clypto/optimizer/native/agent ``Agent``: a single, fixed-layout data structure for agent state. Source: [`clypto/optimizer/native/agent.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/native/agent.pyx) ### `duplicate_agent(agent)` New agent of the same dynamic type: solution and evaluation shared (references), state copied field by field. ```text The engine's canonical copy (Python callers use ``agent.copy()``). Hooks are virtual: a subclass carries its extra state by overriding ``_new_instance`` and ``_copy_state_to`` (the base fields go first, always); it must never override ``copy`` itself. ``` ### `sync_if_duplicate(that, other)` Give ``that`` the evaluation of ``other`` when their solutions match (atol 1e-6). ### `better_fitness(x, y, sense)` True when fitness ``x`` is better than ``y``: ``x < y`` for min, ``not (x < y)`` for max. ### `is_better(x, y, sense)` True when agent ``x`` is better than ``y`` (``better_fitness`` of their fitness). ### `get_better_agent(x, y, sense, reverse)` Copy of the better agent; a tie keeps ``y`` when minimizing, ``x`` when maximizing. ### `argsort_agents(agents, sense)` Positions best first (``np.argsort`` of the fitness, reversed when maximizing). ### `greedy_agents(old, new, sense, mode)` Per position, the ``new`` agent when better, else the ``old`` one (lists of equal length). ```text The batch modes keep ``new`` only when strictly better. ``mode="sequential"`` applies the one-by-one rule of ``get_better_agent`` (``better_fitness``: when maximizing, a tie keeps ``new``), so an algorithm that evaluates its whole batch at once keeps its sequential results exactly. ``` ### `sort_agents(agents, sense)` The agents best first (see ``argsort_agents``). ### `Agent` ```python class Agent(self, solution, objectives, weights) ``` #### `__init__(self, solution, objectives, weights)` #### `evaluate(self, problem)` Evaluate ``solution`` on ``problem`` (counted in ``problem.n_evals``). #### `update_solution(self, other, solution)` Take the evaluation of ``other`` and move to ``solution`` (default: a copy of ``other.solution``). ```text ``solution`` is stored as given, so ``agent.update_solution(candidate, pos_new)`` keeps ``pos_new`` itself; ``agent.update_solution(other, agent.solution)`` only takes the evaluation. ``` #### `copy(self)` The copy protocol's Python face: ``duplicate_agent(self)`` (never override it). #### `snapshot(self)` A ``copy`` whose solution vector is independent of this agent's. ## clypto/optimizer/native/utils Helpers for algorithms: hyper-parameter validation and the random operators. Source: [`clypto/optimizer/native/utils.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/native/utils.pyx) ### `_in_bound(value, bound)` ### `_is_real_number(value)` ### `validator(dtype, value, bound, name)` ``value`` as ``dtype`` (``int``, ``float``, ``str`` or ``bool``) when it lies in ``bound``, else ``TypeError``. ```text Numbers: ``bound`` is a ``tuple`` (exclusive) or ``list`` (inclusive) pair. ``str``: ``bound`` lists the allowed values. ``bool``: default ``(True, False)``. ``` ### `check_is_int_and_float(name, value, bound_int, bound_float)` An ``int`` in ``bound_int`` or a ``float`` in ``bound_float`` (e.g. a count or a ratio). ### `levy_flight(generator, beta, multiplier, size, case)` Levy-flight step of shape ``size``. ```text ``beta`` in [0, 2] (0-1 exploit, 1-2 explore). ``case`` 0 scales by a uniform draw, 1 by a normal draw, -1 not at all. ``` ### `roulette_wheel(generator, sense, fitness)` Roulette-wheel index for a min or max problem; handles negative fitness. ### `kway_tournament(generator, sense, agents, k_way, output, reverse)` Indexes of the ``output`` best (``reverse``: worst) of ``k_way`` random agents. ### `split_groups(agents, n_groups, m_agents)` ``n_groups`` groups of ``m_agents`` consecutive agents (copies). ## clypto/optimizer/history/tracker ``Tracker``: the per-run history held in ``optimizer.tracker``. Source: [`clypto/optimizer/history/tracker.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/history/tracker.pyx) ### `MetricDef` ```python class MetricDef(self, name, func, takes_positions, takes_fits) ``` #### `__init__(self, name, func, takes_positions, takes_fits)` ### `MetricSchema` ```python class MetricSchema(self, cls, names, col_map, idx_gbest, idx_cbest, idx_cworst, idx_mean, idx_std, idx_time, idx_nfe, idx_pop, idx_diversity, idx_exploration, idx_exploitation, custom_callers, has_finalize) ``` #### `__init__(self, cls, names, col_map, idx_gbest, idx_cbest, idx_cworst, idx_mean, idx_std, idx_time, idx_nfe, idx_pop, idx_diversity, idx_exploration, idx_exploitation, custom_callers, has_finalize)` ### `_build_metric_schema(cls)` ### `metrics(cls)` Pydantic-style class decorator defining per-epoch metrics. ```text Methods can accept ``positions: np.ndarray``, ``fits: np.ndarray``, or both, and must return a ``float``. ``` ### `DefaultMetrics` ```python class DefaultMetrics ``` Canonical continuous per-epoch metrics matching mealpy-lts. #### `diversity(self, positions)` ### `resolve_schema(metric_spec)` Resolve metric class/instance/None into ``(MetricSchema, instance)``. ### `MetricBuffer` ```python class MetricBuffer(self) ``` Per-epoch metrics in one fixed ``(epoch, metrics)`` matrix. #### `__init__(self)` #### `allocate(self, max_epochs, schema, instance)` One ``(max_epochs, n_metrics)`` matrix, ready for ``record``. #### `reset(self)` Drop the matrix; ``allocate`` will recreate it on the next start. #### `n_epochs(self)` Number of recorded epochs. #### `buffer(self)` The live matrix (or ``None`` before ``allocate``). #### `record(self, positions, fits, runtime, nfe, global_best_fit, minimize)` Append one epoch's statistics computed from the population arrays. #### `finalize(self)` Derive exploration/exploitation and trim to ``n_epochs`` fresh columns. ### `SnapshotBuffer` ```python class SnapshotBuffer(self) ``` Population frames per epoch, one NaN-padded array per capture field. ```text Solutions, fitness and objectives (multi-objective only) are grown by doubling when an epoch needs more rows or a wider population than before; ``finalize`` copies the exact ``(epochs, max_pop, ...)`` arrays. ``` #### `__init__(self)` #### `reset(self)` #### `n_objs(self)` Objectives per agent, decided by the first recorded frame (``None`` before it). #### `record(self, positions, fits, objectives)` Append one epoch's frames (positions, fitness, objectives when multi-objective). #### `finalize(self)` ``(solution, fitness, objectives)`` arrays with exact shapes, plus the objective frame. ### `Tracker` ```python class Tracker(self) ``` The run history of the engine: per-epoch metrics and optional population frames. #### `__init__(self)` #### `reset(self)` Discard everything from the previous run and return to the initial state. #### `recording(self)` #### `metric_names(self)` #### `start(self, optimizer, problem, seed, capture_population, metrics)` Begin a new recording with the specified metric schema. #### `record(self, pop, runtime, nfe, global_best_fit)` Take the population's agents, buffer the metrics, and (when capturing) the frames. #### `finalize(self)` Compute the derived metrics and assemble the finished arrays. ## clypto/optimizer/precompile/declaration The ``Argument`` declaration used by ``@cy.optimizer`` classes. Source: [`clypto/optimizer/precompile/declaration.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/precompile/declaration.pyx) ### `Argument` ```python class Argument ``` Declare an optimizer hyper-parameter. ```text Example:: @cy.optimizer(agent=MyAgent) class MyOptimizer: a: cy.Argument[int, (1, 100), 5] c: cy.Argument[np.ndarray] The bracket syntax follows the Python typing convention and accepts ``[dtype]``, ``[dtype, bound]`` and ``[dtype, bound, default]``; ``...`` in the bound position means "no bound". Args: dtype: Expected type. ``np.array``/``np.ndarray`` accept array values. bound: Optional validation range (``tuple`` exclusive, ``list`` inclusive). default: Value used when the argument is not passed to the constructor. ``` ## clypto/optimizer/precompile/base The base class injected by ``@cy.optimizer``. Source: [`clypto/optimizer/precompile/base.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/precompile/base.pyx) ### `_coerce_argument(name, declaration, value)` ### `DecoratedOptimizer` ```python class DecoratedOptimizer(self, **kwargs) ``` Base class injected by ``@cy.optimizer``. ```text Subclasses implement ``initialize`` (optional) and ``evolve``. All other lifecycle methods — problem binding, population creation, the epoch loop, termination and returning the best agent — live here. ``` #### `__init__(self, **kwargs)` #### `initialize(self)` Hook the algorithm may override to set up ``self.population``. ```text The population is already generated (randomly, within bounds) before this runs, so a default implementation is not required. ``` #### `evolve(self, epoch)` #### `solve(self, problem, termination, seed)` Run the optimizer and return the best agent found so far (never worse than an earlier epoch). #### `evaluate_agent(self, solution)` Evaluate one solution (counted by the problem). #### `generate(self, agent, solution)` Seed extra state on a freshly created agent before it is evaluated. ```text Override this to initialise algorithm-specific attributes (velocity, memory, a tag, ...). The agent already carries the declared ``@cy.agent`` defaults and is not yet evaluated; return the agent to keep, which the base then evaluates by assigning its solution. ``` #### `generate_agent(self, solution)` Create a fully evaluated agent through the ``generate`` hook. ## clypto/optimizer/precompile/decorator The ``@cy.optimizer`` decorator. Source: [`clypto/optimizer/precompile/decorator.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/precompile/decorator.pyx) ### `optimizer(cls)` ### `optimizer(agent, compile)` ### `optimizer(cls, agent, compile)` Turn a plain class into a new-style optimizer (see module docstring). ## clypto/optimizer/agents/declaration The ``Attribute`` declaration used by ``@cy.agent`` classes. Source: [`clypto/optimizer/agents/declaration.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/agents/declaration.pyx) ### `Attribute` ```python class Attribute ``` Declare a per-agent attribute on a class decorated with ``@cy.agent``. ```text Example:: @cy.agent class MyAgent: v: cy.Attribute[int, (1, 100), 5] The bracket syntax follows the Python typing convention and accepts ``[dtype]``, ``[dtype, bound]`` and ``[dtype, bound, default]``; ``...`` in the bound position means "no bound". Args: dtype: The attribute type (e.g. ``int``, ``float``, ``bool``). bound: Optional validation range, following the validator convention (a ``tuple`` bound is exclusive, a ``list`` bound inclusive). default: Value used when an agent is generated without an explicit one. ``` ## clypto/optimizer/agents/runtime The runtime agent used by the decorator API. Source: [`clypto/optimizer/agents/runtime.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/agents/runtime.pyx) ### `RuntimeAgent` ```python class RuntimeAgent(self, solution, **attributes) ``` Solution-only agent used by ``@cy.optimizer`` when none is declared. ```text This is intentionally a plain Python class (not a Cython ``cdef`` class) so that user agent classes created by ``@cy.agent`` can inject it as a base and carry arbitrary declared attributes. ``` #### `__init__(self, solution, **attributes)` #### `solution(self)` #### `solution(self, value)` #### `objectives(self)` #### `fitness(self)` #### `copy(self)` #### `snapshot(self)` A ``copy`` whose solution vector is independent of this agent's. ## clypto/optimizer/agents/decorator The ``@cy.agent`` decorator. Source: [`clypto/optimizer/agents/decorator.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/agents/decorator.pyx) ### `agent(cls)` ### `agent(compile)` ### `agent(cls, compile)` Turn a plain class into an agent usable by ``@cy.optimizer``. ```text The class may declare per-agent attributes with :class:`Attribute`; the decorated class gains ``solution``/``fitness``/``objectives`` from :class:`RuntimeAgent`. When ``compile`` is ``True`` the class is also Cython-compiled through the same JIT builder as ``@cy.optimizer``. ``` ## clypto/optimizer/precompile/compiler Just-in-time Cython compilation for user-defined optimizers via pyximport. Source: [`clypto/optimizer/precompile/compiler.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/precompile/compiler.pyx) ### `is_precompiling()` True while a compiled module is being imported and re-runs its decorators. ### `compile_decorated(cls, source, imports)` Compile a class produced by the decorator API. ```text The globals are read from ``cls.__module__``. ``source`` may override the class source (used when a decorator injects a base the source does not name), and ``imports`` are added to the generated preamble so that injected base names resolve in the compiled module. ``` ## clypto/optimizer/precompile/decoration Shared building blocks for the ``@cy.agent``/``@cy.optimizer``/``@cy.legacy`` decorators. Source: [`clypto/optimizer/precompile/decoration.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/precompile/decoration.pyx) ### `parse_declaration_params(params)` Normalize ``Attribute[...]`` / ``Argument[...]`` parameters. ```text Accepts ``[dtype]``, ``[dtype, bound]`` and ``[dtype, bound, default]``. ``...`` (Ellipsis) in the bound position means "no bound". ``` ### `Declaration` ```python class Declaration(self, dtype, bound, default) ``` Base for the ``Attribute``/``Argument`` bracket declarations. ```text Concrete subclasses exist only so ``isinstance`` can tell an agent attribute from an optimizer argument; the storage and ``[...]`` parsing are identical. ``` #### `__init__(self, dtype, bound, default)` ### `decorate_with_base(cls, base)` Return ``cls`` with ``base`` injected as an *additional* base. ```text CPython refuses to reassign ``__bases__`` when the only base is ``object`` ("deallocator differs from 'object'"), so the decorator returns a new class that inherits from both the user class and the base. Keeping the original class in the MRO preserves zero-arg ``super()`` calls such as ``super().__init__(**kwargs)`` in a decorated class. ``` ### `collect_declarations(cls, declaration_types)` Collect declaration instances from a class and its bases. ```text Both annotations (``name: cy.Argument[...]``) and class attributes (the form the compiled source is materialized into) are recognized. ``` ### `class_source_with_base(cls, base_name, declaration_types)` Return the class source with ``base_name`` inserted into its header. ```text ``... name: cy.Argument[...]`` annotations are also turned into ordinary assignments, because Cython compiles class-body annotations as type annotations and drops them, which would erase the declarations. ``` ### `maybe_compile(decorated, enabled, source_cls, base_name, import_line, declaration_types)` Return the JIT-compiled class when ``enabled``, else ``decorated``. ```text ``source_cls`` is the original user class (needed because ``decorated`` may be an injected subclass with no source of its own). ``` ## clypto/optimizer/termination Source: [`clypto/optimizer/termination.pyx`](https://github.com/ltsim/clypto/blob/master/clypto/optimizer/termination.pyx) ### `Termination` ```python class Termination(self, max_epoch, max_fe, max_time, max_early_stop, **kwargs) ``` Define custom single/multiple Stopping Conditions (termination criteria) for the Optimizer. ```text Notes + By default, the stopping condition in the Optimizer class is based on the maximum number of generations (epochs/iterations). + Using this class allows you to override the default termination criteria. If multiple stopping conditions are specified, the first one that occurs will be used. + In general, there are four types of termination criteria: FE, MG, TB, and ES. + MG: Maximum Generations / Epochs / Iterations + FE: Maximum Number of Function Evaluations + TB: Time Bound - If you want your algorithm to run for a fixed amount of time (e.g., K seconds), especially when comparing different algorithms. + ES: Early Stopping - Similar to the idea in training neural networks (stop the program if the global best solution has not improved by epsilon after K epochs). + Parameters for Termination class, set it to None if you don't want to use it + max_epoch (int): Indicates the maximum number of generations for the MG type. + max_fe (int): Indicates the maximum number of function evaluations for the FE type. + max_time (float): Indicates the maximum amount of time for the TB type. + max_early_stop (int): Indicates the maximum number of epochs for the ES type. + epsilon (float): (Optional) This is used for the ES termination type (default value: 1e-10). + termination (dict): (Optional) A dictionary of termination criteria. Examples >>> from clypto.native.collection.vectorize.bio_based import BBO >>> import numpy as np >>> from clypto import NumberBounds >>> >>> def objective_function(solution): >>> return np.sum(solution**2) >>> >>> p1 = { >>> "bounds": NumberBounds(float, low=(-10.,) * 30, up=(10.,) * 30, name="C-params"), >>> "sense": "min", >>> "obj_func": objective_function, >>> "name": "Test Function" >>> } >>> >>> term_dict = { >>> "max_epoch": 1000, >>> "max_fe": 100000, # 100000 number of function evaluation >>> "max_time": 10, # 10 seconds to run the program >>> "max_early_stop": 15 # 15 epochs if the best fitness is not getting better we stop the program >>> } >>> model1 = BBO.OriginalBBO(epoch=1000, pop_size=50) >>> model1.solve(p1, termination=term_dict) ``` #### `__init__(self, max_epoch, max_fe, max_time, max_early_stop, **kwargs)` #### `get_name(self)` #### `set_start_values(self, start_epoch, start_fe, start_time, start_threshold)` #### `should_terminate(self, current_epoch, current_fe, current_time, current_threshold)` ## clypto/hints/array Source: [`clypto/hints/array.py`](https://github.com/ltsim/clypto/blob/master/clypto/hints/array.py) ## clypto/hints/primitives Source: [`clypto/hints/primitives.py`](https://github.com/ltsim/clypto/blob/master/clypto/hints/primitives.py) ## clypto/hints/sense Source: [`clypto/hints/sense.py`](https://github.com/ltsim/clypto/blob/master/clypto/hints/sense.py)