API Reference#

flowerevolver#

Every class and free function here is bound directly from the C++ core (src/bindings/python/*.cpp) via nanobind - the same code path the JS/WASM API’s FEService and the native C++ library’s include/fe/FlowerEvolver.hpp both go through, so behavior (and, for Flower/DNA’s JSON, wire format) matches across all three.

FlowerEvolver - generates 2D/3D flowers from CPPN genomes evolved via EvoAI.

Native Python bindings (nanobind) around the same C++ core that powers the JS/WASM API and the native desktop app – genomes and rendered images round-trip with both (see Flower.to_json()/from_json()).

Quick start:

from flowerevolver import make_flower

flower = make_flower(radius=64, num_layers=3, P=6.0, bias=1.0) flower.petals.image.to_png_bytes() # -> bytes, ready to write to disk flower.to_json() # -> str, the genome

class flowerevolver.DNA(*args, **kwargs)#

Bases: object

The genome underlying a Flower - a small collection of CPPN genomes (a stats genome plus another for petals), evolved via EvoAI. Most code creates these indirectly, through make_flower()/reproduce()/mutate() rather than by hand. Individual genomes aren’t exposed to Python (EvoAI::Genome has no binding of its own) – treat DNA as an opaque, sized container.

clear(self) → None#

Removes every genome, leaving size() == 0.

distance = <nanobind.nb_func object>#
from_json = <nanobind.nb_func object>#
get_fitness(self) → float#

Reads back the fitness set via set_fitness() (from genome[0]); 0.0 if this DNA is empty.

mutate(self, rates: flowerevolver._core.MutationRates) → None#

Mutates every existing genome in place (topology and weights), according to rates. This never adds or removes genomes – size() before and after is always identical; what changes is each genome’s internal structure, not how many there are.

reproduce = <nanobind.nb_func object>#
set_fitness(self, fitness: float) → None#

Applies the same fitness value to every genome this DNA holds.

size(self) → int#

Number of genomes this DNA holds.

to_json(self) → str#

Serializes to a compact JSON string – this DNA’s own genomes array, not wrapped in the outer {“Flower”: …} shape Flower.to_json() produces (a bare DNA isn’t a complete, renderable Flower on its own). Round-trips with DNA.from_json().

class flowerevolver.Effects(*args, **kwargs)#

Bases: object

Per-stat effect strengths derived from the genome, roughly -100..100 each.

property agility#

(self) -> float

property intelligence#

(self) -> float

property luck#

(self) -> float

property strength#

(self) -> float

property vitality#

(self) -> float

class flowerevolver.Environment(*args, **kwargs)#

Bases: object

The environment a flower’s Stats are computed under (humidity, temperature, altitude, terrain type). The game varies this per flower on purpose (weather affects a flower’s stats), so a FlowerClassifier’s own recorded environment is documentation only – classify() never checks a genome’s environment against it.

property altitude#

(self) -> int

from_json = <nanobind.nb_func object>#
property humidity#

(self) -> float

property temperature#

(self) -> int

property terrain_type#

(self) -> int

to_json(self) → str#

Compact JSON: {“humidity”:…, “temperature”:…, “altitude”:…, “terrainType”:…}

validate(self) → None#

Raises ValueError if humidity is NaN/Inf. Called again wherever an Environment is used.

class flowerevolver.Flower(*args, **kwargs)#

Bases: object

A complete flower: its genome (dna) and rendered image (petals). Usually created via make_flower()/reproduce()/mutate() rather than constructed directly.

property dna#

(self) -> flowerevolver._core.DNA

from_json = <nanobind.nb_func object>#
property petals#

(self) -> flowerevolver._core.Petals

to_json(self) → str#

Serializes to the same {“Flower”: {“dna”: …, “petals”: …}} JSON shape used throughout this project’s ecosystem (the JS/WASM API, the native desktop app, Generation.json/Session.json’s own per-flower entries) – round-trips with Flower.from_json(), and interoperates with genomes saved by any of those.

class flowerevolver.FlowerClassifier(*args, **kwargs)#

Bases: object

A trained SOM species classifier: the underlying SOM plus the Environment it was trained under (documentation only, see Environment). Build one with train_flower_classifier() rather than this constructor directly unless you specifically want an untrained classifier to call .som-style training on by hand – this constructor gives you the shape only, not a trained SOM.

classify(self, genome: str, environment: flowerevolver._core.Environment) → flowerevolver._core.SpeciesMatch | None#
classify(self, flower: flowerevolver._core.Flower, environment: flowerevolver._core.Environment) → flowerevolver._core.SpeciesMatch | None

Overloaded function.

  1. classify(self, genome: str, environment: flowerevolver._core.Environment) -> flowerevolver._core.SpeciesMatch | None

Finds the grid node whose learned prototype is closest to this flower’s genome: a SpeciesMatch with its x, y and the distance. Returns None (not an error) if genome is malformed or its DNA is unusable.

  1. classify(self, flower: flowerevolver._core.Flower, environment: flowerevolver._core.Environment) -> flowerevolver._core.SpeciesMatch | None

Same as the genome-string overload, for when you already have a Flower object instead of its genome JSON.

classify_features(self, features: collections.abc.Sequence[float]) → flowerevolver._core.SpeciesMatch | None#

Classifies an already-extracted feature vector (see extract_flower_features()), skipping genome parsing and rendering. Returns None if features doesn’t have exactly input_dim values or contains a non-finite one.

classify_flowers(self, generations_json: str, environment: flowerevolver._core.Environment) → list[flowerevolver._core.SpeciesMatch | None]#

Classifies every flower of a {“Generation”: […]} JSON batch, one entry per flower in input order: a SpeciesMatch, or None for a flower that can’t be classified (same meaning as classify()). Raises RuntimeError if generations_json isn’t parsable JSON.

continue_training(self, samples: collections.abc.Sequence[collections.abc.Sequence[float]], epochs: int, base_lr: float, base_radius: float, epoch_offset: int = 0, total_epochs: int = 0, on_epoch: object | None = None) → flowerevolver._core.SOMTrainingReport#

Trains this already-existing classifier further, in place, instead of building a fresh one – for fine-tuning an embedded/loaded classifier on a smaller, more specific population, or for sampling a quantization-error-vs-epochs curve by calling this repeatedly with the same samples (see tools/). Uses the same fixed scheduler pair as train_flower_classifier(); by default each call is a new decay from its own epoch 0, so two calls with epochs=10 are not one call with epochs=20. To split ONE decay over several calls pass the same base_lr/base_radius and total_epochs every time and advance epoch_offset by the epochs already done; the decay is the same as in a single call (the sample order is reshuffled per call, so the weights are not bit-identical). on_epoch, if given, is called with a SOMEpoch after every epoch, to show progress or to stop: returning False stops after that epoch, anything else (None included) goes on; an exception it raises stops the training and is raised from here, the epochs already done stay. Returns a SOMTrainingReport: one SOMEpoch per epoch that ran, the indices of the samples that were skipped (wrong size / non-finite values; always fewer than len(samples)) and the wins per node of the last epoch. Raises ValueError if base_lr or base_radius is not finite and > 0, or if no sample is usable.

property environment#

(self) -> flowerevolver._core.Environment

evaluate(self, samples: collections.abc.Sequence[collections.abc.Sequence[float]]) → dict#

Measures how well this classifier fits already-extracted feature vectors: mean quantization error plus how they spread over the nodes (node_counts is row-major, index = y * width + x). Wrong-size or non-finite samples are counted in samples_skipped. Raises ValueError if no sample is usable.

from_json = <nanobind.nb_func object>#
get_prototype(self, x: int, y: int) → list[float]#

The learned feature vector at grid node (x, y) – same shape as extract_flower_features()’s output (first silhouette_size**2 values reshape to a silhouette_size x silhouette_size image, last 11 are the normalized Stats fields, see stat_names()). Raises IndexError if x/y are out of range.

property height#

Grid height, in nodes.

input_dim = 267#
silhouette_size = 16#
stat_names = <nanobind.nb_func object>#
to_json(self) → str#

The full classifier bundle – version, input shape, stat names, environment, and the trained SOM’s own weights – as compact JSON. This is what gets embedded as fe::resources::trainedSOM once you’re happy with a trained classifier (see tools/).

property weight_decimals#

Rounds the weights to_json() writes to this many decimals (0 to 17) to make the JSON much shorter, None (the default) writes them exactly. A weight within half a unit of the last decimal of 0 or 1 is written as exactly 0 or 1. The rounding is absolute and only changes the JSON, the classifier keeps its exact weights, and it is not saved in the JSON: a classifier loaded with from_json() writes exact weights until it is set again. 4 decimals write about a quarter of the text for the embedded 12x8 classifier. Raises ValueError outside 0 to 17.

property width#

Grid width, in nodes.

class flowerevolver.Image(*args, **kwargs)#

Bases: object

A simple RGBA pixel buffer - what Flower.petals.image and every draw_*()/make_*() call’s rendered output is. Pixel colors are plain (r, g, b, a) tuples of 0-255 ints, not a separate bound Color type.

create(self, width: int, height: int, color: tuple[int, int, int, int]) → None#

Allocates a width x height buffer, filled with color (r, g, b, a).

get_pixel(self, x: int, y: int) → tuple[int, int, int, int]#

Returns the (r, g, b, a) color at (x, y); (0, 0, 0, 0) if out of range.

property height#

(self) -> int

set_pixel(self, x: int, y: int, color: tuple[int, int, int, int]) → None#

Sets the pixel at (x, y) to color (r, g, b, a). Out-of-range x/y are silently ignored (matches the C++ API – see setPixel’s own bounds-check comment in src/fe/Image.cpp).

to_png_bytes(self) → bytes#

Encodes to an in-memory PNG and returns it as bytes – e.g. pathlib.Path(‘flower.png’).write_bytes(image.to_png_bytes()).

property width#

(self) -> int

class flowerevolver.MutationRates(*args, **kwargs)#

Bases: object

Rates controlling how DNA.mutate()/mutate() perturbs a genome. Every parameter is independent – a given mutation call can add a node, add a connection, and perturb weights all at once, each gated by its own rate below.

property act_type_rate#

Rate to change a neuron’s activation function.

property add_conn_rate#

Rate to add a new connection.

property add_node_rate#

Rate to add a new node.

property disable_rate#

Rate to disable a currently-enabled gene.

property enable_rate#

Rate to enable a currently-disabled gene.

property perturb_weights_rate#

Rate to change the weight of a connection.

property remove_conn_rate#

Rate to remove an existing connection.

class flowerevolver.Petals(*args, **kwargs)#

Bases: object

The rendered-image half of a Flower (Flower.petals) - the generation parameters that produced it, plus the resulting image.

property P#

(self) -> float

property bias#

(self) -> float

property has_bloom#

(self) -> bool

property image#

(self) -> flowerevolver._core.Image

property num_layers#

(self) -> int

property radius#

(self) -> int

class flowerevolver.PetalsType(*values)#

Bases: Enum

Which part of a flower to render - passed to some of the lower-level make_*()/draw_*() calls.

TRUNK = 0#
PETALS = 1#
TRUNK_AND_PETALS = 2#
class flowerevolver.Sex(*values)#

Bases: Enum

MALE = 0#
FEMALE = 1#
BOTH = 2#
class flowerevolver.SOMTrainingConfig(*args, **kwargs)#

Bases: object

SOM grid size + training hyperparameters for train_flower_classifier(). Defaults are untuned placeholders – see tools/ for evaluating real grid sizes/hyperparameters against actual training data before picking final ones.

property base_lr#

(self) -> float

property base_radius#

(self) -> float

property epochs#

(self) -> int

from_json = <nanobind.nb_func object>#
property height#

(self) -> int

to_json(self) → str#

Compact JSON: {“width”:…, “height”:…, “epochs”:…, “baseLR”:…, “baseRadius”:…}

validate(self) → None#

Raises ValueError for a zero size/epochs or a non-finite or non-positive base_lr/base_radius. Called again wherever a config is used.

property width#

(self) -> int

class flowerevolver.Stats(*args, **kwargs)#

Bases: object

Environment-dependent stats derived from a flower’s genome - see get_flower_stats().

property effects#

(self) -> flowerevolver._core.Effects

property health#

(self) -> int

property maturation_period#

(self) -> int

property max_temperature#

(self) -> int

property min_temperature#

(self) -> int

property sex#

(self) -> flowerevolver._core.Sex

property stamina#

(self) -> int

property toxicity_rate#

(self) -> float

The species classifier (FlowerClassifier, SOMTrainingConfig, Environment and the three functions at the end of the list below) is explained in Species classification.

Free functions#

flowerevolver.make_flower(radius: int, num_layers: int, P: float, bias: float) → flowerevolver._core.Flower#

Generates a brand new, random flower.

Parameters:
  • radius – pixel radius, clamped to [4, 256].

  • num_layers – clamped to [1, floor(log2(radius))].

  • P – controls roughly how many petals the flower can have.

  • bias – bias fed into the CPPN alongside radius/angle/layer.

Returns:

a Flower – .to_json() for the genome, .petals.image for the render.

flowerevolver.make_petals(radius: int, num_layers: int, P: float, bias: float) → flowerevolver._core.Flower#

Same as make_flower(), but renders just the petals (no stem).

flowerevolver.make_petal_layer(radius: int, num_layers: int, P: float, bias: float, layer: int) → flowerevolver._core.Flower#

Same as make_flower(), but renders just one petal layer (no stem).

Parameters:

layer – which layer to render, 0-indexed from the outermost.

flowerevolver.make_stem(radius: int, num_layers: int, P: float, bias: float) → flowerevolver._core.Flower#

Same as make_flower(), but renders just a stem (no petals).

flowerevolver.draw_flower(dna: flowerevolver._core.DNA, radius: int, num_layers: int, P: float, bias: float) → flowerevolver._core.Image#

Renders an existing DNA (e.g. from Flower.dna, or DNA.from_json()) instead of generating a new one.

Parameters:
  • dna – the genome to render; needs at least 2 genomes.

  • radius – pixel radius, clamped to [4, 256].

  • num_layers – clamped to [1, floor(log2(radius))].

  • P – controls roughly how many petals the flower can have.

  • bias – bias fed into the CPPN alongside radius/angle/layer.

Returns:

the rendered Image.

Raises:

ValueError – if dna has fewer than 2 genomes.

flowerevolver.draw_petals(dna: flowerevolver._core.DNA, radius: int, num_layers: int, P: float, bias: float) → flowerevolver._core.Image#

Same as draw_flower(), but renders just the petals (no stem).

flowerevolver.draw_petal_layer(dna: flowerevolver._core.DNA, radius: int, num_layers: int, P: float, bias: float, layer: int) → flowerevolver._core.Image#

Same as draw_flower(), but renders just one petal layer (no stem).

Parameters:

layer – which layer to render, 0-indexed from the outermost.

flowerevolver.reproduce(dna1: flowerevolver._core.DNA, dna2: flowerevolver._core.DNA, radius: int, num_layers: int, P: float, bias: float) → flowerevolver._core.Flower#

Breeds two genomes into a rendered child Flower. For crossover only, with no rendering, see DNA.reproduce() instead.

Parameters:
  • dna1 – the father’s genome.

  • dna2 – the mother’s genome; must have the same number of genomes as dna1.

  • radius – pixel radius, clamped to [4, 256].

  • num_layers – clamped to [1, floor(log2(radius))].

  • P – controls roughly how many petals the flower can have.

  • bias – bias fed into the CPPN alongside radius/angle/layer.

Raises:

RuntimeError – if dna1 and dna2 don’t have the same number of genomes.

flowerevolver.mutate(dna: flowerevolver._core.DNA, radius: int, num_layers: int, P: float, bias: float, add_node_rate: float = 0.20000000298023224, add_conn_rate: float = 0.30000001192092896, remove_conn_rate: float = 0.20000000298023224, perturb_weights_rate: float = 0.6000000238418579, enable_rate: float = 0.3499999940395355, disable_rate: float = 0.30000001192092896, act_type_rate: float = 0.4000000059604645) → flowerevolver._core.Flower#

Mutates a copy of dna and renders the result – dna itself is left untouched.

Parameters:
  • dna – genome to mutate; needs at least 2 genomes.

  • radius – pixel radius, clamped to [4, 256].

  • num_layers – clamped to [1, floor(log2(radius))].

  • P – controls roughly how many petals the flower can have.

  • bias – bias fed into the CPPN alongside radius/angle/layer.

  • add_node_rate – rate to add a new node.

  • add_conn_rate – rate to add a new connection.

  • remove_conn_rate – rate to remove an existing connection.

  • perturb_weights_rate – rate to change a connection’s weight.

  • enable_rate – rate to enable a currently-disabled gene.

  • disable_rate – rate to disable a currently-enabled gene.

  • act_type_rate – rate to change a neuron’s activation function.

Raises:

ValueError – if dna has fewer than 2 genomes.

flowerevolver.make_3d_flower(dna: flowerevolver._core.DNA, radius: int, num_layers: int, P: float, bias: float, flower_id: str, flower_params: str = '') → str#

Generates a 3D flower model.

Parameters:
  • dna – the genome to render; needs at least 2 genomes.

  • radius – pixel radius, clamped to [4, 256].

  • num_layers – clamped to [1, floor(log2(radius))].

  • P – controls roughly how many petals the flower can have.

  • bias – bias fed into the CPPN alongside radius/angle/layer.

  • flower_id – a unique string identifying this flower (used in the model’s own group names).

  • flower_params – JSON string, e.g. ‘{“sex”: 2, “useNormals”: true, “useEmissive”: false}’; “” for defaults.

Returns:

the 3D model as a glTF 2.0 JSON string.

Raises:

ValueError – if dna has fewer than 2 genomes, or radius/num_layers/flower_id are invalid.

flowerevolver.get_flower_stats(genome: str, humidity: float, temperature: int, altitude: int, terrain_type: int) → flowerevolver._core.Stats#

Derives environment-dependent Stats from a flower’s genome.

Parameters:
  • genome – a Flower.to_json()-shaped JSON string.

  • humidity – 0.0 to 1.0.

  • temperature – degrees, same scale as the resulting Stats’ min_temperature/max_temperature.

  • altitude – meters above sea level.

  • terrain_type – terrain type id.

Raises:
  • ValueError – if genome doesn’t contain a DNA with at least 2 genomes.

  • RuntimeError – if genome is malformed JSON entirely.

flowerevolver.extract_flower_features(genome: str, environment: flowerevolver._core.Environment) → list[float]#

Builds a flower’s FlowerClassifier.input_dim-dimensional SOM feature vector from its genome JSON: a silhouette_size x silhouette_size alpha-only silhouette (max-pool downsampled, rendered with the genome’s own petals config – not a separately-supplied one) followed by 11 fixed-bounds-normalized Stats fields (see FlowerClassifier.stat_names()). Every value is in [0, 1]. Raises ValueError if genome’s DNA doesn’t have enough usable outputs, RuntimeError if genome isn’t valid JSON at all. A genome whose network overflows (for example a weight of 1e999 in the JSON) gives NaN values instead of an error: filter with math.isfinite before using the vector yourself; training and classification skip such a vector. Extraction is not bit-for-bit reproducible between calls (the raw render varies for some genomes); on 300 random flowers it never changed the species cell. When you classify, evaluate or fine-tune the same flowers more than once, extract once and reuse the vectors.

flowerevolver.train_flower_classifier(samples: collections.abc.Sequence[collections.abc.Sequence[float]], environment: flowerevolver._core.Environment, training: flowerevolver._core.SOMTrainingConfig) → flowerevolver._core.FlowerClassifier#
flowerevolver.train_flower_classifier(generations_json: str, environment: flowerevolver._core.Environment, training: flowerevolver._core.SOMTrainingConfig) → flowerevolver._core.FlowerClassifier

Overloaded function.

  1. train_flower_classifier(samples: collections.abc.Sequence[collections.abc.Sequence[float]], environment: flowerevolver._core.Environment, training: flowerevolver._core.SOMTrainingConfig) -> flowerevolver._core.FlowerClassifier

Trains a fresh classifier from already-extracted feature vectors (see extract_flower_features()). Use this overload when you want control over what happens to a sample before training it lands in here – filtering, caching, inspecting, deduplicating – otherwise the other overload (a list of genome JSON strings) does the extraction for you.

  1. train_flower_classifier(generations_json: str, environment: flowerevolver._core.Environment, training: flowerevolver._core.SOMTrainingConfig) -> flowerevolver._core.FlowerClassifier

Trains a fresh classifier from a whole batch given as one {“Generation”: […]} JSON string – the format this project already uses to move a flower collection between apps (see tools/dataset.py for building one from a directory of saved genomes). Entries that fail feature extraction are skipped and logged to stderr, not treated as an error.

flowerevolver.get_trained_som() → str#

The classifier embedded in this build, as-is (fe::resources::trainedSOM).

flowerevolver.get_version() → str#

The semver this extension was built from, e.g. “4.0.0”.

flowerevolver.get_commit_hash() → str#

The short git commit hash this extension was built from, or “unknown” for a build outside a git checkout.

flowerevolver.get_version_string() → str#

get_version() + “+” + get_commit_hash(), e.g. “4.0.0+a1b2c3d” – the one to put in a bug report.

flowerevolver.cli#

The flower-evolver console script installed alongside the package - matches the native desktop app’s own single-flower flags. See the module docstring below for the exact invocations; flower-evolver --help covers the same ground interactively.

FlowerEvolver CLI - matches the native desktop app’s own single-flower flags: -lf, -sf, -si, -s3d, -m, -repr, and the shared -l/-r/-p/-b generation parameters.

Three entry points (each self-sufficient - -lf/-repr just replace “start from a fresh flower” with “start from an existing one/two”). -m <n> mutates n times and saves only the final result, matching the native app - run this repeatedly (feeding each -sf output back in via -lf) if you want every intermediate step saved instead:

flower-evolver -l <numLayers> -r <radius> -p <P> -b <bias> -m <n> flower-evolver -lf <flower.json> -l <numLayers> -r <radius> -p <P> -b <bias> -m <n> -sf <out.json> -si <out.png> flower-evolver -repr <flower1.json> <flower2.json> -l <numLayers> -r <radius> -p <P> -b <bias> -m <n> -sf <out.json> -si <out.png>

Add -s3d <filename> to any of the above to also generate and save a 3D model (glTF) for the resulting flower, e.g.:

flower-evolver -sf flower.json -si flower.png -s3d flower.gltf

Use -se3d <filename> instead of (or alongside) -s3d for an emissive 3D model - same glTF export, but with useEmissive turned on, matching FEService.makeEmissive3DFlower()/drawEmissive3DFlower() on the JS/WASM side. Both can be passed together to save a regular and an emissive model from the same flower:

flower-evolver -sf flower.json -si flower.png -s3d flower.gltf -se3d flower_emissive.gltf

flowerevolver.cli.build_parser() → ArgumentParser#
flowerevolver.cli.main(argv: list[str] | None = None) → int#