XCSF 1.4.8
XCSF learning classifier system
Loading...
Searching...
No Matches
viz.py
Go to the documentation of this file.
1#!/usr/bin/python3
2#
3# This program is free software: you can redistribute it and/or modify
4# it under the terms of the GNU General Public License as published by
5# the Free Software Foundation, either version 3 of the License, or
6# (at your option) any later version.
7#
8# This program is distributed in the hope that it will be useful,
9# but WITHOUT ANY WARRANTY; without even the implied warranty of
10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11# GNU General Public License for more details.
12#
13# You should have received a copy of the GNU General Public License
14# along with this program. If not, see <http://www.gnu.org/licenses/>.
15#
16
17
23
24"""Classes for visualising classifier knowledge representations."""
25
26from __future__ import annotations
27
28import graphviz
29
30
31class TreeViz:
32 """! Visualises a GP tree with graphviz."""
33
35 self,
36 tree: list[str],
37 filename: str,
38 note: str | None = None,
39 feature_names: list[str] | None = None,
40 ) -> None:
41 """
42 Plots a tree with graphviz, saving to a file.
43
44 Parameters
45 ----------
46 tree : list[str]
47 List of strings representing a GP tree.
48 filename : str
49 Name of the output file to save the drawn tree.
50 note : str, optional
51 Optional string to be added as a note/caption.
52 feature_names : list[str], optional
53 Optional list of feature names.
54 """
55 self.feature_names: list[str] | None = feature_names
56 self.tree: list[str] = tree
57 self.cnt: int = 0
58 self.pos: int = 0
59 self.gviz = graphviz.Graph("G", filename=filename + ".gv")
60 self.read_subexpr()
61 if note is not None:
62 self.gviz.attr(label=note)
63 self.gviz.view()
64
65 def label(self, symbol: str) -> str:
66 """Returns the node label for a symbol."""
67 if self.feature_names is not None and isinstance(symbol, str):
68 start, end = symbol.split("_") if "_" in symbol else (symbol, "")
69 if start == "feature" and int(end) < len(self.feature_names):
70 return self.feature_names[int(end)]
71 elif isinstance(symbol, float):
72 return f"{symbol:.5f}"
73 return str(symbol)
74
75 def read_function(self) -> str:
76 """Parses functions."""
77 expr1: str = self.read_subexpr()
78 symbol: str = self.tree[self.pos]
79 if symbol in ("+", "-", "*", "/"):
80 self.pos += 1
81 expr2 = self.read_function()
82 self.cnt += 1
83 self.gviz.edge(str(self.cnt), expr1)
84 self.gviz.edge(str(self.cnt), expr2)
85 self.gviz.node(str(self.cnt), label=self.label(symbol))
86 return expr2
87 return expr1
88
89 def read_subexpr(self) -> str:
90 """Parses sub-expressions."""
91 symbol: str = self.tree[self.pos]
92 self.pos += 1
93 if symbol == "(":
94 self.read_function()
95 self.pos += 1 # ')'
96 else:
97 self.cnt += 1
98 self.gviz.node(str(self.cnt), label=self.label(symbol))
99 return str(self.cnt)
100
101
102class DGPViz:
103 """! Visualises a DGP graph with graphviz."""
104
106 self,
107 graph: dict,
108 filename: str,
109 note: str | None = None,
110 feature_names: list[str] | None = None,
111 ) -> None:
112 """
113 Plots a DGP graph with graphviz, saving to a file.
114
115 Parameters
116 ----------
117 graph : dict
118 Dictionary representing a DGP graph.
119 filename : str
120 Name of the output file to save the drawn graph.
121 note : str, optional
122 Optional string to be added as a note/caption.
123 feature_names : list[str], optional
124 Optional list of feature names.
125 """
126 self.feature_names: list[str] | None = feature_names
127 self.n: int = graph["n"]
128 self.n_inputs: int = graph["n_inputs"]
129 self.functions: list[str] = graph["functions"]
130 self.connectivity: list[int] = graph["connectivity"]
131 self.k: int = int(len(self.connectivity) / self.n)
132 self.gviz = graphviz.Digraph("G", filename=filename + ".gv")
133 self.draw()
134 label: str = "" if note is None else note
135 label += "\nN = {graph['n']}\n"
136 label += f"T = {graph['t']}\n"
137 label += "match node shaded\n"
138 self.gviz.attr(label=label)
139 self.gviz.view()
140
141 def label(self, symbol: str) -> str:
142 """Returns the node label for a symbol."""
143 if self.feature_names is not None and isinstance(symbol, str):
144 start, end = symbol.split("_") if "_" in symbol else (symbol, "")
145 if start == "feature" and int(end) < len(self.feature_names):
146 return self.feature_names[int(end)]
147 elif isinstance(symbol, float):
148 return f"{symbol:.5f}"
149 return str(symbol)
150
151 def draw(self) -> None:
152 """Plots the nodes and edges in the graph."""
153 for i in range(self.n):
154 style: str = "filled" if i == 0 else "" # fill the match node
155 self.gviz.node(str(i), label=self.functions[i], style=style)
156 n_inputs: int = 1 if self.functions[i] == "Fuzzy NOT" else self.k
157 for j in range(n_inputs):
158 src = self.connectivity[(i * self.k) + j]
159 if src < self.n_inputs:
160 feature = f"feature_{src}"
161 self.gviz.node(feature, label=self.label(feature), shape="square")
162 self.gviz.edge(feature, str(i))
163 else:
164 self.gviz.edge(str(src - self.n_inputs), str(i))
Visualises a DGP graph with graphviz.
Definition viz.py:102
None draw(self)
Definition viz.py:151
None __init__(self, dict graph, str filename, str|None note=None, list[str]|None feature_names=None)
Definition viz.py:111
str label(self, str symbol)
Definition viz.py:141
Visualises a GP tree with graphviz.
Definition viz.py:31
str read_function(self)
Definition viz.py:75
str read_subexpr(self)
Definition viz.py:89
str label(self, str symbol)
Definition viz.py:65
None __init__(self, list[str] tree, str filename, str|None note=None, list[str]|None feature_names=None)
Definition viz.py:40