-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmcts.html
236 lines (209 loc) · 7.21 KB
/
mcts.html
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MCTS</title>
<style>
body, html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
#mctsDiagramDiv {
width: 100%;
height: 100%;
border: 1px solid black;
}
</style>
</head>
<body>
<input type="file" id="jsonInput">
<div id="mctsDiagramDiv"></div>
<script src="go.js"></script>
<script>
// ----------- UTILITIES -------------
// Stringify with custom handling for 'state' key
function customStringify(obj) {
const entries = Object.entries(obj);
return `{ ${entries.map(([key, value]) => {
if (key === 'state') return `${key}: "${value.replace(/\\n/g, '\n')}"`;
return `${key}: ${JSON.stringify(value)}`;
}).join(',\n')} }`;
}
// Parse JSON data to derive parent-child relations
function parseJSON(jsonData) {
const parentMap = {};
jsonData.forEach((item) => {
if (item.children && item.children.length) {
item.children.forEach((childId) => parentMap[childId] = item.node_id);
}
});
return jsonData.map((item) => ({
key: item.node_id,
text: customStringify(item),
fill: item.fillcolor,
parent: parentMap[item.node_id],
children: item.children,
probabilities: item.probabilities,
accumulated_relative_values: item.accumulated_relative_values,
average_relative_values: item.average_relative_values,
visit_counts: item.visit_counts,
}));
}
function nodeStrokeConverter(node) {
if (node instanceof go.Node) {
// Check if the node is a leaf (has no children)
if (node.findTreeChildrenNodes().count === 0) {
return { color: 'black', width: 1 };
}
// Check if node is not expanded
if (!node.isTreeExpanded) {
return { color: 'orange', width: 20 };
}
}
// Default return
return { color: 'black', width: 1 };
}
// ----------- INITIALIZATION -------------
document.getElementById('jsonInput').addEventListener('change', (event) => {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function (e) {
const nodeDataArray = parseJSON(JSON.parse(e.target.result));
init(nodeDataArray);
};
reader.readAsText(file);
});
function init(nodeDataArray) {
const $ = go.GraphObject.make;
const myDiagram = $(go.Diagram, 'mctsDiagramDiv', {
layout: $(go.TreeLayout, {
angle: 90,
compaction: go.TreeLayout.CompactionNone,
arrangement: go.TreeLayout.ArrangementFixedRoots,
layerSpacing: 35, // Increase spacing between layers
layerSpacingParentOverlap: 1.0, // Overlap factor between parent and children
setsPortSpot: false, // Don't allow the layout to set port spots since we're using orthogonal links
setsChildPortSpot: false,
}),
allowCopy: false,
allowDelete: false,
allowMove: true,
initialAutoScale: go.Diagram.Uniform,
layout: $(FlatTreeLayout, {
angle: 90,
compaction: go.TreeLayout.CompactionNone,
arrangement: go.TreeLayout.ArrangementFixedRoots,
}),
'undoManager.isEnabled': true,
});
myDiagram.nodeTemplate = $(
go.Node,
'Vertical',
{
isTreeExpanded: false, // By default, nodes are collapsed
selectionObjectName: 'BODY',
},
$(
go.Panel,
'Auto',
{ name: 'BODY' },
$(
go.Shape,
'RoundedRectangle',
new go.Binding('fill'),
new go.Binding('stroke', '', (node) => nodeStrokeConverter(node).color).ofObject(),
new go.Binding('strokeWidth', '', (node) => nodeStrokeConverter(node).width).ofObject(),
),
$(go.TextBlock, {
font: 'bold 12pt Arial, sans-serif',
margin: new go.Margin(4, 2, 2, 2),
isMultiline: true,
textAlign: 'center',
editable: false,
}, new go.Binding('text')),
),
);
myDiagram.linkTemplate = $(
go.Link,
{
curve: go.Link.Bezier,
curviness: -10,
},
$(go.Shape, { stroke: '#007BFF', strokeWidth: 5 }),
$(
go.TextBlock,
{ name: 'LABEL', segmentOffset: new go.Point(0, -10) },
new go.Binding('text', '', ''),
),
);
myDiagram.toolManager.mouseWheelBehavior = go.ToolManager.WheelZoom;
myDiagram.addDiagramListener('ObjectDoubleClicked', (e) => {
const node = e.subject.part;
if (!(node instanceof go.Node)) return;
const { diagram } = node;
if (!diagram) return;
diagram.startTransaction('CollapseExpandTree');
if (node.isTreeExpanded) {
diagram.commandHandler.collapseTree(node);
} else {
node.expandTree(1); // Expand to just one level
}
diagram.commitTransaction('CollapseExpandTree');
});
myDiagram.addDiagramListener('InitialLayoutCompleted', (e) => {
// Find top-level nodes and expand them to one level
e.diagram.nodes.each((node) => {
if (!node.findTreeParentNode()) {
node.expandTree(1);
}
});
// Update the labels for all links after layout
e.diagram.links.each((link) => {
const fromNodeData = link.fromNode.data;
console.log(fromNodeData);
if (fromNodeData) {
// Extract the data object from the node's data
console.log(fromNodeData);
edge_index = fromNodeData.children.indexOf(link.toNode.data.key);
// Create a JSON object with the desired properties
const jsonObject = {
accumulated_relative_value: fromNodeData.accumulated_relative_values[edge_index],
average_relative_value: fromNodeData.average_relative_values[edge_index],
visit_count: fromNodeData.visit_counts[edge_index],
probability: fromNodeData.probabilities[edge_index],
};
link.findObject('LABEL').text = JSON.stringify(jsonObject, null, 2); // Pretty print with indentation
}
});
});
myDiagram.model = new go.TreeModel({ nodeDataArray });
myDiagram.nodes.each((node) => {
if (node.isTreeExpanded) myDiagram.commandHandler.collapseTree(node);
});
}
// Custom layout class for diagram
class FlatTreeLayout extends go.TreeLayout {
commitLayout() {
super.commitLayout();
let y = -Infinity;
this.network.vertexes.each((v) => {
y = Math.max(y, v.node.position.y);
});
this.network.vertexes.each((v) => {
if (v.destinationEdges.count === 0) {
v.node.moveTo(v.node.position.x, y);
v.node.toEndSegmentLength = Math.abs(v.centerY - y);
} else {
v.node.toEndSegmentLength = 10;
}
});
}
}
</script>
</body>
</html>