-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplugin.js
1198 lines (1051 loc) · 38.8 KB
/
plugin.js
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Tree Globals
var stateCounter, graph, treemap, svg, duration, treeData, treeHeight, goTree = true, heurMax = 0;
var root, d3, zoom, viewerWidth, viewerHeight;
// Heuristic globals
var hSim, svgID, heursvg, svgCount = 1, actions, fluents, fluentPreconditions = {}, formattedActions, heurdata;
var UNFOLD_LIMIT = 15;
// Called when you click 'Go' on the file chooser
function loadStatespace() {
// Getting string versions of the selected files
var domain = window.ace.edit($('#domainSelection').find(':selected').val()).getSession().getValue();
var problem = window.ace.edit($('#problemSelection').find(':selected').val()).getSession().getValue();
window.heuristicVizDomain = domain;
window.heuristicVizProblem = problem;
// Lowering the choose file modal menu
$('#chooseFilesModal').modal('toggle');
$('#plannerURLInput').show();
// Ground the domain and problem
ground(domain, problem).then(function (result) {
treeData = { "name": "root", "children": [], "state": result.state, "strState": result.strState, "precondition": null, "loadedChildren": false };
stateCounter = 1;
launchViz();
});
}
function launchViz() {
window.new_tab('Statespace', function (editor_name) {
$('#' + editor_name).html('<div style = "margin:13px 26px;text-align:center"><h2>Heuristic Search Vizualization</h2>' +
//'<button onclick="zoomIn()" style="float:right;margin-left:16px" id ="ZoomIn">ZoomIn</button>' +
//'<button onclick="zoomOut()" style="float:right;margin-left:16px" id ="ZoomOut">ZoomOut</button>' +
'<div class="row">' +
' <div id="statespace" class="col-md-9"></div>' +
' <div id="statepanel" class="col-md-3">' +
' <div id="statebuttons" style="padding:10px">' +
' <button onclick="show_hadd()" type="button" class="btn btn-info">hadd</button>' +
' <button onclick="compute_plan()" type="button" class="btn btn-success">Plan</button><br /><br />' +
' <button onclick="compute_all_heur()" type="button" class="btn btn-primary">Compute All Heuristics</button>' +
' </div>' +
' <div id="statename" style="clear:both">State</div>' +
' <div id="statedetails" style="padding:10px"></div>' +
' </div>' +
'</div>' +
'<node circle style ="fill:black;stroke:black;stroke-width:3px;></node circle>' +
'<p id="hv-output"></p>');
});
makeTree();
}
// Generates the SVG object, and loads the tree data into a d3 style tree
function makeTree() {
// Prevents the creation of more than one tree
if (goTree) {
// Set the dimensions and margins of the diagram
var margin = { top: 20, right: 30, bottom: 30, left: 90 };
var width = $('#statespace').width() - margin.left - margin.right;
var height = 700 - margin.top - margin.bottom;
// Initialize d3 zoom
zoom = d3.zoom().on('zoom', function () {
svg.attr('transform', d3.event.transform);
})
// Declaring the SVG object, init attributes
svg = d3.select("#statespace").append("svg")
.attr("width", "100%")
.attr("height", height + margin.top + margin.bottom)
.style("background-color", "white")
.call(zoom)
.on("dblclick.zoom", null)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.append("g")
.attr("transform", "translate(" + (width / 2) + "," + margin.top + ")");
// create the tooltip
d3.select("#statespace")
.append("div")
.style("opacity", 0)
.attr("class", "tooltip")
.style("background-color", "white")
.style("border", "solid")
.style("border-width", "2px")
.style("border-radius", "5px")
.style("padding", "5px")
// Num and duration of animations
duration = 750;
// declares a tree layout and assigns the size
treemap = d3.tree().size([height, width]);
// Assigns parent, children, height, depth
root = d3.hierarchy(treeData, function (d) { return d.children; });
root.x0 = height / 2;
root.y0 = 0;
// Loads children of root
loadData(root, function (result) {
convertNode(result);
update(result);
// Preventing multiple trees
goTree = false;
});
}
}
// d3 zoom in
function zoomIn() {
zoom.scaleBy(svg.transition().duration(750), 1.3);
}
// d3 zoom out
function zoomOut() {
zoom.scaleBy(svg, 1 / 1.3);
}
// Loads children of a supplied node
function loadData(node, callback) {
if (!node.loadedChildren) {
const state = node.data.state;
getChildStates(state)
.then(data => {
for (let i = 0; i < data['states'].length; i++) {
if (node.data.children) {
// Create data
const newName = "State " + stateCounter;
stateCounter += 1;
const newState = { "name": newName, "children": [], "state": data.states[i], "strState": data.stringStates[i], "precondition": data.actions[i].toString(), "loadedChildren": false };
node.data.children.push(newState);
}
}
node.loadedChildren = true;
// Call the callback function with the node that contains
// the newly loaded children
callback(node);
});
}
}
// Converts the node to d3 tree form using d3.hierarchy
// and initializes other properties
function convertNode(node) {
// Get children of node
const allChildren = node.data.children;
// Var to hold formatted children
const newHierarchyChildren = [];
allChildren.forEach((child) => {
const newNode = d3.hierarchy(child); // create a node
newNode.depth = node.depth + 1; // update depth depends on parent
newNode.height = node.height;
newNode.parent = node; // set parent
newNode.id = String(child.id); // set uniq id
newHierarchyChildren.push(newNode);
});
// Add to parent's children array and collapse
node.children = newHierarchyChildren;
node._children = newHierarchyChildren;
}
function nodeSelected(d) {
window.current_state_node = d;
var action_desc = "";
if (d.data.precondition)
action_desc = infix(d.data.precondition.toLowerCase());
$('#statename').html('<div style="float:left; padding-left:13px">' + d.data.name + '</div><div style="display:inline-block">' + action_desc + '</div>');
var fluents = [];
d.data.strState.forEach(f => {
fluents.push(infix(f).toLowerCase());
});
$('#statedetails').html('<pre style="text-align: left">' + fluents.sort().join('\n') + '</pre>');
// Compute the heuristic value of this node
if ((d.data.heuristic_value === undefined) || (d.data.heuristic_value == '??')) {
graph = makeGraph(d);
heurdata = generateHeuristicGraphData(graph);
d.data.heuristic_value = autoUpdate(graph, true, false);
heurMax = Math.max(d.data.heuristic_value, heurMax);
update(d);
}
}
function nodeChildrenToggled(d, cb = null) {
if (d3.event && d3.event.defaultPrevented) return;
if (!d.loadedChildren && !d.children) {
// Load children, expand
loadData(d, result => {
convertNode(d);
d.children = d._children;
d._children = null;
update(d);
if (cb)
cb(d);
});
}
else if (d.children) {
d._children = d.children;
d.children = null;
update(d);
if (cb)
cb(d);
} else {
d.children = d._children;
d._children = null;
update(d);
if (cb)
cb(d);
}
}
function infix(orig) {
return '(' + orig.split('(')[0] + ' ' + orig.split('(')[1].split(')')[0].split(',').join(' ') + ')'
}
function normalized_check(first, second) {
return first.replaceAll(' ', '').toLowerCase() == second.replaceAll(' ', '').toLowerCase();
}
function successor_node(src, act) {
for (var i = 0; i < src.children.length; i++) {
if (normalized_check(infix(src.children[i].data.precondition), act))
return src.children[i];
}
}
async function compute_all_heur() {
toastr.info("Computing heuristic values...");
// Delaying just to get the toastr shown
setTimeout(function () {
// Compute heuristic values for all nodes
// and update the tree
treemap(root).descendants().forEach(d => {
if ((d.data.heuristic_value === undefined) || (d.data.heuristic_value == '??')) {
graph = makeGraph(d);
heurdata = generateHeuristicGraphData(graph);
d.data.heuristic_value = autoUpdate(graph, true, false);
heurMax = Math.max(d.data.heuristic_value, heurMax);
}
});
toastr.success("Done computing heuristic values!")
update(root);
}, 400);
}
function compute_plan() {
var fluents = [];
window.current_state_node.data.strState.forEach(f => {
fluents.push(infix(f));
});
var new_prob = '';
var old_prob = window.heuristicVizProblem;
var open_brackets = 0;
for (var i = 0; i < old_prob.length; i++) {
if (old_prob.substring(i, i + 5) == ":init") {
new_prob += ":init " + fluents.join('\n') + ')\n';
open_brackets = 1;
}
if (open_brackets) {
if (old_prob[i] == '(')
open_brackets += 1;
else if (old_prob[i] == ')')
open_brackets -= 1
} else {
new_prob += old_prob[i];
}
}
$.ajax({
url: "https://solver.planning.domains/solve-and-validate",
type: "POST",
contentType: 'application/json',
data: JSON.stringify({
"domain": window.heuristicVizDomain,
"problem": new_prob
})
})
.done(function (res) {
if (res['status'] === 'ok') {
toastr.success('Plan found!');
// Restrict the plan length if it is larger than UNFOLD_LIMIT
if (res.result.plan.length > UNFOLD_LIMIT) {
toastr.info("Plan too long, only the first " + UNFOLD_LIMIT + " actions will be used.");
res.result.plan = res.result.plan.slice(0, UNFOLD_LIMIT);
}
var index = 0;
var time_per_reveal = Math.min(300, (4000.0 / res.result.plan.length));
function _expand(cur_node) {
if (index < res.result.plan.length) {
// console.log(res.result.plan[index].name);
// console.log('i='+index);
if (cur_node.children == null) {
nodeChildrenToggled(cur_node, function (d) {
var act = res.result.plan[index].name
index += 1;
setTimeout(_expand, time_per_reveal, successor_node(cur_node, act));
});
}
} else {
if (cur_node) {
// Compute the heuristic for the current node (presumably the goal)
graph = makeGraph(cur_node);
heurdata = generateHeuristicGraphData(graph);
cur_node.data.heuristic_value = autoUpdate(graph, true, false);
heurMax = Math.max(cur_node.data.heuristic_value, heurMax);
update(root);
}
}
}
_expand(window.current_state_node);
} else {
toastr.error('Planning failed.');
}
}
);
}
// Single click on node: update the info shown for a node
function click(d) {
nodeSelected(d);
}
// Double click on node: expand/collapse children
function dblclick(d) {
nodeChildrenToggled(d);
}
// Called when the hadd button is clicked
function show_hadd() {
startHeuristicViz(window.current_state_node);
}
// Collapses the node and all it's children
function collapse(d) {
if (d.children) {
d._children = d.children
d._children.forEach(collapse)
d.children = null
}
}
// Updates the tree: drawing links, nodes, and tooltip
function update(source) {
//Assigns the x and y position for the nodes
var treeData = treemap(root);
// Compute the new tree layout.
var nodes = treeData.descendants(),
links = treeData.descendants().slice(1);
// Normalize for fixed-depth.
nodes.forEach(function (d) {
if (d.depth > treeHeight)
treeHeight = d.depth;
d.y = d.depth * 130;
if (d.data.name === "goal state") {
while (d !== root) {
d.path = true;
d = d.parent;
}
}
});
// ****************** Nodes section ***************************
var Tooltip = d3.select(".tooltip");
// Three function that change the tooltip when user hover / move / leave a cell
var mouseover = function (d) {
Tooltip
.style("opacity", 1)
d3.select(this)
.style("stroke", "black")
.style("opacity", 1);
hoveredOverStateInStatespace(d);
}
var mousemove = function (d) {
Tooltip
.html(formatTooltip(d))
.style("left", (d3.event.pageX - 400) + "px")
.style("top", (d3.event.pageY - 50) + "px");
}
var mouseleave = function (d) {
Tooltip
.style("opacity", 0)
d3.select(this)
.style("stroke", "none");
}
var getColor = function (d) {
if (d.data.heuristic_value == 0)
return '#FFD700'; // gold
else if (d.data.heuristic_value == Number.POSITIVE_INFINITY)
return '#000000'; // black
else
return d3.interpolateHsl('red', 'blue')(d.data.heuristic_value / heurMax);
}
// Update the nodes...
var node = svg.selectAll('g.node')
.data(nodes, function (d) { return d.data.name; })
// Enter any new modes at the parent's previous position.
var nodeEnter = node.enter().append('g')
.attr('class', 'node')
.attr("transform", function (d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.on('click', click)
.on('dblclick', dblclick)
.on("mouseover", mouseover)
.on("mousemove", mousemove)
.on("mouseleave", mouseleave);
// Add Circle for the nodes
nodeEnter.append('circle')
.attr('class', 'node')
.attr('r', 1e-6)
.style("fill", "lightsteelblue");
// Add labels for the nodes
/*
nodeEnter.append('text')
.attr("dy", ".35em")
.attr("x", function(d) {
return d.children || d._children ? -13 : 13;
})
.attr("text-anchor", function(d) {
return d.children || d._children ? "end" : "start";
})
.text(function(d) { return d.data.name; });
*/
// UPDATE
var nodeUpdate = nodeEnter.merge(node);
// Transition to the proper position for the node
nodeUpdate.transition()
.duration(duration)
.attr("transform", function (d) {
return "translate(" + d.y + "," + d.x + ")";
});
// Update the node attributes and style
nodeUpdate.select('circle.node')
.attr('r', 10)
.style("fill", getColor)
.attr('cursor', 'pointer');
// Remove any exiting nodes
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function (d) {
return "translate(" + source.y + "," + source.x + ")";
})
.remove();
// On exit reduce the node circles size to 0
nodeExit.select('circle')
.attr('r', 1e-6);
// On exit reduce the opacity of text labels
nodeExit.select('text')
.style('fill-opacity', 1e-6);
// ****************** links section ***************************
// Update the links...
var link = svg.selectAll('path.link')
.data(links, function (d) { return d.data.name; });
// Enter any new links at the parent's previous position.
var linkEnter = link.enter().insert('path', "g")
.attr("class", "link")
.attr('d', function (d) {
var o = { x: source.x0, y: source.y0 }
return diagonal(o, o)
})
.on('mousemove', function (d) {
Tooltip
.html(formatTooltip(d, false))
.style("left", (d3.event.pageX - 400) + "px")
.style("top", (d3.event.pageY - 50) + "px");
})
.on('mouseleave', function (d) {
Tooltip
.style("opacity", 0)
d3.select(this)
.style("stroke", "#ccc");
})
.on('mouseover', function (d) {
Tooltip
.style("opacity", 1)
d3.select(this)
.style("stroke", "black")
.style("opacity", 1);
})
.style("fill", "none")
.style("stroke", "#ccc")
.style("stroke-width", "2px");
// UPDATE
var linkUpdate = linkEnter.merge(link);
// Transition back to the parent element position
linkUpdate.transition()
.duration(duration)
.attr('d', function (d) { return diagonal(d, d.parent) });
// Remove any exiting links
var linkExit = link.exit().transition()
.duration(duration)
.attr('d', function (d) {
var o = { x: source.x, y: source.y }
return diagonal(o, o)
})
.remove();
// Store the old positions for transition.
nodes.forEach(function (d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
// Creates a curved (diagonal) path from parent to the child nodes
function diagonal(s, d) {
path = `M ${s.y} ${s.x}
C ${(s.y + d.y) / 2} ${s.x},
${(s.y + d.y) / 2} ${d.x},
${d.y} ${d.x}`
return path
}
// Returns a string of formatted html
function formatTooltip(d, node = true) {
if (node) {
if (d.data.heuristic_value === undefined)
d.data.heuristic_value = '??';
return "h=" + d.data.heuristic_value;
} else {
// console.log(infix(d.data.precondition).toLowerCase());
return infix(d.data.precondition).toLowerCase();
}
}
function hoveredOverStateInStatespace(d) {
console.log("Hovered over state ", d, " in the state space.");
}
/*
--------------------------------------------------------------------------------
END OF TREE CODE
--------------------------------------------------------------------------------
*/
/*
--------------------------------------------------------------------------------
START OF HEURISTIC GRAPH CODE
--------------------------------------------------------------------------------
*/
// Make graph function, returns false if the problem is not a legal version for the heuristic
function makeGraph(state) {
var graph = new Map();
let index = 1;
fluents = getGroundedFluents();
actions = getGroundedActions();
if (actions == false) {
// Precondition has a negative, cannot compute heuristic, return
return false;
}
generateFluentNodes(state, graph, index);
generateActionNodes(graph, index);
generateGoalNode(graph, index);
return graph;
}
function formatActions(actions) {
formattedActions = [];
Array.from(actions.preconditions.keys()).forEach(action => {
let newAction = { "action": action, "preconditions": [], "effects": [], "value": 0 };
actions.preconditions.get(action).forEach(pcond => {
newAction.preconditions.push(pcond);
});
actions['effects'].get(action).forEach(effect => {
// fluentPreconditions[effect].push(action);
newAction.effects.push(effect);
});
formattedActions.push(newAction);
})
return formattedActions;
}
function generateFluentNodes(state, graph, index) {
// Have to check if this fluent is in the state to initialize (do this after)
fluents.forEach(fluent => {
// fluent.preconditions = fluentPreconditions[fluent.]
if (state.data.strState.includes(fluent)) {
graph.set(fluent, {
'type': 'fluent',
'value': 0,
'index': index,
});
} else {
graph.set(fluent, {
'type': 'fluent',
'value': Number.POSITIVE_INFINITY,
'index': index,
});
}
index += 1;
});
}
function generateActionNodes(graph, index) {
Array.from(actions.keys()).forEach(action => {
actionData = actions.get(action);
graph.set(action, {
'type': 'action',
'value': Number.POSITIVE_INFINITY,
'preconditions': actionData.get('preconditions'),
'effects': actionData.get('effects'),
'index': index
});
index += 1;
});
}
function generateGoalNode(graph, index) {
goalNode = {
'type': 'goal',
'object': 'goal',
'value': Number.POSITIVE_INFINITY,
'preconditions': convertStateToArray(getGoalState()),
'effects': null,
'index': index
}
graph.set('goal', goalNode);
}
function generateHeuristicGraphData(graph) {
var data = { "nodes": [], "links": [] };
// Populating data with fluents
fluents.forEach(fluent => {
data.nodes.push({ "id": fluent, "name": fluent, "type": "fluent", "value": graph.get(fluent).value });
fluentPreconditions[fluent] = [];
});
// Populating data with actions, and links with their respective connections
// based on the actions preconditions and effects.
Array.from(actions.keys()).forEach(action => {
data.nodes.push({ "id": action, "name": action, "type": "action", "value": graph.get(action).value });
actions.get(action).get('preconditions').forEach(pcond => {
if (fluents.has(pcond)) {
data.links.push({ "source": pcond, "target": action });
}
});
actions.get(action).get('effects').forEach(effect => {
if (fluents.has(effect)) {
fluentPreconditions[effect].push(action);
data.links.push({ "source": action, "target": effect });
}
});
});
// Adding goal node
data.nodes.push({ "id": 'goal', "name": 'goal', "type": "goal", "value": graph.get('goal').value });
// Adding goal links
graph.get('goal').preconditions.forEach(goalPrecondtion => {
data.links.push({ "source": goalPrecondtion, "target": 'goal' });
});
return data;
}
// Update node labels to reflect value change
function updateLabels() {
// Updates labels to reflect changes in value
heursvg.selectAll("text").data(heurdata.nodes)
.transition().duration(500)
.text((d) => d.name + " Value: " + graph.get(d.name).value)
.attr('dx', 3)
}
// Launches the heuristic visualizer tab, formats data, and initiates the visualization
function startHeuristicViz(node) {
graph = makeGraph(node);
if (graph == false) {
// Cannot make the heuristic graph, throw err
window.toastr.error("Problem needs to be in STRIPS format for heuristic visualization.");
return;
}
data = generateHeuristicGraphData(graph);
heurdata = data;
// Make a new tab for the viz
window.new_tab('Heuristic Computation', function (editor_name) {
var tmp = '';
tmp += '<div style = "margin:13px 7px;text-align:center">';
tmp += ' <h2>Heuristic Visualization</h2>';
tmp += ' <div class="row">';
tmp += ' <div id="heuristic" class="col-md-9"></div>';
tmp += ' <div id="heuristicbuttons" style="padding:10px" class="col-md-3">';
tmp += ' <button onclick="autoUpdate(graph, true, true)" type="button" class="btn btn-success">Compute</button>';
tmp += ' </div>';
tmp += ' </div>';
tmp += '</div>';
$('#' + editor_name).html(tmp);
svgID = editor_name;
});
// Holds the nodes, the links, and the labels
var node, link, text;
// Set the dimensions and margins of the diagram
// var margin = {top: 20, right: 400, bottom: 30, left: 400},
// width = $('#' + svgID).width() - margin.right - margin.left;
// height = 1000 - margin.top - margin.bottom;
// Set the dimensions and margins of the diagram
var margin = { top: 20, right: 30, bottom: 30, left: 90 };
var width = $('#statespace').width() - margin.left - margin.right;
var height = 700 - margin.top - margin.bottom;
// Init SVG object
heursvg = d3.select('#' + svgID)
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.style("background-color", "white")
.style("margin-left", "30px")
.on("dblclick.zoom", null)
.call(d3.zoom().on("zoom", function () {
heursvg.attr("transform", d3.event.transform)
}))
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Initializing the arrow head for links
heursvg.append('defs')
.append('marker')
.attr('id', 'arrowhead')
.attr('viewBox', '-0 -5 10 10')
.attr('refX', 20)
.attr('refY', 0)
.attr('orient', 'auto')
.attr('markerWidth', 8)
.attr('markerHeight', 14)
.attr('xoverflow', 'visible')
.append('svg:path')
.attr('d', 'M 0,-5 L 10 ,0 L 0,5')
.attr('fill', '#bc5090')
.style('stroke', 'none');
// Initializing the force that gets applied to the network
hSim = d3.forceSimulation(data.nodes) // Force algorithm is applied to data.nodes
.force("link", (d3.forceLink() // This force provides links between nodes
.id(function (d, i) { return d.id; })
.distance(300)
.strength(1) // This provide the id of a node // and this the list of links
))
.force("charge", d3.forceManyBody().strength(-500)) // This adds repulsion between nodes. Play with the -400 for the repulsion strength
.force("center", d3.forceCenter(width / 2, height / 2)) // This force attracts nodes to the center of the svg area
.on("end", ticked);
// Initialize the D3 graph with generated data
link = heursvg.selectAll(".link")
.data(data.links)
.enter()
.append("line")
.attr("class", "link")
.attr("stroke", "#999")
.attr("stroke-width", "1px")
.attr("marker-end", "url(#arrowhead)")
link.append("title").text(d => d.type);
text = heursvg.selectAll("text")
.data(data.nodes)
.enter()
.append("g")
.append("text")
.text((d) => {
return d.name + " Value: " + d.value;
})
.attr('dy', -18)
.attr("text-anchor", "middle");
node = heursvg.selectAll('.node')
.data(data.nodes)
.enter()
.append('g')
.attr('class', 'node')
.attr('fixed', true)
.attr('stroke-width', '2')
.on("dblclick", dclk)
.on("click", clk)
.on("mouseover", highlight)
.on("mouseleave", removeHighlight)
.call(
d3.drag()
.on('start', dragstarted)
.on('drag', dragged)
.on('end', dragended)
);
node.append('circle')
.attr('r', 10)
.style('fill', (d, i) => getColor(d))
node.append('title')
.text((d) => d.id)
hSim
.nodes(data.nodes)
.on('tick', ticked);
hSim.force('link')
.links(data.links);
// This function is run at each iteration of the force algorithm, updating the node, link, and text positions.
function ticked() {
link
.attr("x1", function (d) { return d.source.x; })
.attr("y1", function (d) { return d.source.y; })
.attr("x2", function (d) { return d.target.x; })
.attr("y2", function (d) { return d.target.y; });
node
.attr("transform", (d) => "translate(" + d.x + ", " + d.y + ")");
text
.attr("transform", (d) => "translate(" + d.x + ", " + d.y + ")");
}
function dragstarted(d) {
if (!d3.event.active) hSim.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
d.fixed = false;
}
function dragged(d) {
d.fx = d3.event.x;
d.fy = d3.event.y;
}
function dragended(d) {
d.fixed = true;
}
// Double click
function dclk(d) {
d.fixed = false;
}
// Click
function clk(d) {
// Update node on click
updateHeuristicNode(d);
}
// Returns node color based on type / being the goal node
function getColor(d) {
if (d.name == "goal") {
return "#ffa600";
} else if (d.type == "action") {
return "#ff6361";
} else {
return "#003f5c";
}
}
// Highlights node and all of its predecessors
function highlight(d) {
d3.select(this).style('opacity', 0.9);
node.style("stroke", function (o) {
// d is this
// o is other
if (d.type == "goal") {
if (graph.get('goal').preconditions.includes(o.id) || d.id == o.id) {
// o is precondition
return '#a7440f';
} else {
return 'none';
}
} else if (d.type == "action") {
if (actions.get(d.id).get('preconditions').includes(o.id) || d.id == o.id) {
// o is precondition
return '#a7440f';
} else {
return 'none';
}
} else {
if (fluentPreconditions[d.id].includes(o.id) || d.id == o.id) {
// o is precondition
return '#a7440f';
} else {
return 'none';
}
}
});
node.style("opacity", function (o) {
if (d.type == "goal") {
if (graph.get('goal').preconditions.includes(o.id) || d.id == o.id) {
// o is precondition
return 1;
} else {
return 0.5;
}
} else if (d.type == "action") {
if (actions.get(d.id).get('preconditions').includes(o.id) || d.id == o.id) {
// o is precondition
return 1;
} else {
return 0.5;
}
} else {
if (fluentPreconditions[d.id].includes(o.id) || d.id == o.id) {
// o is precondition
return 1;
} else {
return 0.5;
}
}
});
text.style('opacity', function (o) {
if (d.type == "goal") {
if (graph.get('goal').preconditions.includes(o.id) || d.id == o.id) {
// o is precondition
return 1;
} else {
return 0.5;
}
} else if (d.type == "action") {
if (actions.get(d.id).get('preconditions').includes(o.id) || d.id == o.id) {
// o is precondition
return 1;
} else {
return 0.5;
}
} else {
if (fluentPreconditions[d.id].includes(o.id) || d.id == o.id) {
// o is precondition
return 1;
} else {
return 0.5;
}
}
});
link
.style('stroke', function (o) {
if (o.target.id == d.id) {
return '#69b3b2';
} else {
return '#b8b8b8';
}
})
.style('opacity', function (o) {
if (o.target.id == d.id) {
return 1;
} else {
return 0.5;
}
});
}
// Removes black highlight from nodes and their predecessors
function removeHighlight(d) {