# SPDX-License-Identifier: MIT
# Copyright (c) 2026 János Abonyi, Dániel Leitold, Ágnes Vathy-Fogarassy
r"""Improvement of input and output configurations (NOCAD module 3).
:class:`Placement` adds driver or sensor nodes to the matching-based configuration so
that the relative order of the system does not exceed a bound, with five methods:
grassroot and retrofit set covering, the centrality-based retrofit, mCLASA and
GDFCMSA. :func:`improve_configuration` runs all of them for drivers and sensors and
returns a comparison table (MATLAB ``extendData``).
"""
from __future__ import annotations
import numpy as np
import pandas as pd
import scipy.sparse as sp
from .._graph import as_adjacency
from .._utils import BaseEstimator, check_random_state
from ..design import driver_nodes
from ..distances import geodesic_distances, placement_cost
from .annealing import anneal, annealing_placement
from .heuristics import centrality_retrofit, greedy_set_cover, reach_within, set_cover, set_cover_except
__all__ = [
"PLACEMENT_METHODS",
"Placement",
"improve_configuration",
"anneal",
"annealing_placement",
"centrality_retrofit",
"greedy_set_cover",
"reach_within",
"set_cover",
"set_cover_except",
"configuration_cost",
]
PLACEMENT_METHODS = ("set_cover", "retrofit", "centrality", "mclasa", "gdfcmsa")
[docs]
def configuration_cost(adj, nodes, kind: str = "drivers", beta: float = 0.5):
"""Cost, maximal and mean relative order of a configuration (unreachable = N)."""
A = as_adjacency(adj)
G = A if kind == "drivers" else sp.csr_array(A.T)
D = geodesic_distances(G)
D[~np.isfinite(D)] = A.shape[0]
return placement_cost(D, np.asarray(nodes, dtype=int), beta)
[docs]
class Placement(BaseEstimator):
r"""Place additional driver or sensor nodes to bound the relative order.
Parameters
----------
kind : {"sensors", "drivers"}, default="sensors"
method : {"set_cover", "retrofit", "centrality", "mclasa", "gdfcmsa"}, default="gdfcmsa"
r_max : int, optional
Required bound on the relative order (network distance). Needed by the set
covering and centrality methods; the annealing methods add nodes until it holds.
n_add : int, optional
Number of nodes added by the annealing methods when ``r_max`` is None.
beta : float, default=0.5
Weight of the worst case in the cost.
n_iter, n_runs : int, default=500, 10
Annealing iterations and independent runs.
base : str, default="path_finding"
Method of the initial (fixed) configuration, see :func:`nocad.driver_nodes`.
random_state : int, Generator or None
Attributes
----------
base_nodes_ : ndarray
Matching-based configuration that ensures controllability (observability).
nodes_ : ndarray
Final configuration.
n_added_ : int
cost_, max_order_, mean_order_ : float
depth_ : ndarray of shape (N,)
Control (observation) depth of every state for the final configuration.
history_ : pandas.DataFrame
Annealing methods: best result for every number of added nodes.
Examples
--------
>>> from nocad.datasets import load_nocad_example
>>> p = Placement(kind="drivers", method="retrofit", r_max=2).fit(load_nocad_example().adj)
>>> p.base_nodes_, p.nodes_, p.max_order_
(array([7]), array([3, 7]), 2.0)
"""
def __init__(
self,
kind: str = "sensors",
method: str = "gdfcmsa",
r_max=None,
n_add=None,
beta: float = 0.5,
n_iter: int = 500,
n_runs: int = 10,
base: str = "path_finding",
random_state=None,
):
self.kind = kind
self.method = method
self.r_max = r_max
self.n_add = n_add
self.beta = beta
self.n_iter = n_iter
self.n_runs = n_runs
self.base = base
self.random_state = random_state
def fit(self, adj, y=None):
if self.kind not in ("sensors", "drivers"):
raise ValueError("kind must be 'sensors' or 'drivers'")
if self.method not in PLACEMENT_METHODS:
raise ValueError(f"method must be one of {PLACEMENT_METHODS}")
A = as_adjacency(adj)
G = A if self.kind == "drivers" else sp.csr_array(A.T)
self.adj_ = A
base = driver_nodes(G, self.base)
self.base_nodes_ = base
history = None
if self.method in ("set_cover", "retrofit", "centrality") and self.r_max is None:
raise ValueError(f"method {self.method!r} needs r_max")
if self.method == "set_cover":
nodes = set_cover(G, self.r_max)
elif self.method == "retrofit":
nodes = set_cover_except(G, self.r_max, base)
elif self.method == "centrality":
nodes = centrality_retrofit(G, base, self.r_max)
else:
nodes, history = annealing_placement(
G,
base,
method=self.method,
r_max=self.r_max,
n_add=self.n_add,
beta=self.beta,
n_iter=self.n_iter,
n_runs=self.n_runs,
random_state=check_random_state(self.random_state),
)
self.nodes_ = np.sort(np.asarray(nodes, dtype=int))
self.n_added_ = int(np.setdiff1d(self.nodes_, base).size)
D = geodesic_distances(G)
self.depth_ = D[self.nodes_].min(axis=0) if self.nodes_.size else np.full(A.shape[0], np.inf)
D[~np.isfinite(D)] = A.shape[0]
self.cost_, self.max_order_, self.mean_order_ = placement_cost(D, self.nodes_, self.beta)
self.history_ = pd.DataFrame(history) if history is not None else None
return self
[docs]
def improve_configuration(
adj,
r_max: int,
beta: float = 0.5,
n_iter: int = 500,
n_runs: int = 10,
methods=PLACEMENT_METHODS,
random_state=0,
) -> pd.DataFrame:
"""Compare the five placement methods for drivers and sensors (MATLAB ``extendData``).
Returns
-------
table : DataFrame with one row per (kind, method): number of nodes, added nodes, cost,
maximal and mean relative order, structural controllability (observability) of the
configuration and the node list.
"""
from ..structural import is_structurally_controllable
rng = check_random_state(random_state)
A = as_adjacency(adj)
n = A.shape[0]
rows = []
for kind in ("drivers", "sensors"):
G = A if kind == "drivers" else sp.csr_array(A.T)
for method in methods:
p = Placement(
kind=kind,
method=method,
r_max=r_max,
beta=beta,
n_iter=n_iter,
n_runs=n_runs,
random_state=rng,
).fit(A)
Bm = sp.csr_array(
(np.ones(p.nodes_.size), (p.nodes_, np.arange(p.nodes_.size))),
shape=(n, max(p.nodes_.size, 1)),
)
ok = is_structurally_controllable(sp.csr_array(G.T), Bm) if p.nodes_.size else False
rows.append(
{
"kind": kind,
"method": method,
"n_nodes": int(p.nodes_.size),
"n_added": p.n_added_,
"cost": p.cost_,
"max_order": p.max_order_,
"mean_order": p.mean_order_,
"structural": ok,
"nodes": p.nodes_.tolist(),
}
)
return pd.DataFrame(rows)