DNALandscape

DNALandscape(maximize: bool = True)

A specialized landscape class for DNA sequence configuration spaces.

This class represents fitness landscapes where each configuration is a DNA sequence using the standard DNA alphabet (A, C, G, T).

Methods at a glance

build_from_graph()
Construct a landscape from a saved graph file.
to_graph()
Save the landscape graph and essential attributes to a file.
get_params()
Return the constructor parameters as a dict.
register_input_handler()
Register a custom input handler for a data type on this instance.
register_neighbor_generator()
Register a custom neighbor generator for a data type on this instance.
build_from_data()
Build the landscape, inferring the alphabet from *X* when it was not
get_data()
Extracts landscape data as a pandas DataFrame.
get_lon()
Constructs and returns the Local Optima Network (LON).
describe()
Return a structured summary of the landscape as a dict.

Parameters

maximize : bool, default=True

Determines the optimization direction. If True, the landscape seeks higher fitness values. If False, it seeks lower values.

n_configs

Number of configurations (nodes). Derived from the graph once built (single source of truth); falls back to the working count during construction, before self.graph exists.

n_edges

Number of directed edges. Derived from the graph once built (single source of truth); falls back to the working count during construction.

shape

Return the shape (n_configs, n_edges) of the landscape graph.

configs : Optional[pd.Series]

Per-node configuration tuple Series (built lazily, then cached).

The numeric _configs_array is the source of truth and is what graph construction consumes; this tuple Series is a downstream artifact used only by analyses that need per-node configuration tuples. It is materialised from _configs_array on first access -- builds that never read configs (the common construction-only path) skip the cost entirely. Returns None only when neither the cached Series nor a numeric array is available (e.g. an unbuilt landscape, or a graph load from which configurations could not be reconstructed).

Note: a landscape.configs is None check materialises the Series if _configs_array is present.

basins : pd.Series

Per-node greedy basin size (size_basin_greedy), computed lazily.

accessible_paths : pd.Series

Per-node accessible-basin size (size_basin_accessible), computed lazily.

dist_to_go : pd.Series

Per-node configuration distance to the nearest global optimum (dist_go), computed lazily.

neighbor_fitness : pd.Series

Per-node mean neighbour fitness (mean_neighbor_fit), computed lazily.

pagerank : pd.Series

Per-node PageRank centrality, computed lazily.

PageRank is not used by any landscape metric; it is only an optional, descriptive node attribute. To keep it off the construction critical path (where it was the single dominant cost) it is computed on first access here -- producing values identical to the eager computation (weighted by delta_fit when present, directed=True).

build_from_graph()

Inherited from _IOMixin

build_from_graph(
    filepath: str, *, verbose: bool = True
) -> "Landscape"

Construct a landscape from a saved graph file.

Parameters

filepath : str

Path to the saved graph file (.graphml).

verbose : bool, default=True

Controls verbosity of output during loading and analysis.

Returns

Landscape

A new instance populated with the graph and inferred properties.

This class method creates a new landscape instance by loading a previously saved graph, avoiding the need to reconstruct the landscape from original configuration data. This is significantly faster than building from scratch.

Notes

This method will:

  1. Load the saved graph structure and attributes

  2. Infer essential landscape properties from the graph

  3. Recalculate local optima and global optimum from the graph structure

Previously computed attributes (basins, accessible paths, distances, neighbor fitness) are preserved from the saved graph if present.

Some specialized attributes from subclasses (like sequence_length in SequenceLandscape) will be inferred where possible.

Only load GraphML from trusted sources: embedded configuration metadata is parsed with ast.literal_eval (safe against arbitrary code execution, but not a substitute for validating untrusted files).

Raises

ValueError

If the file cannot be read or doesn't contain valid graph data.

FileNotFoundError

If the specified file doesn't exist.

to_graph()

Inherited from _IOMixin

to_graph(filepath: str) -> None

Save the landscape graph and essential attributes to a file.

Parameters

filepath : str

The path where the graph file will be saved. If the file doesn't end with '.graphml', this extension will be added automatically.

This method serializes the landscape's graph structure and relevant attributes to a GraphML file, which can later be loaded using build_from_graph. This allows efficient storage and sharing of landscapes without requiring re-construction from scratch.

Notes

The GraphML format preserves the graph structure and all vertex/edge attributes. In addition to the graph itself, essential landscape attributes like maximize and epsilon are stored as graph attributes.

Raises

NotBuiltError

If the landscape has not been built.

ValueError

If the graph cannot be saved to the specified path.

get_params()

Inherited from Landscape

get_params() -> Dict[str, Any]

Return the constructor parameters as a dict.

Useful for introspection and reconstruction: type(ls)(**ls.get_params()) yields a fresh, unbuilt landscape with the same configuration.

register_input_handler()

Inherited from Landscape

register_input_handler(
    data_type: str, handler: InputHandler
) -> None

Register a custom input handler for a data type on this instance.

register_neighbor_generator()

Inherited from Landscape

register_neighbor_generator(
    data_type: str, generator: NeighborGenerator
) -> None

Register a custom neighbor generator for a data type on this instance.

build_from_data()

Inherited from SequenceLandscape

build_from_data(X, f, **kwargs)

Build the landscape, inferring the alphabet from X when it was not supplied at construction (see SequenceLandscape).

get_data()

Inherited from Landscape

get_data(
    lo_only: bool = False, include_pagerank: bool = False
) -> pd.DataFrame

Extracts landscape data as a pandas DataFrame.

Parameters

lo_only : bool, default=False

If True, returns data only for the configurations identified as local optima. If the Local Optima Network (LON) has been computed (see get_lon), data from the LON graph is returned. Otherwise, it returns data from the main graph filtered for local optima nodes. If False, returns data for all configurations in the main graph.

include_pagerank : bool, default=False

If True, compute (if needed) and include a pagerank column. PageRank is otherwise omitted -- it is an optional, comparatively expensive centrality that most callers do not need, so get_data no longer triggers it as a hidden side effect.

Returns

pandas.DataFrame

A DataFrame containing the attributes of the landscape nodes. Index corresponds to the node indices.

Returns a DataFrame where rows correspond to configurations (nodes) and columns correspond to their attributes (e.g., fitness, degree, basin information, original features). Feature columns appear in the original input order.

Raises

RuntimeError

If the landscape has not been built (via build_from_data or build_from_graph) before calling this method. If lo_only=True and the LON graph (self.lon) is unexpectedly None despite self.has_lon being True.

get_lon()

Inherited from Landscape

get_lon(
    mlon: bool = True,
    min_edge_freq: int = 3,
    trim: Optional[int] = None,
    verbose: Optional[bool] = None,
) -> ig.Graph

Constructs and returns the Local Optima Network (LON).

Parameters

mlon : bool, default=True

If True, also build the monotonic LON (edges restricted to non-worsening transitions).

min_edge_freq : int, default=3

Keep a LON edge only when the number of basin transitions between two optima is strictly greater than this threshold.

trim : int, default=None

If given, keep only the trim strongest outgoing edges per node.

verbose : bool, default=None

Verbosity override; defaults to the landscape's own verbose.

Returns

ig.Graph

The constructed Local Optima Network graph. The graph is also stored in the self.lon attribute, and self.has_lon is set to True.

The LON is a coarse-grained representation of the fitness landscape where nodes are the local optima of the original landscape, and edges represent the possibility of transitions between their basins of attraction, typically weighted by the fitness difference or distance between the optima. This method requires the landscape graph to be built and local optima to be identified.

The landscape's own graph, configurations, optima and config_dict are supplied automatically; the parameters below control the LON itself and are forwarded to graphfla.lon.get_lon.

Raises

RuntimeError

If the landscape has not been built, or if essential attributes (graph, configs, lo_index, config_dict) required for LON construction are missing.

describe()

Inherited from Landscape

describe() -> Dict[str, Any]

Return a structured summary of the landscape as a dict.

Returns

dict

class, kind, built, maximize and epsilon are always present. When built, size/optima fields (n_vars, n_configs, n_edges, n_lo, go_index), the calculation flags, and -- if a plateau layer exists -- the plateau counts are added.

Unlike a printed summary, the returned mapping is composable and testable -- callers can log it, assert on it, or render it. For a quick human-readable view use print(landscape) (see __str__).