nocad 1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nocad/__init__.py +162 -0
- nocad/_graph.py +165 -0
- nocad/_utils.py +122 -0
- nocad/annotation.py +376 -0
- nocad/components.py +204 -0
- nocad/connection.py +263 -0
- nocad/data/__init__.py +1 -0
- nocad/data/networks.npz +0 -0
- nocad/datasets.py +432 -0
- nocad/design.py +512 -0
- nocad/distances.py +241 -0
- nocad/io.py +771 -0
- nocad/matching.py +323 -0
- nocad/measures/__init__.py +65 -0
- nocad/measures/network.py +258 -0
- nocad/measures/similarity.py +171 -0
- nocad/measures/summary.py +217 -0
- nocad/placement/__init__.py +208 -0
- nocad/placement/annealing.py +180 -0
- nocad/placement/heuristics.py +155 -0
- nocad/plotting.py +561 -0
- nocad/profiles.py +153 -0
- nocad/robustness.py +145 -0
- nocad/structural.py +354 -0
- nocad/viz/__init__.py +63 -0
- nocad/viz/layouts.py +474 -0
- nocad/viz/maps.py +580 -0
- nocad/viz/structure.py +527 -0
- nocad/viz/studies.py +207 -0
- nocad-1.0.dist-info/METADATA +203 -0
- nocad-1.0.dist-info/RECORD +33 -0
- nocad-1.0.dist-info/WHEEL +4 -0
- nocad-1.0.dist-info/licenses/LICENSE +21 -0
nocad/__init__.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 János Abonyi, Dániel Leitold, Ágnes Vathy-Fogarassy
|
|
3
|
+
"""nocad: network-based observability and controllability analysis of dynamical systems.
|
|
4
|
+
|
|
5
|
+
Python successor of the NOCAD toolbox for MATLAB and Octave (Leitold, Vathy-Fogarassy,
|
|
6
|
+
Abonyi). The network of the state variables of a linear system has an edge
|
|
7
|
+
:math:`x_j\\to x_i` whenever :math:`a_{ij}\\neq0`; its adjacency matrix is
|
|
8
|
+
:math:`\\mathbf{A}^{\\mathsf T}`.
|
|
9
|
+
|
|
10
|
+
Main entry points
|
|
11
|
+
-----------------
|
|
12
|
+
* :func:`maximum_matching`, :func:`driver_nodes`, :func:`sensor_nodes`,
|
|
13
|
+
:func:`generate_matrices`, :class:`InputOutputDesign` -- network mapping;
|
|
14
|
+
* :func:`is_controllable`, :func:`is_observable`, :mod:`nocad.measures` -- system
|
|
15
|
+
characterisation;
|
|
16
|
+
* :class:`nocad.placement.Placement`, :mod:`nocad.robustness` -- improvement and robustness;
|
|
17
|
+
* :mod:`nocad.viz` -- visualization of controllability and observability.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from . import annotation, datasets, io, measures, placement, plotting, viz
|
|
21
|
+
from ._graph import (
|
|
22
|
+
adjacency_to_state_matrix,
|
|
23
|
+
as_adjacency,
|
|
24
|
+
edge_list,
|
|
25
|
+
node_labels,
|
|
26
|
+
resolve_labels,
|
|
27
|
+
resolve_pos,
|
|
28
|
+
state_matrix_to_adjacency,
|
|
29
|
+
)
|
|
30
|
+
from ._utils import Bunch, check_random_state
|
|
31
|
+
from .annotation import annotate, edge_table, node_table
|
|
32
|
+
from .components import (
|
|
33
|
+
condensation,
|
|
34
|
+
sink_components,
|
|
35
|
+
source_components,
|
|
36
|
+
strongly_connected_components,
|
|
37
|
+
topological_order,
|
|
38
|
+
)
|
|
39
|
+
from .connection import (
|
|
40
|
+
CONNECTION_TYPES,
|
|
41
|
+
add_edge_dynamics,
|
|
42
|
+
add_node_dynamics,
|
|
43
|
+
apply_connection_type,
|
|
44
|
+
connection_type,
|
|
45
|
+
dynamics_heatmap,
|
|
46
|
+
)
|
|
47
|
+
from .design import (
|
|
48
|
+
InputOutputDesign,
|
|
49
|
+
driver_nodes,
|
|
50
|
+
generate_matrices,
|
|
51
|
+
generate_matrices_pf,
|
|
52
|
+
generate_matrices_ss,
|
|
53
|
+
maximum_matching_min,
|
|
54
|
+
maximum_matching_pf,
|
|
55
|
+
maximum_matching_ss,
|
|
56
|
+
n_driver_nodes,
|
|
57
|
+
sensor_nodes,
|
|
58
|
+
)
|
|
59
|
+
from .distances import (
|
|
60
|
+
control_depth,
|
|
61
|
+
control_regions,
|
|
62
|
+
geodesic_distances,
|
|
63
|
+
observation_depth,
|
|
64
|
+
observation_regions,
|
|
65
|
+
placement_cost,
|
|
66
|
+
relative_degree,
|
|
67
|
+
relative_degree_matrix,
|
|
68
|
+
)
|
|
69
|
+
from .io import from_networkx, from_state_space, to_networkx
|
|
70
|
+
from .io import read as read_network
|
|
71
|
+
from .io import write as write_network
|
|
72
|
+
from .matching import Matching, all_maximum_matchings, edge_classes, maximum_matching, node_roles
|
|
73
|
+
from .profiles import control_profile, driver_types, observation_profile, sensor_types
|
|
74
|
+
from .robustness import node_removal_robustness, robustness_table
|
|
75
|
+
from .structural import (
|
|
76
|
+
control_centrality,
|
|
77
|
+
controllable_subspace_dimension,
|
|
78
|
+
is_controllable,
|
|
79
|
+
is_observable,
|
|
80
|
+
is_structurally_controllable,
|
|
81
|
+
is_structurally_observable,
|
|
82
|
+
observe_centrality,
|
|
83
|
+
structural_rank,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
__version__ = "1.0"
|
|
87
|
+
|
|
88
|
+
__all__ = [
|
|
89
|
+
"annotation",
|
|
90
|
+
"io",
|
|
91
|
+
"datasets",
|
|
92
|
+
"measures",
|
|
93
|
+
"placement",
|
|
94
|
+
"plotting",
|
|
95
|
+
"viz",
|
|
96
|
+
"__version__",
|
|
97
|
+
"Bunch",
|
|
98
|
+
"check_random_state",
|
|
99
|
+
"as_adjacency",
|
|
100
|
+
"adjacency_to_state_matrix",
|
|
101
|
+
"state_matrix_to_adjacency",
|
|
102
|
+
"edge_list",
|
|
103
|
+
"node_labels",
|
|
104
|
+
"resolve_labels",
|
|
105
|
+
"resolve_pos",
|
|
106
|
+
"to_networkx",
|
|
107
|
+
"from_networkx",
|
|
108
|
+
"from_state_space",
|
|
109
|
+
"read_network",
|
|
110
|
+
"write_network",
|
|
111
|
+
"annotate",
|
|
112
|
+
"node_table",
|
|
113
|
+
"edge_table",
|
|
114
|
+
"condensation",
|
|
115
|
+
"strongly_connected_components",
|
|
116
|
+
"source_components",
|
|
117
|
+
"sink_components",
|
|
118
|
+
"topological_order",
|
|
119
|
+
"Matching",
|
|
120
|
+
"maximum_matching",
|
|
121
|
+
"node_roles",
|
|
122
|
+
"edge_classes",
|
|
123
|
+
"all_maximum_matchings",
|
|
124
|
+
"InputOutputDesign",
|
|
125
|
+
"driver_nodes",
|
|
126
|
+
"sensor_nodes",
|
|
127
|
+
"n_driver_nodes",
|
|
128
|
+
"generate_matrices",
|
|
129
|
+
"generate_matrices_pf",
|
|
130
|
+
"generate_matrices_ss",
|
|
131
|
+
"maximum_matching_pf",
|
|
132
|
+
"maximum_matching_ss",
|
|
133
|
+
"maximum_matching_min",
|
|
134
|
+
"is_controllable",
|
|
135
|
+
"is_observable",
|
|
136
|
+
"is_structurally_controllable",
|
|
137
|
+
"is_structurally_observable",
|
|
138
|
+
"structural_rank",
|
|
139
|
+
"controllable_subspace_dimension",
|
|
140
|
+
"control_centrality",
|
|
141
|
+
"observe_centrality",
|
|
142
|
+
"driver_types",
|
|
143
|
+
"sensor_types",
|
|
144
|
+
"control_profile",
|
|
145
|
+
"observation_profile",
|
|
146
|
+
"CONNECTION_TYPES",
|
|
147
|
+
"connection_type",
|
|
148
|
+
"apply_connection_type",
|
|
149
|
+
"add_node_dynamics",
|
|
150
|
+
"add_edge_dynamics",
|
|
151
|
+
"dynamics_heatmap",
|
|
152
|
+
"geodesic_distances",
|
|
153
|
+
"relative_degree",
|
|
154
|
+
"relative_degree_matrix",
|
|
155
|
+
"control_depth",
|
|
156
|
+
"observation_depth",
|
|
157
|
+
"control_regions",
|
|
158
|
+
"observation_regions",
|
|
159
|
+
"placement_cost",
|
|
160
|
+
"node_removal_robustness",
|
|
161
|
+
"robustness_table",
|
|
162
|
+
]
|
nocad/_graph.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 János Abonyi, Dániel Leitold, Ágnes Vathy-Fogarassy
|
|
3
|
+
r"""Conversion between the representations of a network of state variables.
|
|
4
|
+
|
|
5
|
+
The network :math:`\mathcal{G}` of a linear system :math:`\dot{\mathbf{x}}=\mathbf{A}\mathbf{x}+\dots`
|
|
6
|
+
has an edge :math:`x_j\to x_i` whenever :math:`a_{ij}\neq 0`. Its adjacency matrix
|
|
7
|
+
(``adj``, rows are start nodes) is therefore the transpose of :math:`\mathbf{A}`.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
import scipy.sparse as sp
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"as_adjacency",
|
|
17
|
+
"node_labels",
|
|
18
|
+
"resolve_labels",
|
|
19
|
+
"resolve_pos",
|
|
20
|
+
"adjacency_to_state_matrix",
|
|
21
|
+
"state_matrix_to_adjacency",
|
|
22
|
+
"edge_list",
|
|
23
|
+
"to_networkx",
|
|
24
|
+
"n_nodes",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _is_networkx(G) -> bool:
|
|
29
|
+
return type(G).__module__.startswith("networkx")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def as_adjacency(G, *, weighted: bool = False) -> sp.csr_array:
|
|
33
|
+
"""Return the adjacency matrix of a network as a sparse CSR array.
|
|
34
|
+
|
|
35
|
+
Parameters
|
|
36
|
+
----------
|
|
37
|
+
G : array-like, sparse matrix, networkx.DiGraph or pandas.DataFrame
|
|
38
|
+
Square matrix with ``G[i, j] != 0`` iff there is an edge :math:`x_i\\to x_j`,
|
|
39
|
+
or a directed networkx graph (nodes in insertion order).
|
|
40
|
+
weighted : bool, default=False
|
|
41
|
+
Keep the numeric weights; otherwise a boolean structure is returned.
|
|
42
|
+
|
|
43
|
+
Returns
|
|
44
|
+
-------
|
|
45
|
+
adj : scipy.sparse.csr_array of shape (N, N)
|
|
46
|
+
|
|
47
|
+
Examples
|
|
48
|
+
--------
|
|
49
|
+
>>> adj = as_adjacency([[0, 1], [0, 0]])
|
|
50
|
+
>>> adj.toarray()
|
|
51
|
+
array([[False, True],
|
|
52
|
+
[False, False]])
|
|
53
|
+
"""
|
|
54
|
+
if _is_networkx(G):
|
|
55
|
+
import networkx as nx
|
|
56
|
+
|
|
57
|
+
M = nx.to_scipy_sparse_array(G, nodelist=list(G.nodes()), weight="weight" if weighted else None)
|
|
58
|
+
M = sp.csr_array(M)
|
|
59
|
+
elif hasattr(G, "to_numpy") and hasattr(G, "columns"):
|
|
60
|
+
M = sp.csr_array(np.asarray(G.to_numpy(), dtype=float))
|
|
61
|
+
elif sp.issparse(G):
|
|
62
|
+
M = sp.csr_array(G)
|
|
63
|
+
else:
|
|
64
|
+
M = sp.csr_array(np.asarray(G, dtype=float))
|
|
65
|
+
if M.shape[0] != M.shape[1]:
|
|
66
|
+
raise ValueError(f"adjacency matrix must be square, got shape {M.shape}")
|
|
67
|
+
M = M.copy()
|
|
68
|
+
M.eliminate_zeros()
|
|
69
|
+
if weighted:
|
|
70
|
+
return M.astype(float)
|
|
71
|
+
out = sp.csr_array(M != 0)
|
|
72
|
+
out.sort_indices()
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def n_nodes(G) -> int:
|
|
77
|
+
"""Number of nodes (state variables) of a network."""
|
|
78
|
+
if _is_networkx(G):
|
|
79
|
+
return G.number_of_nodes()
|
|
80
|
+
return int(np.shape(G)[0]) if not sp.issparse(G) else int(G.shape[0])
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def node_labels(G, prefix: str = "x", start: int = 1) -> list[str]:
|
|
84
|
+
"""Labels of the nodes: networkx node names, DataFrame index, or ``x1, x2, ...``.
|
|
85
|
+
|
|
86
|
+
Examples
|
|
87
|
+
--------
|
|
88
|
+
>>> node_labels([[0, 1], [1, 0]])
|
|
89
|
+
['x1', 'x2']
|
|
90
|
+
"""
|
|
91
|
+
if _is_networkx(G):
|
|
92
|
+
return [str(v) for v in G.nodes()]
|
|
93
|
+
if hasattr(G, "index") and hasattr(G, "columns"):
|
|
94
|
+
return [str(v) for v in G.index]
|
|
95
|
+
return [f"{prefix}{i + start}" for i in range(n_nodes(G))]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def resolve_labels(G, labels=None):
|
|
99
|
+
"""Labels to draw: ``False`` stays ``False``, given labels are used as strings, and
|
|
100
|
+
otherwise the node names of the input (:func:`node_labels`)."""
|
|
101
|
+
if labels is False:
|
|
102
|
+
return False
|
|
103
|
+
if labels is None:
|
|
104
|
+
return node_labels(G)
|
|
105
|
+
return [str(v) for v in labels]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def resolve_pos(G, pos):
|
|
109
|
+
"""Positions as an ``(N, 2)`` array.
|
|
110
|
+
|
|
111
|
+
``pos`` may be an array, a mapping from node to coordinates in the NetworkX style
|
|
112
|
+
(keys: the nodes of a networkx graph, the labels, or the integer indices), or None.
|
|
113
|
+
|
|
114
|
+
Examples
|
|
115
|
+
--------
|
|
116
|
+
>>> resolve_pos([[0, 1], [0, 0]], {"x1": (0, 0), "x2": (1, 0)}).tolist()
|
|
117
|
+
[[0.0, 0.0], [1.0, 0.0]]
|
|
118
|
+
"""
|
|
119
|
+
if pos is None:
|
|
120
|
+
return None
|
|
121
|
+
if isinstance(pos, dict):
|
|
122
|
+
n = n_nodes(G)
|
|
123
|
+
keys = list(G.nodes()) if _is_networkx(G) else list(range(n))
|
|
124
|
+
names = node_labels(G)
|
|
125
|
+
out = np.zeros((n, 2))
|
|
126
|
+
for i in range(n):
|
|
127
|
+
for key in (keys[i], names[i], i):
|
|
128
|
+
if key in pos:
|
|
129
|
+
out[i] = np.asarray(pos[key], dtype=float)[:2]
|
|
130
|
+
break
|
|
131
|
+
else:
|
|
132
|
+
raise KeyError(f"no position for node {names[i]!r}")
|
|
133
|
+
return out
|
|
134
|
+
return np.asarray(pos, dtype=float)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def adjacency_to_state_matrix(adj, weighted: bool = False):
|
|
138
|
+
"""Structure (or weights) of :math:`\\mathbf{A}=\\mathbf{W}^{\\mathsf T}` from the adjacency matrix."""
|
|
139
|
+
return sp.csr_array(as_adjacency(adj, weighted=weighted).T)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def state_matrix_to_adjacency(A, weighted: bool = False):
|
|
143
|
+
"""Adjacency matrix :math:`\\mathbf{W}=\\mathbf{A}^{\\mathsf T}` of the state variables."""
|
|
144
|
+
return sp.csr_array(as_adjacency(A, weighted=weighted).T)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def edge_list(adj) -> np.ndarray:
|
|
148
|
+
"""Edges as an ``(E, 2)`` int array of (start, end) pairs, row-major order."""
|
|
149
|
+
A = sp.coo_array(as_adjacency(adj))
|
|
150
|
+
order = np.lexsort((A.col, A.row))
|
|
151
|
+
return np.column_stack([A.row[order], A.col[order]]).astype(int)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def to_networkx(adj, labels=None):
|
|
155
|
+
"""Directed networkx graph of the network (node attribute ``label``)."""
|
|
156
|
+
import networkx as nx
|
|
157
|
+
|
|
158
|
+
A = as_adjacency(adj)
|
|
159
|
+
G = nx.DiGraph()
|
|
160
|
+
n = A.shape[0]
|
|
161
|
+
labels = labels if labels is not None else node_labels(A)
|
|
162
|
+
for i in range(n):
|
|
163
|
+
G.add_node(i, label=labels[i])
|
|
164
|
+
G.add_edges_from(map(tuple, edge_list(A)))
|
|
165
|
+
return G
|
nocad/_utils.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT
|
|
2
|
+
# Copyright (c) 2026 János Abonyi, Dániel Leitold, Ágnes Vathy-Fogarassy
|
|
3
|
+
"""Small helpers shared by all modules (random state, Bunch, parameter handling)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import inspect
|
|
8
|
+
import numbers
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
__all__ = ["Bunch", "check_random_state", "BaseEstimator", "as_index_array"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Bunch(dict):
|
|
16
|
+
"""Dictionary with attribute access (as :class:`sklearn.utils.Bunch`).
|
|
17
|
+
|
|
18
|
+
Examples
|
|
19
|
+
--------
|
|
20
|
+
>>> b = Bunch(name="tank", n_states=3)
|
|
21
|
+
>>> b.name, b["n_states"]
|
|
22
|
+
('tank', 3)
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(self, **kwargs):
|
|
26
|
+
super().__init__(kwargs)
|
|
27
|
+
|
|
28
|
+
def __getattr__(self, key):
|
|
29
|
+
try:
|
|
30
|
+
return self[key]
|
|
31
|
+
except KeyError as exc: # pragma: no cover - mirrors sklearn
|
|
32
|
+
raise AttributeError(key) from exc
|
|
33
|
+
|
|
34
|
+
def __setattr__(self, key, value):
|
|
35
|
+
self[key] = value
|
|
36
|
+
|
|
37
|
+
def __dir__(self):
|
|
38
|
+
return list(self.keys())
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def check_random_state(seed) -> np.random.Generator:
|
|
42
|
+
"""Turn ``seed`` into a :class:`numpy.random.Generator`.
|
|
43
|
+
|
|
44
|
+
Parameters
|
|
45
|
+
----------
|
|
46
|
+
seed : None, int, numpy.random.Generator or numpy.random.RandomState
|
|
47
|
+
``None`` gives a fresh generator; an ``int`` a seeded one; a generator is
|
|
48
|
+
returned unchanged; a legacy ``RandomState`` is wrapped.
|
|
49
|
+
|
|
50
|
+
Examples
|
|
51
|
+
--------
|
|
52
|
+
>>> rng = check_random_state(0)
|
|
53
|
+
>>> int(rng.integers(10))
|
|
54
|
+
8
|
|
55
|
+
"""
|
|
56
|
+
if seed is None:
|
|
57
|
+
return np.random.default_rng()
|
|
58
|
+
if isinstance(seed, np.random.Generator):
|
|
59
|
+
return seed
|
|
60
|
+
if isinstance(seed, numbers.Integral):
|
|
61
|
+
return np.random.default_rng(int(seed))
|
|
62
|
+
if isinstance(seed, np.random.RandomState):
|
|
63
|
+
return np.random.default_rng(seed.randint(0, 2**31 - 1))
|
|
64
|
+
raise ValueError(f"{seed!r} cannot be used to seed a numpy.random.Generator")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def as_index_array(nodes, n: int | None = None) -> np.ndarray:
|
|
68
|
+
"""Convert a node selection (indices or boolean mask) to a sorted int array."""
|
|
69
|
+
if nodes is None:
|
|
70
|
+
return np.zeros(0, dtype=int)
|
|
71
|
+
arr = np.asarray(nodes)
|
|
72
|
+
if arr.dtype == bool:
|
|
73
|
+
if n is not None and arr.size != n:
|
|
74
|
+
raise ValueError("boolean node mask has the wrong length")
|
|
75
|
+
return np.flatnonzero(arr)
|
|
76
|
+
arr = np.unique(arr.astype(int).ravel())
|
|
77
|
+
if n is not None and arr.size and (arr.min() < 0 or arr.max() >= n):
|
|
78
|
+
raise ValueError("node index out of range")
|
|
79
|
+
return arr
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class BaseEstimator:
|
|
83
|
+
"""Minimal scikit-learn style base class: ``get_params``, ``set_params``, ``repr``."""
|
|
84
|
+
|
|
85
|
+
@classmethod
|
|
86
|
+
def _param_names(cls):
|
|
87
|
+
sig = inspect.signature(cls.__init__)
|
|
88
|
+
return [p.name for p in sig.parameters.values() if p.name != "self" and p.kind != p.VAR_KEYWORD]
|
|
89
|
+
|
|
90
|
+
def get_params(self, deep: bool = True) -> dict:
|
|
91
|
+
return {name: getattr(self, name) for name in self._param_names()}
|
|
92
|
+
|
|
93
|
+
def set_params(self, **params):
|
|
94
|
+
valid = set(self._param_names())
|
|
95
|
+
for key, value in params.items():
|
|
96
|
+
if key not in valid:
|
|
97
|
+
raise ValueError(f"invalid parameter {key!r} for {type(self).__name__}")
|
|
98
|
+
setattr(self, key, value)
|
|
99
|
+
return self
|
|
100
|
+
|
|
101
|
+
def __repr__(self) -> str:
|
|
102
|
+
defaults = {
|
|
103
|
+
p.name: p.default
|
|
104
|
+
for p in inspect.signature(type(self).__init__).parameters.values()
|
|
105
|
+
if p.name != "self"
|
|
106
|
+
}
|
|
107
|
+
changed = []
|
|
108
|
+
for name, value in self.get_params().items():
|
|
109
|
+
default = defaults.get(name, inspect.Parameter.empty)
|
|
110
|
+
same = default is value
|
|
111
|
+
if not same:
|
|
112
|
+
try:
|
|
113
|
+
same = bool(default == value)
|
|
114
|
+
except Exception: # noqa: BLE001 - arrays etc.
|
|
115
|
+
same = False
|
|
116
|
+
if not same:
|
|
117
|
+
changed.append(f"{name}={value!r}")
|
|
118
|
+
return f"{type(self).__name__}({', '.join(changed)})"
|
|
119
|
+
|
|
120
|
+
def _check_fitted(self, attr: str):
|
|
121
|
+
if not hasattr(self, attr):
|
|
122
|
+
raise RuntimeError(f"{type(self).__name__} is not fitted yet; call fit() first")
|