-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgraphlink_chart_data.py
More file actions
194 lines (162 loc) · 7.58 KB
/
Copy pathgraphlink_chart_data.py
File metadata and controls
194 lines (162 loc) · 7.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
"""Canonical chart-data validation shared by generation, rendering, and storage."""
from __future__ import annotations
import math
SUPPORTED_CHART_TYPES = frozenset({"bar", "line", "pie", "histogram", "sankey"})
MAX_SERIES_POINTS = 300
MAX_SANKEY_FLOWS = 300
MAX_LABEL_LENGTH = 160
MAX_TITLE_LENGTH = 200
class ChartDataError(ValueError):
"""Raised when a chart payload cannot be converted to the canonical schema."""
def _finite_number(value, field_name):
if isinstance(value, bool):
raise ChartDataError(f"{field_name} must be a finite number")
try:
number = float(value)
except (TypeError, ValueError) as exc:
raise ChartDataError(f"{field_name} must be a finite number") from exc
if not math.isfinite(number):
raise ChartDataError(f"{field_name} must be a finite number")
return number
def _clean_text(value, field_name, *, default="", max_length=MAX_LABEL_LENGTH):
text = " ".join(str(value if value is not None else "").split()).strip()
if not text:
if default:
return default
raise ChartDataError(f"{field_name} must be non-empty")
if len(text) > max_length:
raise ChartDataError(f"{field_name} is too long (maximum {max_length} characters)")
return text
def _legacy_sankey_flows(payload):
nested = payload.get("data")
if not isinstance(nested, dict):
return None
nodes = nested.get("nodes", [])
links = nested.get("links", [])
if not isinstance(nodes, list) or not isinstance(links, list):
return None
names = []
for index, node in enumerate(nodes):
if isinstance(node, dict):
node_name = node.get("name", f"Node {index}")
else:
node_name = node
names.append(str(node_name).strip())
flows = []
for link in links:
if not isinstance(link, dict):
raise ChartDataError("Sankey links must be objects")
source = link.get("source")
target = link.get("target")
if isinstance(source, int) and 0 <= source < len(names):
source = names[source]
if isinstance(target, int) and 0 <= target < len(names):
target = names[target]
flows.append({"source": source, "target": target, "value": link.get("value")})
return flows
def _assert_acyclic(flows):
adjacency = {}
for flow in flows:
adjacency.setdefault(flow["source"], set()).add(flow["target"])
adjacency.setdefault(flow["target"], set())
visiting = set()
visited = set()
def visit(node):
if node in visiting:
raise ChartDataError("Sankey charts cannot contain cycles")
if node in visited:
return
visiting.add(node)
for target in sorted(adjacency.get(node, ())):
visit(target)
visiting.remove(node)
visited.add(node)
for node in sorted(adjacency):
visit(node)
def canonicalize_chart_data(data, chart_type=None):
"""Return a new, bounded chart payload or raise :class:`ChartDataError`.
The function intentionally does not mutate ``data``. Callers that retain the
legacy in-place API can copy the returned mapping back into their payload.
"""
if not isinstance(data, dict):
raise ChartDataError("Chart payload must be a JSON object")
expected_type = str(chart_type or data.get("type") or "").strip().lower()
if expected_type not in SUPPORTED_CHART_TYPES:
raise ChartDataError(f"Unsupported chart type: {expected_type or 'unknown'}")
actual_type = str(data.get("type") or expected_type).strip().lower()
if actual_type != expected_type:
raise ChartDataError(f"Chart payload type must be {expected_type}")
result = {
"type": expected_type,
"title": _clean_text(
data.get("title"),
"Chart title",
default=f"{expected_type.title()} Chart",
max_length=MAX_TITLE_LENGTH,
),
}
if expected_type in {"bar", "line", "pie"}:
labels = data.get("labels")
values = data.get("values")
if not isinstance(labels, list) or not isinstance(values, list):
raise ChartDataError("Labels and values must both be lists")
if not labels or not values:
raise ChartDataError(f"{expected_type.title()} charts require at least one data point")
if len(labels) != len(values):
raise ChartDataError("Labels and values must have the same length")
if len(labels) > MAX_SERIES_POINTS:
raise ChartDataError(f"Charts support at most {MAX_SERIES_POINTS} data points")
if expected_type == "line" and len(labels) < 2:
raise ChartDataError("Line charts require at least two data points")
result["labels"] = [_clean_text(label, f"Label at index {index}") for index, label in enumerate(labels)]
result["values"] = [
_finite_number(value, f"Value at index {index}") for index, value in enumerate(values)
]
if expected_type == "pie" and any(value <= 0 for value in result["values"]):
raise ChartDataError("Pie chart values must be greater than zero")
result["xAxis"] = _clean_text(
data.get("xAxis"),
"X-axis label",
default="Category" if expected_type == "bar" else "Sequence",
max_length=MAX_LABEL_LENGTH,
)
result["yAxis"] = _clean_text(data.get("yAxis"), "Y-axis label", default="Value", max_length=MAX_LABEL_LENGTH)
return result
if expected_type == "histogram":
values = data.get("values")
if not isinstance(values, list) or len(values) < 2:
raise ChartDataError("Histogram charts require at least two values")
if len(values) > MAX_SERIES_POINTS:
raise ChartDataError(f"Histograms support at most {MAX_SERIES_POINTS} values")
bins = _finite_number(data.get("bins", 10), "Histogram bins")
if bins < 2:
raise ChartDataError("Histogram bins must be at least 2")
result["values"] = [_finite_number(value, f"Value at index {index}") for index, value in enumerate(values)]
result["bins"] = max(2, min(int(bins), 24, len(values)))
result["xAxis"] = _clean_text(data.get("xAxis"), "X-axis label", default="Value", max_length=MAX_LABEL_LENGTH)
result["yAxis"] = _clean_text(data.get("yAxis"), "Y-axis label", default="Frequency", max_length=MAX_LABEL_LENGTH)
return result
raw_flows = data.get("flows")
if raw_flows is None:
raw_flows = _legacy_sankey_flows(data)
if not isinstance(raw_flows, list) or not raw_flows:
raise ChartDataError("Sankey charts require at least one flow")
if len(raw_flows) > MAX_SANKEY_FLOWS:
raise ChartDataError(f"Sankey charts support at most {MAX_SANKEY_FLOWS} flows")
aggregated = {}
for index, flow in enumerate(raw_flows):
if not isinstance(flow, dict):
raise ChartDataError(f"Sankey flow at index {index} must be an object")
source = _clean_text(flow.get("source"), f"Sankey source at index {index}")
target = _clean_text(flow.get("target"), f"Sankey target at index {index}")
value = _finite_number(flow.get("value"), f"Sankey value at index {index}")
if value <= 0:
raise ChartDataError(f"Sankey value at index {index} must be greater than zero")
key = (source, target)
aggregated[key] = aggregated.get(key, 0.0) + value
result["flows"] = [
{"source": source, "target": target, "value": value}
for (source, target), value in sorted(aggregated.items())
]
_assert_acyclic(result["flows"])
return result