saealib.Population#
- class saealib.Population(attrs, init_capacity=100, *, genomes=None, space=None, dense_numeric_view=None, dense_view=None)[source]#
Bases:
Generic[T_Individual]Container for schema-defined population attributes and genome data.
- Parameters:
attrs (list[PopulationAttribute])
init_capacity (int)
genomes (GenomeBatch | None)
space (Any | None)
dense_numeric_view (DenseNumericView | None)
dense_view (DenseNumericView | None)
Methods
Initialize a Population. |
|
Append one candidate. |
|
Return row indices that order a named column. |
|
Clear the population. |
|
Delete candidates selected by |
|
Create an empty population with the same schema and representation. |
|
Extend the population with another candidate collection. |
|
Return a new population containing rows selected by |
|
Get the array of a specific attribute. |
|
Return a read-only view of the active rows in a named column. |
|
Return a cached value without changing population state. |
|
Mark population structure as changed and invalidate cached results. |
|
Mark population values as changed and invalidate cached results. |
|
Reorder candidates according to a complete row permutation. |
|
Store a value in the population cache without changing its version. |
|
Keep the first |
|
Update array in place and bump the value version. |
|
Atomically update multiple columns for the given rows. |
Method Details
- Population.__init__(attrs, init_capacity=100, *, genomes=None, space=None, dense_numeric_view=None, dense_view=None)[source]#
Initialize a Population.
- Parameters:
attrs (list[PopulationAttribute]) – Column definitions for per-candidate data.
init_capacity (int) – Initial storage capacity.
genomes (GenomeBatch | None) – Optional initial genome batch.
space (Any | None) – Search space associated with the genomes.
dense_numeric_view (DenseNumericView | None) – Service used to obtain a dense numeric view of dense genomes.
dense_view (DenseNumericView | None) – Compatibility alias for
dense_numeric_view.
- Return type:
None
- Population.append(element=None, **kwargs)[source]#
Append one candidate.
- Parameters:
element (Individual-like object, dict, or None) – Candidate values read from an individual or mapping. Values passed through
kwargstake precedence over values fromelement.**kwargs (Any) – Column values to assign.
genomeorgenomessupplies the single genome required by a non-dense genome representation.
- Raises:
ValidationError – If an explicit candidate ID other than the unassigned
-1sentinel is supplied, or if a custom genome representation does not receive exactly one genome.- Return type:
None
Notes
The population grows its storage as needed. Appending invalidates cached values and structure-dependent views.
- Population.argsort(name, reverse=False)[source]#
Return row indices that order a named column.
- Parameters:
name (str) – Name of a column in the population schema.
reverse (bool, optional) – If true, return the indices in descending rather than ascending column order.
- Returns:
Indices for the active rows in sorted order. The population is not mutated.
- Return type:
ndarray of int
- Raises:
KeyError – If
nameis not present in the population schema.
- Population.delete(index)[source]#
Delete candidates selected by
indexin place.- Parameters:
index (int, slice, list of int, or ndarray) – Row index or indices to remove from the active population.
- Return type:
None
Notes
Surviving rows retain their relative order. The operation mutates the population and invalidates cached values and structure-dependent views.
- Population.empty_like(capacity=None)[source]#
Create an empty population with the same schema and representation.
- Parameters:
capacity (int or None, optional) – Storage capacity for the new population. If omitted, the current capacity is reused.
- Returns:
An empty population of the same concrete type, schema, and genome representation. It reuses the associated space and dense-view service but has independent row storage.
- Return type:
- Population.extend(other)[source]#
Extend the population with another candidate collection.
- Parameters:
other (Population or dict) – Source population or column-data mapping. A mapping may provide
genomeorgenomesfor an opaque genome representation.- Raises:
ValidationError – If the source supplies assigned candidate IDs through this public method, or omits genomes required by a custom representation.
- Return type:
None
Notes
An empty source is a no-op. Otherwise rows are copied, storage grows as needed, and cached values and structure-dependent views are invalidated.
- Population.extract(indices)[source]#
Return a new population containing rows selected by
indices.- Parameters:
indices (ndarray, list of int, or slice) – Indices into the active rows. Rows appear in the requested order; a slice follows normal Python slicing semantics.
- Returns:
A new population of the same concrete type, schema, and genome representation. Row and genome data have independent storage, and the source population is unchanged.
- Return type:
- Population.get(key: str) ndarray | None[source]#
- Population.get(key: str, default: _T_Default) ndarray | _T_Default
Get the array of a specific attribute.
- Parameters:
key (str) – The attribute name to get the array for.
default (any, optional) – Returned when the key is absent. Defaults to
None.
- Returns:
The attribute array if
keyexists, otherwisedefault.- Return type:
np.ndarray or default
- Population.get_array(key)[source]#
Return a read-only view of the active rows in a named column.
- Parameters:
key (str) – Column name. For
"x", the value is obtained through the configuredDenseNumericViewunless this is a legacy scalar-x population.- Returns:
A non-writeable view covering the active rows of the column. The returned array for stored columns shares backing storage rather than being an owned copy;
"x"uses the service-provided view.- Return type:
np.ndarray
- Raises:
KeyError – If
keyis not a stored non-genome column.AttributeError – If
keyis"x"and the requiredDenseNumericViewis unavailable or reports that it cannot provide a view.
Notes
The population is not modified by this method. Mutating the returned view raises
ValueError; useupdate_array()orupdate_rows()so value versions and caches remain synchronized.
- Population.get_cache(key)[source]#
Return a cached value without changing population state.
- Parameters:
key (Hashable) – Cache key to look up.
- Returns:
The cached value, or
Nonewhen no value is stored forkey. A cachedNoneis therefore indistinguishable from a missing key through this method.- Return type:
Any or None
- Raises:
TypeError – If
keyis not hashable.
Notes
Cached values are removed when the population is modified through
mod_value()ormod_structure().
- Population.mod_structure()[source]#
Mark population structure as changed and invalidate cached results.
- Return type:
None
- Population.mod_value()[source]#
Mark population values as changed and invalidate cached results.
- Return type:
None
- Population.reorder(order)[source]#
Reorder candidates according to a complete row permutation.
- Parameters:
order (ndarray of int) – Permutation containing one row index for every active candidate.
- Raises:
ValueError – If
orderdoes not contain one entry per active row.- Return type:
None
Notes
Reordering is in place and invalidates cached values and structure-dependent views.
- Population.set_cache(key, value)[source]#
Store a value in the population cache without changing its version.
- Parameters:
key (Hashable) – Cache key. An existing value for the key is replaced.
value (Any) – Value to retain until the population is modified.
- Raises:
TypeError – If
keyis not hashable.- Return type:
None
Notes
The cache is cleared by
mod_value()andmod_structure(). Storing a value replaces only the entry forkey; it does not clear other cached entries or bump the population’s value or structure version.
- Population.truncate(new_size)[source]#
Keep the first
new_sizecandidates in place.- Parameters:
new_size (int) – Number of leading active rows to retain. Values greater than or equal to the current size leave the population unchanged.
- Raises:
ValueError – If
new_sizeis negative.- Return type:
None
Notes
When the population is reduced, trailing rows become inactive and non-dense genome storage is reduced accordingly. Structure-dependent state and cached values are invalidated. No version or cache change occurs for a no-op truncation.
- Population.update_array(key, value)[source]#
Update array in place and bump the value version.
- Parameters:
key (str)
value (Any)
- Return type:
None
- Population.update_rows(indices, values, genome=None)[source]#
Atomically update multiple columns for the given rows.
Validates every index and value before mutating any backing storage, so a validation failure never leaves a partial update applied. Bumps the value version exactly once for a non-empty update; an update with empty
indicesor an emptyvaluesmapping is a no-op and does NOT bump the version.- Parameters:
indices (np.ndarray | list[int]) – Row indices to update. Must be 1-D, integer dtype, within
[0, len(self)), and free of duplicates.values (dict[str, np.ndarray]) – Mapping of column name to the new values for those rows. Each value array must match shape
(len(indices), *schema[key].shape)and dtypeschema[key].dtypeexactly.genome (GenomeBatch | ndarray | None)
- Raises:
ValidationError – If
indicesis invalid (wrong dtype/ndim, out of range, or contains duplicates), if a key invaluesis unknown (or is"id"), or if a value array’s shape/dtype does not match the schema exactly.- Return type:
None