Skip to content

API Reference

The stable, public entry points of EZGA. Everything below is importable from the top-level ezga package (e.g. from ezga import QuickGA).

Quick start

QuickGA

A high-level facade for EZGA designed for simplicity and ease of use.

QuickGA allows defining and running a Genetic Algorithm experiment with minimal boilerplate, using sensible defaults and shorthand string aliases for common components.

config property

config

Lazy-loaded GAConfig.

engine property

engine

Lazy-loaded GeneticAlgorithm engine.

run

run()

Run the evolution.

Returns:

Type Description
Any

The final population or result of the evolution.

Configuration

GAConfig

Bases: BaseModel

Top-level configuration for BANS-GA (validated via Pydantic v2).

This model is intentionally strict (extra=forbid) to catch typos early, but remains assignment-validating to support programmatic modification during experiments.

Attributes:

Name Type Description
initial_generation NonNegativeInt

Starting generation index (useful for resuming runs).

max_generations PositiveInt

Maximum generations allowed before optimization stops.

min_size_for_filter PositiveInt

Minimum size of population required to trigger duplicate filtering.

foreigners NonNegativeInt

Number of foreign (randomly generated) structures injected per generation.

save_logs bool

Save history files, workflow actions, and tracking logs.

save_logs_every PositiveInt

Cadence (in generations) for writing the per-generation logger/gen_*.json snapshot when save_logs is True. 1 (default) writes every generation (historical behaviour); larger values thin the snapshot I/O for long cheap-evaluator runs.

save_generations bool

Write generational XYZ files containing coordinate dumps.

output_path Path

Output root directory path for logs, databases, and structural dumps.

resume bool

Automatically resume runs from prior outputs in output_path.

resume_mode ResumeMode

Active resume scanning mode.

mem_hiwater_mb PositiveInt | None

High-water memory limit in Megabytes (safely aborts GA if memory usage spikes).

gc_every NonNegativeInt

Cadence (in generations) for the forced gc.collect() in the memory-cleanup step. 10 (default) matches the historical behaviour; 0 disables the cadence entirely so collection happens only when mem_hiwater_mb is breached (recommended for cheap-evaluator runs whose heap stays small).

executor_restart_every NonNegativeInt

Cadence (in generations) for rotating the physics ThreadPoolExecutor. 50 (default) matches historical behaviour; 0 disables the periodic restart.

population PopulationParams

Database and structural boundary rules.

thermostat ThermostatParams

Dynamic temperature controller settings.

evaluator EvaluatorParams

Physics calculators, objectives, and feature tracking properties.

multiobjective SelectionParams

Sorting and niching parameters.

variation VariationParams

Mutation limits and crossover configuration.

mutation_funcs list[Callable[..., Any] | dict[str, Any] | str | list[Any]]

List of mutation operators applied during variation steps.

crossover_funcs list[Callable[..., Any] | dict[str, Any] | str | list[Any]]

List of crossover operators applied during variation steps.

simulator SimulatorParams

Underlying ASE calculators and evaluation modes.

convergence ConvergenceParams

Stagnation tracking and termination boundaries.

hashmap HashMapConfig

Active structural hashing fingerprint configuration.

descriptor GlobalDescriptorParams

Optional global (whole-structure) continuous descriptor (selectable/custom backend, optionally stored in metadata). Off by default.

agentic AgenticParams

Swarm agent synchronization and social adaptive policies.

ensemble EnsembleParams

Thermodynamic Monte Carlo ensemble sampler parameters.

hise HiSEParams | None

Hierarchical cell scaling options (HiSE).

generative GenerativeParams

Bayesian Optimization surrogate generator settings.

initial_population list[Any] | None

Direct, list-based insertion of starting structures.

debug bool

Activate verbose logging and engine diagnostics.

rng int | None

Global system-wide random number seed.

cast_foreigners_int classmethod

cast_foreigners_int(v)

Guards against string entries for foreigners limit.

check_relationships

check_relationships()

Performs inter-parameter safety checks and resolves system-wide seeds.

for_cheap_evaluator classmethod

for_cheap_evaluator(**overrides)

Build a config tuned for a trivial / near-trivial evaluator (microseconds).

Convenience preset that flips the fast-path knobs so the fixed per-generation bookkeeping (the "generation tax") stops dominating wall-clock when the physics is effectively free. It is pure sugar over the individual fields; each one keeps its historical default elsewhere, so this only changes what it explicitly touches:

  • population.export_overflow -> "off" (skip the config_overflow.xyz archive)
  • population.storage -> "memory" (no per-gen disk sync; NOT resumable)
  • save_generations -> False (no per-gen population XYZ dump)
  • gc_every -> 0 (gc.collect only under mem_hiwater_mb)
  • executor_restart_every -> 0 (no periodic executor rotation)
  • simulator.execution -> "inline" (no ThreadPoolExecutor round-trip)

Note it deliberately leaves evaluator.cache_objectives at its default (False): with a microsecond evaluator recomputing the objectives after a set_population re-wrap is free, so the cache buys nothing here — and it is also incompatible with the "memory" backend (see the check_relationships guard). cache_objectives is meant for the opposite regime (expensive descriptors) and remains available together with storage="composite".

Anything the caller sets explicitly wins over the preset (detected via Pydantic model_fields_set), so for_cheap_evaluator(save_generations=True, ...) keeps the dump. Pass the usual sub-configs (population, evaluator, simulator, ...) through overrides exactly as you would to GAConfig(...).

Engine

GeneticAlgorithm

High-level GA coordinator (single agent).

This class wires the modular stages and executes the per-generation loop. It assumes the heavy-cost physical model runs inside ISimulator.run(), which is overlapped with GA bookkeeping via a thread pool.

Attributes:

Name Type Description
population IPopulation

Manages the active individuals and historical datasets.

thermostat IThermostat

Controls the search temperature and adaptive cooling.

evaluator IEvaluator

Maps structures to feature vectors and objective scores.

selector ISelector

Picks parent candidates based on fitness or diversity.

simulator ISimulator

Executes the heavy-cost physical calculations (e.g. DFT, Force Fields).

variation IVariation

Orchestrates mutation and crossover operations.

generative IGenerative | None

Generates novel structural seeds or foreigners.

convergence IConvergence

Monitors for steady-state or search completion.

logger ILogger

Handles structural logging and diagnostic telemetry.

plotter IPlotter

Generates visual summaries and convergence plots.

transition ITransitionKernel | None

Manages probabilistic state transitions.

ctx Context

Shared runtime state and environment across all components.

cfg GAConfig

Master configuration settings for the search engine.

_executor ThreadPoolExecutor

Internal executor for asynchronous task overlap.

load_population

load_population()

Loads or initializes the starting dataset from IPopulation.

Expected to populate the dataset and internal indices.

Side Effects
  • I/O: reads persisted individuals if present.
  • Logging: emits timing and status messages.

run

run()

Executes the full GA workflow for one agent.

Control flow

1) Initialize environment and load population. 2) For each generation: a) Update temperature. b) Pipeline stages (Evaluation, Selection, Variation, Generation). c) Execution Mode (Sync Ensemble vs Async Pipelined). 3) Finalize run and export final artifacts.

Factory

load_config

load_config(source)

Create a validated :class:GAConfig from YAML path or Python dict.

If source is a string/Path, it is interpreted as a YAML file and parsed via :func:ezga.io.config_loader.load_config_yaml (which also resolves dotted callable references). If source is a dict, it is validated directly using Pydantic.

Parameters:

Name Type Description Default
source ConfigInput

YAML file path or a Python dict matching the GAConfig schema.

required

Returns:

Type Description
GAConfig

A validated :class:GAConfig instance.

Raises:

Type Description
SystemExit

If the YAML fails validation (the loader prints a friendly error message and exits).

TypeError

If source is neither a path-like nor a dict.

build_default_engine

build_default_engine(cfg, *, lineage=LineageTracker, hash_map=Structure_Hash_Map, agent=Agentic_Sync, population=Population, thermostat=Thermostat, evaluator=Evaluator, selector=Selector, variation=Variation_Operator, simulator=Simulator, convergence=Convergence, logger=WorkflowLogger, plotter=Plotter, transition=None, ctx=None)

Constructs a fully-wired GeneticAlgorithm instance from a GAConfig.

This factory implements a phased Dependency Injection (DI) pattern: 1. Shared State: Initializes the global Context and RNG. 2. Infrastructure: Sets up identity tracking (Hashing, Lineage). 3. Population: Assembles the structural container with its Agentic interface. 4. Science Core: Links physical evaluators and simulators. 5. Search Logic: Configures genetic operators and selection kernels. 6. Diagnostics: Wires convergence monitors and diagnostic plotters.

General-purpose optimization

The ezga.simple package solves arbitrary (non-atomistic) optimization problems.

minimize

minimize(problem, algorithm, termination=('n_gen', 100), seed=1, verbose=False, save_history=False, mutation_rate=1.0, callback=None, save_generations=True, **kwargs)

Minimizes the given problem using the provided algorithm configuration.

Parameters:

Name Type Description Default
problem ElementwiseProblem

ElementwiseProblem instance.

required
algorithm GA

GA configuration instance.

required
termination tuple

Tuple ('n_gen', int) or similar.

('n_gen', 100)
seed int

Random seed.

1
verbose bool

Print logs.

False
save_history bool

Keep full history (not implemented fully, placeholder).

False
**kwargs

Extra args passed to GAConfig.

{}

Returns:

Type Description
Result

Result object.

ElementwiseProblem

Base class for defining optimization problems where evaluation depends on individual element vectors (element-wise).

This matches the PyMOO ElementwiseProblem signature.

evaluate

evaluate(x, *args, **kwargs)

Public evaluation method calling the internal _evaluate.

Symbolic regression

SymbolicRegressionProblem

Bases: ElementwiseProblem

Compatibility wrapper for the new Multi-Formulation Symbolic Regression engine. Mimics the legacy API while internally using StrongFormulation.

best_fitness property writable

best_fitness

Returns the score of the best discovered model.

best_tree property writable

best_tree

Legacy alias for the best discovered tree.

expression property

expression

Returns the string representation of the best model found (automatically simplified).

optimization_config property

optimization_config

Maps intensity (0-1) to solver parameters.

compute_error

compute_error(y_true, y_pred, kind='mse')

Natively computes a variety of error metrics for regression.

compute_residual_structure

compute_residual_structure(y_true, y_pred)

Natively computes metrics assessing the predictability of residuals.

decompose_residuals

decompose_residuals(tree, site=None, max_components=1)

Modern alternative to legacy Residual Life Cycle discovery.

fit

fit(X=None, y=None, n_gen=None, pop_size=None)

Standard fit method: uses the core engine to execute the evolutionary cycle.

get_best_models

get_best_models(k=6)

Returns the top candidate models with their originating backend information.

get_models

get_models(n=5, sort_by='error', *args, **kwargs)

Standard method for retrieving top models from Pareto front.

predict_all

predict_all(X)

Ensemble prediction from all Pareto-front candidates.

predict

predict(X)

Standard prediction using the best discovered model.

score

score(X, y)

Returns R^2 score for regression.

update_penalty

update_penalty(stall_count)

Adjusts complexity penalty based on search stagnation (Adaptive Parsimony).

get_supported_operators staticmethod

get_supported_operators()

Returns a categorized dictionary of supported operators.

print_available_ops staticmethod

print_available_ops()

Diagnostic helper to print all string-accessible operators.

plot_results

plot_results(X, y, outfile=None, title='Symbolic Regression Fit')

Simple built-in plotter for 1D symbolic regression results.

plot_pareto_front

plot_pareto_front(outfile=None)

Plots the Complexity vs Fitness Pareto front for discovered models.

plot_all_models

plot_all_models(X, y, outfile=None, max_models=10)

Plots the top Pareto models overlaid on the data (1D only).

refine

refine(top_k=1, intensity=1.0)

Perform high-precision numerical refinement on the best discovered models. Useful for getting exact coefficients after evolution finishes.

evaluate_tree

evaluate_tree(eval_tree, tree_id=None)

Public evaluation method used by legacy operators. Scores the tree against all active backends and tracks the best one.

get_guided_repairs

get_guided_repairs(tree, top_k=5, **kwargs)

Native implementation of guided repair generation using residual decomposition.

compute_complexity

compute_complexity(tree)

Natively computes tree complexity (size).