RNALandscape ¶
RNALandscape(maximize: bool = True)A specialized landscape class for RNA sequence configuration spaces.
This class represents fitness landscapes where each configuration is an RNA sequence using the standard RNA alphabet (A, C, G, U).
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()
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:
-
Load the saved graph structure and attributes
-
Infer essential landscape properties from the graph
-
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()
to_graph(filepath: str) -> NoneSave 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_data()
get_data(
lo_only: bool = False, include_pagerank: bool = False
) -> pd.DataFrameExtracts 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
pagerankcolumn. PageRank is otherwise omitted -- it is an optional, comparatively expensive centrality that most callers do not need, soget_datano 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_dataorbuild_from_graph) before calling this method. Iflo_only=Trueand the LON graph (self.lon) is unexpectedly None despiteself.has_lonbeing True.
get_lon()
get_lon(
mlon: bool = True,
min_edge_freq: int = 3,
trim: Optional[int] = None,
verbose: Optional[bool] = None,
) -> ig.GraphConstructs 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
trimstrongest 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.lonattribute, andself.has_lonis 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()
describe() -> Dict[str, Any]Return a structured summary of the landscape as a dict.
Returns
-
dict class,kind,built,maximizeandepsilonare 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__).