1.2 Build a graph from objects of your own
You give your objects node IDs, keep an array to find each object again, and handle input that is numbered elsewhere.
Problem
Section titled “Problem”Your program has objects that refer to each other, and you want to analyze these references as a graph. Graphity’s nodes are numbers, not objects. So you need three things: a numbering of your objects, a way back from a number to its object, and an edge for each reference. Such objects are found in:
- a model of a program, with classes and the classes they use;
- a plan, with tasks and the tasks they wait for;
- an organization, with people and the people they report to.
Example
Section titled “Example”A small program describes its packages as objects of a type Package, each with its name and the
names of the packages it uses:
// The packages of a program as objects.List<Package> packages = List.of( new Package("app", List.of("cli", "ui", "service")), new Package("cli", List.of("util")), new Package("ui", List.of("service", "model", "util")), new Package("service", List.of("model", "storage")), new Package("model", List.of("storage")), new Package("storage", List.of("model", "json", "util")), new Package("json", List.of("util")), new Package("util", List.of()));// The packages of a program as objects.let packages = vec![ Package::new("app", &["cli", "ui", "service"]), Package::new("cli", &["util"]), Package::new("ui", &["service", "model", "util"]), Package::new("service", &["model", "storage"]), Package::new("model", &["storage"]), Package::new("storage", &["model", "json", "util"]), Package::new("json", &["util"]), Package::new("util", &[]),];// The packages of a program as objects.const packages: readonly Package[] = [ new Package("app", ["cli", "ui", "service"]), new Package("cli", ["util"]), new Package("ui", ["service", "model", "util"]), new Package("service", ["model", "storage"]), new Package("model", ["storage"]), new Package("storage", ["model", "json", "util"]), new Package("json", ["util"]), new Package("util", [])];// The packages of a program as objects.List<Package> packages =[ new Package("app", ["cli", "ui", "service"]), new Package("cli", ["util"]), new Package("ui", ["service", "model", "util"]), new Package("service", ["model", "storage"]), new Package("model", ["storage"]), new Package("storage", ["model", "json", "util"]), new Package("json", ["util"]), new Package("util", []),];The example graph models the dependencies between these packages. It has an edge from each package to each package it uses. Which node ID does each package get, and how does a node ID lead back to its package? Each package gets its position in the list:
Solution
Section titled “Solution”Number the objects in the order of the list, keep each object in an array at its node ID, and look up the node ID of each reference by name:
// Give each package a node ID, its position in the list, and keep the package of each// node ID in an array. A map from name to int, from the fastutil library that// Graphity uses, avoids boxing the node IDs; an unknown name gives -1, which the// builder rejects.Package[] packageOf = packages.toArray(new Package[0]);Object2IntMap<String> nodeOf = new Object2IntOpenHashMap<>();nodeOf.defaultReturnValue(-1);for (int node = 0; node < packageOf.length; node++) { nodeOf.put(packageOf[node].name(), node);}
// Add an edge for each package another package uses.var builder = new GraphBuilder();builder.addNodes(packages.size());for (Package p : packages) { for (String used : p.uses()) { builder.addEdge(nodeOf.getInt(p.name()), nodeOf.getInt(used)); }}Graph dependencies = builder.build();String usedByApp = packageOf[dependencies.outNodes(0).getInt(1)].name(); // ui// Give each package a node ID, its position in the list, so that the list, as// package_of, leads from a node ID to its package. A HashMap from name to node ID// leads back; indexing it with an unknown name panics, so a wrong reference fails// at once.let package_of: &[Package] = &packages;let mut node_of = HashMap::new();for (node, package) in package_of.iter().enumerate() { node_of.insert(package.name.as_str(), node as u32);}
// Add an edge for each package another package uses.let mut builder = GraphBuilder::new();builder.add_nodes(packages.len() as u32);for p in &packages { for used in &p.uses { builder.add_edge(node_of[p.name.as_str()], node_of[used.as_str()]); }}let dependencies = builder.build();let used_by_app = &package_of[dependencies.out_nodes(0)[1] as usize].name; // "ui"// Give each package a node ID, its position in the list, and keep the package of each// node ID in an array. A Map from name to node ID finds the node ID of a name; an// unknown name gives -1, which the builder rejects.const packageOf: Package[] = [...packages];const nodeOf = new Map<string, number>();for (let node = 0; node < packageOf.length; node++) { nodeOf.set(packageOf[node].name, node);}
// Add an edge for each package another package uses.const builder = new GraphBuilder();builder.addNodes(packages.length);for (const p of packages) { for (const used of p.uses) { builder.addEdge(nodeOf.get(p.name) ?? -1, nodeOf.get(used) ?? -1); }}const dependencies = builder.build();const usedByApp = packageOf[dependencies.outNodes(0).get(1)].name; // ui// Give each package a node ID, its position in the list, and keep the package of// each node ID in an array. A dictionary from name to node ID finds the node ID// of each name; read with GetValueOrDefault, an unknown name gives -1, which the// builder rejects.Package[] packageOf = [.. packages];var nodeOf = new Dictionary<string, int>();for (int node = 0; node < packageOf.Length; node++){ nodeOf[packageOf[node].Name] = node;}
// Add an edge for each package another package uses.var builder = new GraphBuilder();builder.AddNodes(packages.Count);foreach (Package p in packages){ foreach (string used in p.Uses) { builder.AddEdge(nodeOf[p.Name], nodeOf.GetValueOrDefault(used, -1)); }}Graph dependencies = builder.Build();string usedByApp = packageOf[dependencies.OutNodes(0)[1]].Name; // uiThe result is the graph of the picture. A list of edges gives the same graph. See
Build a graph from a list of edges. The array
packageOfpackage_ofpackageOfpackageOf leads from a node
ID back to its object. It is the first column of a table of node data: every further piece of data
about the packages can be another array of the same length. The last line of the code goes both
ways: from the node ID of app to its out-nodes with
Graph.outNodesGraph::out_nodesGraph.outNodesGraph.OutNodes, and from the second out-node back to its object, which is ui.
The node IDs may come from elsewhere, numbered in a database or in a file. Then you may not know
how many nodes there are. The methods whose names end in
AndNodes_and_nodesAndNodesAndNodes add the nodes up to
the highest node ID they see:
// Edges between nodes numbered elsewhere, for example by a database: no node count// needed.int[] endpoints = {0, 3, 3, 4, 4, 0, 7, 3}; // 0 -> 3, 3 -> 4, 4 -> 0, 7 -> 3var builder = new GraphBuilder();builder.addEdgePairsAndNodes(endpoints);Graph graph = builder.build();// 8 - the nodes 0 to 7; 1, 2, 5 and 6 have no edgesint nodeCount = graph.nodeCount();// Edges between nodes numbered elsewhere, for example by a database: no node count// needed.let endpoints = [0, 3, 3, 4, 4, 0, 7, 3]; // 0 -> 3, 3 -> 4, 4 -> 0, 7 -> 3let mut builder = GraphBuilder::new();builder.add_edge_pairs_and_nodes(&endpoints);let graph = builder.build();// 8 - the nodes 0 to 7; 1, 2, 5 and 6 have no edgeslet node_count = graph.node_count();// Edges between nodes numbered elsewhere, for example by a database: no node count// needed.const endpoints = [0, 3, 3, 4, 4, 0, 7, 3]; // 0 -> 3, 3 -> 4, 4 -> 0, 7 -> 3const builder = new GraphBuilder();builder.addEdgePairsAndNodes(endpoints);const graph = builder.build();// 8 - the nodes 0 to 7; 1, 2, 5 and 6 have no edgesconst nodeCount = graph.nodeCount;// Edges between nodes numbered elsewhere, for example by a database: no node// count needed.int[] endpoints = [0, 3, 3, 4, 4, 0, 7, 3]; // 0 -> 3, 3 -> 4, 4 -> 0, 7 -> 3var builder = new GraphBuilder();builder.AddEdgePairsAndNodes(endpoints);Graph graph = builder.Build();// 8 - the nodes 0 to 7; 1, 2, 5 and 6 have no edgesint nodeCount = graph.NodeCount;The graph has 8 nodes. The nodes 0, 3, 4 and 7 have the four edges. The nodes 1, 2, 5 and 6 have no edges and fill the gaps between them.
Good to know
Section titled “Good to know”- A wrong node ID. Without
AndNodes_and_nodesAndNodesAndNodes, the builder rejects an edge to a node that has not been added, so a wrong node ID fails at once. With it, a node ID that is too high adds nodes instead. Use the plain methods when the node count is known. A wrong reference also fails at once if your map lookup gives-1NONE-1-1for a key it does not know, or fails for it. - Single edges and pairs.
GraphBuilder.addEdgeAndNodesGraphBuilder::add_edge_and_nodesGraphBuilder.addEdgeAndNodesGraphBuilder.AddEdgeAndNodesadds one edge and its missing nodes.GraphBuilder.addEdgePairsGraphBuilder::add_edge_pairsGraphBuilder.addEdgePairsGraphBuilder.AddEdgePairstakes the source and target of each edge in turn from one array. Data from a file often comes this way. - Keys other than names work the same way. You can use any map from your key to the node ID, or a field in your object that holds its node ID once it has one.
API used
Section titled “API used”GraphBuilder()GraphBuilder::newnew GraphBuildernew GraphBuilderGraphBuilder.addNodes(int)GraphBuilder::add_nodesGraphBuilder.addNodesGraphBuilder.AddNodesGraphBuilder.addEdge(int, int)GraphBuilder::add_edgeGraphBuilder.addEdgeGraphBuilder.AddEdgeGraphBuilder.build()GraphBuilder::buildGraphBuilder.buildGraphBuilder.BuildGraph.outNodes(int)Graph::out_nodesGraph.outNodesGraph.OutNodesSortedIntView.getInt(int)SortedIntView.getInt(int)SortedIntView.getSortedIntView.this[int]GraphBuilder.addEdgeAndNodes(int, int)GraphBuilder::add_edge_and_nodesGraphBuilder.addEdgeAndNodesGraphBuilder.AddEdgeAndNodesGraphBuilder.addEdgePairs(int...)GraphBuilder::add_edge_pairsGraphBuilder.addEdgePairsGraphBuilder.AddEdgePairsGraphBuilder.addEdgePairsAndNodes(int...)GraphBuilder::add_edge_pairs_and_nodesGraphBuilder.addEdgePairsAndNodesGraphBuilder.AddEdgePairsAndNodes