1
0
Fork 0
mirror of https://github.com/sbrl/Pepperminty-Wiki.git synced 2024-11-21 16:13:00 +00:00

BkTree: Add graphviz .dot file generation

This commit is contained in:
Starbeamrainbowlabs 2020-03-05 01:20:51 +00:00
parent 593f16dfb9
commit d099be8e16
Signed by: sbrl
GPG key ID: 1BE5172E637709C2
2 changed files with 72 additions and 3 deletions

View file

@ -292,6 +292,40 @@ class BkTree
return $result;
}
public function walk() {
$stack = [ (object)[
"id" => 0,
"node" => $this->box->get("node|0"),
"parent_id" => -1,
"parent" => null,
"depth" => 0
] ];
$stack_top = 0;
// https://softwareengineering.stackexchange.com/a/226162/58491
while(!empty($stack)) {
// Take the topmost node off the stack
$current = $stack[$stack_top];
unset($stack[$stack_top]);
$stack_top--;
// echo("Visiting "); var_dump($current);
yield $current;
// Iterate over the child nodes
foreach($current->node->children as $child_distance => $child_id) {
$stack_top++;
$stack[$stack_top] = (object) [
"id" => $child_id,
"node" => $this->box->get("node|{$current->node->children->$child_distance}"),
"parent_id" => $current->id,
"parent" => $current->node,
"depth" => $current->depth + 1
];
}
}
}
/**
* Saves changes to the tree back to disk.
* @return void

View file

@ -46,6 +46,25 @@ function test_search_linear() {
exit();
}
function writegraph() {
global $tree;
echo("Writing graph to bktree.dot\n");
$handle = fopen("bktree.dot", "w");
fwrite($handle, "// Generated by bktreetest.php by Starbeamrainbowlabs\n");
fwrite($handle, "// Date: ".date("r")."\n");
fwrite($handle, "digraph BkTree {\n");
fwrite($handle, "\tgraph [bgcolor=\"transparent\", nodesep=\"5\", root=\"N0\"];\n");
fwrite($handle, "\tnode [shape=\"point\", color=\"#cb3d38\"];\n");
fwrite($handle, "\tedge [arrowhead=\"open\", gradientangle=\"90\", style=\"filled\", color=\"#fcba2280\"];\n"); // #8cc03280
foreach($tree->walk() as $next) {
if($next->id == 0) continue; // Skip the first node
fwrite($handle, "\tN$next->parent_id -> N$next->id;\n");
}
fwrite($handle, "}\n");
fclose($handle);
}
if(file_exists("bktree.sqlite"))
$tree = time_callable("tree_load");
else
@ -54,8 +73,7 @@ else
echo("Tree created in ".($tree["time"]*1000)."ms\n");
$tree = $tree["value"];
echo("Tree stats: ");
var_dump($tree->stats());
writegraph(); exit();
function test_auto() {
global $tree;
@ -67,7 +85,7 @@ function test_auto() {
exit();
}
test_auto();
// test_auto();
echo("BkTree Test CLI\n");
echo("Exit with .exit\n");
@ -89,6 +107,23 @@ while(true) {
echo("Serialised tree in ".round($result["time"] * 1000, 2)."ms\n");
exit("exit\n");
break;
case ".help":
echo("dot commands:
.exit Exit, saving edits to the tree to disk
.writegraph Write a graphviz dot file to disk representing the tree in the current directory
.stats Compute statistics about the tree
");
break;
case ".writegraph":
writegraph();
break;
case ".stats":
echo("Tree stats: ");
var_dump($tree->stats());
break;
}
continue;
}