public void Traversal_should_travel_loops_once1() { using (var storage = new GraphStorage()) { long id1, id2; using (var tx = storage.WriteTransaction()) { id1 = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); id2 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); storage.AddEdge(tx, id1, id2); storage.AddEdge(tx, id2, id1); tx.Commit(); } using (var tx = storage.ReadTransaction()) { var results = storage.Traverse() .Execute(id1); results.Should() .HaveCount(2) .And .ContainInOrder(id1, id2); results = storage.Traverse() .Execute(id2); results.Should() .HaveCount(2) .And .ContainInOrder(id2, id1); } } }
/// <summary> Save the current app state as a project </summary> public static void Save() { Project prj = new Project(); prj.data = DataStorage.Create(); prj.graphSettings = GraphStorage.Create(); string path = StandaloneFileBrowser.SaveFilePanel("Save your project", "", "", FileExtension); if (path == "") { return; } string jsonString = JsonUtility.ToJson(prj); try { File.WriteAllText(path, jsonString); } catch (Exception e) { string msg = "Error saving project to file " + path + "\n\n" + e.Message; UIManager.I.ShowMessageDialog(msg); return; } UIManager.I.ShowMessageDialog("Project Saved"); }
public unsafe void Simple_edge_read_write_without_data_should_work() { using (var storage = new GraphStorage()) { long vertexId1, vertexId2, edgeId; using (var tx = storage.WriteTransaction()) { vertexId1 = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); vertexId2 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); edgeId = storage.AddEdge(tx, vertexId1, vertexId2); tx.Commit(); } using (var tx = storage.ReadTransaction()) { Assert.Empty(storage.ReadEdgeData(tx, edgeId)); int size; var data = storage.ReadEdgeData(tx, edgeId, out size); Assert.Equal(0, size); //will return valid ptr, but the size of data chunk is zero Assert.False(null == data); } } }
public void Simple_edge_delete_should_work() { using (var storage = new GraphStorage()) { long vertexId1, vertexId2, edgeId; using (var tx = storage.WriteTransaction()) { vertexId1 = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); vertexId2 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); edgeId = storage.AddEdge(tx, vertexId1, vertexId2, new byte[] { 5, 6, 7, 8 }); tx.Commit(); } using (var tx = storage.ReadTransaction()) { var data = storage.ReadEdgeData(tx, edgeId); Assert.NotNull(data); } using (var tx = storage.WriteTransaction()) { storage.RemoveEdge(tx, edgeId); tx.Commit(); } using (var tx = storage.ReadTransaction()) { var data = storage.ReadEdgeData(tx, edgeId); Assert.Null(data); } } }
public void Traversal_with_DFS_should_handle_loops_properly1() { using (var storage = new GraphStorage()) { long id1, id2, id3; using (var tx = storage.WriteTransaction()) { id1 = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); id2 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); id3 = storage.AddVertex(tx, new byte[] { 1, 1, 1 }); storage.AddEdge(tx, id1, id2); storage.AddEdge(tx, id2, id3); storage.AddEdge(tx, id3, id1); tx.Commit(); } using (var tx = storage.ReadTransaction()) { var results = storage.Traverse() .WithStrategy(Traversal.Strategy.Dfs) .Execute(id1); results.Should() .HaveCount(3) .And .Contain(new[] { id1, id2, id3 }); } } }
public void Traversal_without_limits_should_traverse_all_edges1() { using (var storage = new GraphStorage()) { long id1, id2; using (var tx = storage.WriteTransaction()) { id1 = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); id2 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); storage.AddEdge(tx, id1, id2); tx.Commit(); } using (var tx = storage.ReadTransaction()) { var results = storage.Traverse() .Execute(id1); results.Should() .HaveCount(2) .And .Contain(id1).And.Contain(id2); results = storage.Traverse() .Execute(id2); results.Should() .HaveCount(1) .And .OnlyContain(r => r == id2); } } }
public async Task BFS_FindOne_with_disconnected_root_should_return_null() { var graph = new GraphStorage("TestGraph", Env); Node node2; using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { var node1 = graph.Commands.CreateNode(tx, JsonFromValue("test1")); node2 = graph.Commands.CreateNode(tx, JsonFromValue("test2")); var node3 = graph.Commands.CreateNode(tx, JsonFromValue("test3")); graph.Commands.CreateEdgeBetween(tx, node3, node1); graph.Commands.CreateEdgeBetween(tx, node3, node2); //note: root node is selected by using a first node that was added //since Voron.Graph is a directed graph - no node leads from the root node means nothing //can be found tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var bfs = new BreadthFirstSearch(graph, CancelTokenSource.Token); var node = await bfs.FindOne(tx, data => ValueFromJson<string>(data).Equals("test2")); node.Should().BeNull(); } }
public async Task BFS_FindOne_with_connected_root_should_return_correct_results() { var graph = new GraphStorage("TestGraph", Env); Node node2; using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { var node1 = graph.Commands.CreateNode(tx, JsonFromValue("test1")); node2 = graph.Commands.CreateNode(tx, JsonFromValue("test2")); var node3 = graph.Commands.CreateNode(tx, JsonFromValue("test3")); graph.Commands.CreateEdgeBetween(tx, node3, node1); graph.Commands.CreateEdgeBetween(tx, node3, node2); graph.Commands.CreateEdgeBetween(tx, node2, node2); graph.Commands.CreateEdgeBetween(tx, node1, node3); tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var bfs = new BreadthFirstSearch(graph, CancelTokenSource.Token); var node = await bfs.FindOne(tx, data => ValueFromJson<string>(data).Equals("test2")); node.Should().NotBeNull(); node.Key.Should().Be(node2.Key); } }
public void Simple_shortest_path_with_equal_weights_and_alternative_path () { var graph = new GraphStorage("TestGraph", Env); Node node1, node2, node3,node4,node5; using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { node1 = graph.Commands.CreateNode(tx, JsonFromValue(1)); node2 = graph.Commands.CreateNode(tx, JsonFromValue(1)); node3 = graph.Commands.CreateNode(tx, JsonFromValue(1)); node4 = graph.Commands.CreateNode(tx, JsonFromValue(1)); node5 = graph.Commands.CreateNode(tx, JsonFromValue(1)); node1.ConnectWith(tx, node2, graph); node1.ConnectWith(tx, node3, graph); node2.ConnectWith(tx, node4, graph); node4.ConnectWith(tx, node5, graph); node5.ConnectWith(tx, node3, graph); tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var shortestPathsData = GetAlgorithm(tx, graph, node1).Execute(); var shortestNodePath = shortestPathsData.GetShortestPathToNode(node3).ToList(); shortestNodePath.Should().ContainInOrder(node1.Key, node3.Key); } }
public void Put_edge_between_nodes_in_different_session_should_work() { var graph = new GraphStorage("TestGraph", Env); Node node1, node2, node3; using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { node1 = graph.Commands.CreateNode(tx, JsonFromValue("test1")); node2 = graph.Commands.CreateNode(tx, JsonFromValue("test2")); node3 = graph.Commands.CreateNode(tx, JsonFromValue("test3")); tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { graph.Commands.CreateEdgeBetween(tx, node2, node3); graph.Commands.CreateEdgeBetween(tx, node2, node1); //looping edge also ok! //adding multiple loops will overwrite each other //TODO: add support for multiple edges that have the same keyFrom and keyTo graph.Commands.CreateEdgeBetween(tx, node2, node2); tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var adjacentNodes = graph.Queries.GetAdjacentOf(tx, node2); adjacentNodes.Select(x => x.Key).Should().Contain(new []{ node1.Key, node2.Key, node3.Key}); } }
internal AStarShortestPath(GraphStorage parent, Func <long, long, TableValueReader, double> g, Func <long, TableValueReader, double> h) { _parent = parent; _g = g; _h = h; }
public unsafe void GetAdjacent_should_work() { using (var storage = new GraphStorage()) { long vertexId1, vertexId2, vertexId3, vertexId4, vertexId5; using (var tx = storage.WriteTransaction()) { vertexId1 = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); vertexId2 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); vertexId3 = storage.AddVertex(tx, new byte[] { 4, 5, 6 }); vertexId4 = storage.AddVertex(tx, new byte[] { 7 }); vertexId5 = storage.AddVertex(tx, new byte[] { 8 }); storage.AddEdge(tx, vertexId1, vertexId2); storage.AddEdge(tx, vertexId1, vertexId3); storage.AddEdge(tx, vertexId1, vertexId5); storage.AddEdge(tx, vertexId4, vertexId2); storage.AddEdge(tx, vertexId4, vertexId4); storage.AddEdge(tx, vertexId4, vertexId1); storage.AddEdge(tx, vertexId2, vertexId3); tx.Commit(); } using (var tx = storage.ReadTransaction()) { var adjacentVertices = storage.GetAdjacent(tx, vertexId1).ToList(); adjacentVertices.Should() .HaveCount(3) .And.Contain(new[] { vertexId2, vertexId3, vertexId5 }); adjacentVertices = storage.GetAdjacent(tx, vertexId2).ToList(); adjacentVertices.Should() .HaveCount(1) .And.Contain(new[] { vertexId3 }); adjacentVertices = storage.GetAdjacent(tx, vertexId4).ToList(); adjacentVertices.Should() .HaveCount(3) .And.Contain(new[] { vertexId1, vertexId2, vertexId4 }); } } }
void Update() { if (Input.GetKeyDown("space")) { Debug.Log("pressed space"); GraphStorage storage = gameObject.AddComponent(typeof(GraphStorage)) as GraphStorage; int startTime = Environment.TickCount; mapgrid = storage.Load(); int endTime = Environment.TickCount; Debug.Log(string.Format("Time to load: {0}", endTime - startTime)); Debug.Log(mapgrid); startTime = Environment.TickCount; Cell[,,] graph = mapgrid.createGraph(); endTime = Environment.TickCount; Debug.Log(string.Format("Time to create grid: {0}", endTime - startTime)); Astar astar = new Astar(mapgrid); float[] floatorigin = new float[] { origin[0], origin[1], origin[2] }; float[] floattarget = new float[] { target[0], target[1], target[2] }; startTime = Environment.TickCount; var answer = astar.search(floatorigin, floattarget); endTime = Environment.TickCount; Debug.Log(string.Format("Time to search: {0}", endTime - startTime)); List <Vector3> vectorPath; if (answer == null) { Debug.Log("ASTAR: No valid path"); vectorPath = null; } else { startTime = Environment.TickCount; vectorPath = astar.PathToVectors(); endTime = Environment.TickCount; Debug.Log(string.Format("Time to convert to vector: {0}", endTime - startTime)); } foreach (Vector3 vec in vectorPath) { // Debug.Log(vec.ToString()); GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); cube.transform.localScale = new Vector3(.5f, .5f, .5f); cube.transform.position = vec; cube.GetComponent <Renderer>().material.color = Color.green; } Debug.Log(string.Format("StraightLineRatio: {0}", astar.StraightLineRatio())); } }
public void Traversal_with_min_depth_should_traverse_relevant_edges1_with_DFS() { using (var storage = new GraphStorage()) { long id1, id2, id3, id4, id5; using (var tx = storage.WriteTransaction()) { id1 = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); id2 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); id3 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); id4 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); id5 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); storage.AddEdge(tx, id1, id2); storage.AddEdge(tx, id2, id3); storage.AddEdge(tx, id2, id4); storage.AddEdge(tx, id4, id5); tx.Commit(); } using (var tx = storage.ReadTransaction()) { var results = storage.Traverse() .WithStrategy(Traversal.Strategy.Dfs) .WithMinDepth(1) .Execute(id1); results.Should() .HaveCount(4) .And .Contain(new[] { id2, id3, id4, id5 }); results = storage.Traverse() .WithStrategy(Traversal.Strategy.Dfs) .WithMinDepth(2) .Execute(id1); results.Should() .HaveCount(3) .And .Contain(new[] { id3, id4, id5 }); results = storage.Traverse() //zero-based depth, //4 levels in total .WithStrategy(Traversal.Strategy.Dfs) .WithMinDepth(3) .Execute(id1); results.Should() .HaveCount(1) .And .Contain(id5); } } }
public DijkstraMultiDestinationShortestPath(Transaction tx, GraphStorage graphStorage, Node root, CancellationToken cancelToken) { _rootNode = root; _shortestPathVisitor = new DijkstraMultiDestinationShortestPathVisitor(root, (nodeFrom, nodeTo) => 0, (traversalInfo, adjacentNode) => adjacentNode.EdgeTo.Weight + traversalInfo.TotalEdgeWeightUpToNow); _bfs = new TraversalAlgorithm(tx, graphStorage, root, TraversalType.BFS, cancelToken) { Visitor = _shortestPathVisitor }; }
// Start is called before the first frame update void Start() { numSamples = numBoxes * numBoxes * numBoxes; sample = 0; int percent = numSamples / 100; Debug.Log(percent); int startTime = Environment.TickCount; // bool[,,] collisionMask = new bool[(int)numBoxes, (int)numBoxes, (int)numBoxes]; MapGrid grid = new MapGrid(); float[] startpos = new float[] { startPosition[0], startPosition[1], startPosition[2] }; int[] initsize = new int[] { (int)numBoxes, (int)numBoxes, (int)numBoxes, }; grid.initialize(startpos, initsize, boxSize); for (int x = 0; x < numBoxes; x++) { for (int y = 0; y < numBoxes; y++) { for (int z = 0; z < numBoxes; z++) { Collider[] hitColliders = Physics.OverlapBox(new Vector3(x * boxSize + startPosition[0], y * boxSize + startPosition[1], z * boxSize + startPosition[2]), new Vector3(objectRadius, objectRadius, objectRadius), Quaternion.identity, m_LayerMask); if (hitColliders.Length > 0) { GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); cube.transform.localScale = new Vector3(boxSize, boxSize, boxSize); cube.transform.position = new Vector3(x * boxSize + startPosition[0], y * boxSize + startPosition[1], z * boxSize + startPosition[2]); cube.GetComponent <Renderer>().material.color = Color.red; grid.setMaskItem(x, y, z, false); } else { grid.setMaskItem(x, y, z, true); } sample++; } } } int endTime = Environment.TickCount; Debug.Log(endTime - startTime); GraphStorage storage = gameObject.AddComponent(typeof(GraphStorage)) as GraphStorage; storage.Save(grid); Debug.Log(Application.persistentDataPath); }
public void Traversal_without_edges_should_return_first_vertex() { using (var storage = new GraphStorage()) { long id1, id2; using (var tx = storage.WriteTransaction()) { id1 = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); id2 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); tx.Commit(); } //test both dfs and bfs using (var tx = storage.ReadTransaction()) { var results = storage.Traverse() .WithStrategy(Traversal.Strategy.Bfs) .Execute(id1); results.Should() .HaveCount(1) .And .OnlyContain(r => r == id1); results = storage.Traverse() .Execute(id2); results.Should() .HaveCount(1) .And .OnlyContain(r => r == id2); results = storage.Traverse() .WithStrategy(Traversal.Strategy.Dfs) .Execute(id1); results.Should() .HaveCount(1) .And .OnlyContain(r => r == id1); results = storage.Traverse() .Execute(id2); results.Should() .HaveCount(1) .And .OnlyContain(r => r == id2); } } }
protected BaseSingleDestinationShortestPath(Transaction tx, GraphStorage graphStorage, Node root, Node targetNode, SingleDestinationShortestPathVisitor shortestPathVisitor, TraversalAlgorithm traversal, CancellationToken cancelToken) { _rootNode = root; _targetNode = targetNode; _shortestPathVisitor = shortestPathVisitor; _traversal = traversal; _traversal.Visitor = shortestPathVisitor; }
public EdmondsKarpMaximumFlow(Transaction tx, GraphStorage graphStorage, Node sourceNode, Node targetNode, Func<Edge, long> capacity, CancellationToken? cancelToken = null) : base(capacity) { _sourceNode = sourceNode; _targetNode = targetNode; _storage = graphStorage; _cancelToken = cancelToken; _flow = new Dictionary<Tuple<long, long>, long>(); _tx = tx; }
public void Traversal_with_DFS_and_with_vertex_visitor_should_visit_vertices_once() { using (var storage = new GraphStorage()) { long id1, id2, id3, id4; using (var tx = storage.WriteTransaction()) { id1 = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); id2 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); id3 = storage.AddVertex(tx, new byte[] { 1, 1, 1 }); id4 = storage.AddVertex(tx, new byte[] { 1, 0, 1 }); //create well connected graph storage.AddEdge(tx, id1, id2); storage.AddEdge(tx, id2, id3); storage.AddEdge(tx, id3, id1); storage.AddEdge(tx, id2, id4); storage.AddEdge(tx, id1, id4); storage.AddEdge(tx, id3, id4); storage.AddEdge(tx, id4, id3); tx.Commit(); } using (var tx = storage.ReadTransaction()) { var fetchedData = new List <byte[]>(); var expectedData = new[] { new byte[] { 1, 2, 3 }, new byte[] { 3, 2, 1 }, new byte[] { 1, 1, 1 }, new byte[] { 1, 0, 1 } }; var results = storage.Traverse() .WithStrategy(Traversal.Strategy.Dfs) .Execute(id1, vertexVisitor: reader => { var data = reader.ReadData((int)VertexTableFields.Data); fetchedData.Add(data); }); //DFS has reverse traversal order Assert.Equal(expectedData.Reverse(), fetchedData); } } }
public void Construct() { _graph = new GraphStorage<string, Variable>(); foreach (Variable variable in _storage.Variables) { _graph.AddNode(VariableKey(variable), variable); } foreach (Connection connection in _storage.Connections.Where(conn => conn.Type == ConnectionType.Data)) { string nodeKey = GetConnectionNodeKey(connection.Source, connection.FBType); string connectedNodeKey = GetConnectionNodeKey(connection.Destination, connection.FBType); _graph.AddConnection(nodeKey, connectedNodeKey, k => k == connectedNodeKey); _graph.AddConnection(connectedNodeKey, nodeKey, k => k == nodeKey); } }
public static GraphStorage SetGraphStorage(BlockGraph graph, int walletIdentifier, GraphStateEnum stateGraph) { string hash = GraphCompression.GetUniqueGraphHash(walletIdentifier, graph.CompressedRaw); var storage = new GraphStorage() { StoredHash = hash, CompressedBytes = graph.CompressedRaw, WalletIdentifierOwner = walletIdentifier, StateGraph = stateGraph }; var conn = muxer.GetDatabase(0); conn.StringSet(string.Format("graphs/{0}", hash), JsonConvert.SerializeObject(storage)); return(storage); }
public async Task BFS_FindOne_with_only_root_node_in_graph_returns_correct_results() { var graph = new GraphStorage("TestGraph", Env); using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { graph.Commands.CreateNode(tx, JsonFromValue("test1")); tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var bfs = new BreadthFirstSearch(graph, CancelTokenSource.Token); var node = await bfs.FindOne(tx, data => ValueFromJson<string>(data).Equals("test1")); node.Should().NotBeNull(); } }
public DijkstraShortestPath(Transaction tx, GraphStorage graphStorage, Node root, Node targetNode, CancellationToken cancelToken) : base(tx,graphStorage,root,targetNode, new SingleDestinationShortestPathVisitor(root, targetNode, (nodeFrom, nodeTo) => 0, (traversalInfo, adjacentNode) => adjacentNode.EdgeTo.Weight + traversalInfo.TotalEdgeWeightUpToNow), new TraversalAlgorithm(tx, graphStorage, root, TraversalType.BFS, cancelToken), cancelToken ) { _shortestPathVisitor.IsProcessingQueueEmpty = () => _traversal.ProcessingQueueCount == 0; }
public AStarShortestPath(Transaction tx, GraphStorage graphStorage, Node root, Node targetNode, Func<Node,Node,double> heuristic, CancellationToken cancelToken) :base(tx,graphStorage,root,targetNode, new AStarShortestPathVisitor(root, targetNode, heuristic, (traversalInfo, adjacentNode) => adjacentNode.EdgeTo.Weight + traversalInfo.TotalEdgeWeightUpToNow), new TraversalAlgorithm(tx, graphStorage, root, new PriorityQueueTraversalStore(new TraversalNodeInfoComparer(root, heuristic)), cancelToken), cancelToken) { _shortestPathVisitor.IsProcessingQueueEmpty = () => _traversal.ProcessingQueueCount == 0; }
public void Initialization_should_work() { //create in-memory using (var storage = new GraphStorage()) { } //create persisted var tempPath = Path.GetTempPath() + Path.DirectorySeparatorChar + Guid.NewGuid(); try { using (var storage = new GraphStorage(tempPath)) { } } finally { Directory.Delete(tempPath, true); } }
public void Simple_vertex_delete_should_work() { using (var storage = new GraphStorage()) { long id; using (var tx = storage.WriteTransaction()) { id = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); tx.Commit(); } using (var tx = storage.WriteTransaction()) { storage.RemoveVertex(tx, id); tx.Commit(); } using (var tx = storage.ReadTransaction()) Assert.Null(storage.ReadVertexData(tx, id)); } }
public void Traversal_with_DFS_and_with_edges_visitor_should_visit_vertices_once() { using (var storage = new GraphStorage()) { long id1, id2, id3; using (var tx = storage.WriteTransaction()) { id1 = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); id2 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); id3 = storage.AddVertex(tx, new byte[] { 1, 1, 1 }); storage.AddEdge(tx, id1, id2, new byte[] { 12 }); storage.AddEdge(tx, id2, id3, new byte[] { 23 }); storage.AddEdge(tx, id3, id1, new byte[] { 31 }); tx.Commit(); } using (var tx = storage.ReadTransaction()) { var fetchedData = new List <byte[]>(); var expectedData = new[] { new byte[] { 12 }, new byte[] { 23 }, new byte[] { 31 } }; var results = storage.Traverse() .WithStrategy(Traversal.Strategy.Dfs) .Execute(id1, edgeVisitor: reader => { var data = reader.ReadData((int)EdgeTableFields.Data); fetchedData.Add(data); }); //DFS visits edges in the same manner as BFS, but vertices it visits in reverse Assert.Equal(expectedData, fetchedData); } } }
public void Traversal_with_max_results_should_return_proper_number_of_results() { using (var storage = new GraphStorage()) { long id1, id2, id3; using (var tx = storage.WriteTransaction()) { id1 = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); id2 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); id3 = storage.AddVertex(tx, new byte[] { 1, 1, 1 }); storage.AddEdge(tx, id1, id2); storage.AddEdge(tx, id2, id3); storage.AddEdge(tx, id3, id1); tx.Commit(); } using (var tx = storage.ReadTransaction()) { var results = storage.Traverse() .WithMaxResults(2) .Execute(id1); results.Should() .HaveCount(2) .And .Contain(new[] { id1, id2 }); results = storage.Traverse() .WithMaxResults(2) .Execute(id2); results.Should() .HaveCount(2) .And .Contain(new[] { id2, id3 }); } } }
public void Simple_vertex_read_write_should_work() { using (var storage = new GraphStorage()) { long id1, id2; using (var tx = storage.WriteTransaction()) { id1 = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); id2 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); tx.Commit(); } using (var tx = storage.ReadTransaction()) { var data1 = storage.ReadVertexData(tx, id1); Assert.NotNull(data1); Assert.Equal(new byte[] { 1, 2, 3 }, data1); var data2 = storage.ReadVertexData(tx, id2); Assert.NotNull(data2); Assert.Equal(new byte[] { 3, 2, 1 }, data2); } } }
public void Traversal_with_max_results_lower_than_actual_results_should_have_no_effect() { using (var storage = new GraphStorage()) { long id1, id2, id3; using (var tx = storage.WriteTransaction()) { id1 = storage.AddVertex(tx, new byte[] { 1, 2, 3 }); id2 = storage.AddVertex(tx, new byte[] { 3, 2, 1 }); id3 = storage.AddVertex(tx, new byte[] { 1, 1, 1 }); storage.AddEdge(tx, id1, id2); storage.AddEdge(tx, id2, id3); storage.AddEdge(tx, id3, id1); tx.Commit(); } using (var tx = storage.ReadTransaction()) { var results = storage.Traverse() .WithMaxResults(50) .Execute(id1); results.Should() .HaveCount(3) .And .ContainInOrder(id1, id2, id3); results = storage.Traverse() .Execute(id2); results.Should() .HaveCount(3) .And .ContainInOrder(id2, id3, id1); } } }
private long Create2DepthHierarchy(GraphStorage graph) { long centerNodeKey = 0; using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { var centerNode = graph.Commands.CreateNode(tx, JsonFromValue("centerNode")); centerNodeKey = centerNode.Key; for (var i = 1; i < 6; i++) { var curChild = graph.Commands.CreateNode(tx,JsonFromValue("childNode" + i.ToString())); graph.Commands.CreateEdgeBetween(tx, centerNode, curChild, JsonFromValue(i.ToString())); for (var j = 1; j < 6; j++) { var curGrandChild = graph.Commands.CreateNode(tx, JsonFromValue(string.Concat("grandchild", i.ToString(), "child", i.ToString()))); graph.Commands.CreateEdgeBetween(tx, curChild, curGrandChild,JsonFromValue((i * 10 + j).ToString())); } } tx.Commit(); } return centerNodeKey; }
public BreadthFirstSearch(GraphStorage graphStorage, CancellationToken cancelToken) : base(cancelToken) { _graphStorage = graphStorage; }
public void Edge_predicate_should_filter_edge_types_correctly() { var graph = new GraphStorage("TestGraph", Env); Node node1, node2, node3, node4, node5; using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { node1 = graph.Commands.CreateNode(tx, JsonFromValue("test1")); node2 = graph.Commands.CreateNode(tx, JsonFromValue("test2")); node3 = graph.Commands.CreateNode(tx, JsonFromValue("test3")); node4 = graph.Commands.CreateNode(tx, JsonFromValue("test4")); node5 = graph.Commands.CreateNode(tx, JsonFromValue("test5")); tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { graph.Commands.CreateEdgeBetween(tx, node1, node2,type: 1); graph.Commands.CreateEdgeBetween(tx, node1, node3, type: 2); graph.Commands.CreateEdgeBetween(tx, node1, node4, type: 3); graph.Commands.CreateEdgeBetween(tx, node1, node5, type: 2); tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var adjacentNodes = graph.Queries.GetAdjacentOf(tx, node1, type => type == 2); adjacentNodes.Select(x => x.Node.Key).Should().Contain(new[] { node3.Key, node5.Key }); } }
public void Between_two_equivalent_paths_first_created_should_be_chosen() { var graph = new GraphStorage("TestGraph", Env); Node node1, node2, node3, node4; using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { node1 = graph.Commands.CreateNode(tx, JsonFromValue(1)); node2 = graph.Commands.CreateNode(tx, JsonFromValue(2)); node3 = graph.Commands.CreateNode(tx, JsonFromValue(3)); node4 = graph.Commands.CreateNode(tx, JsonFromValue(4)); node1.ConnectWith(tx, node2, graph, 2); node2.ConnectWith(tx, node4, graph, 1); node1.ConnectWith(tx, node3, graph, 1); node3.ConnectWith(tx, node4, graph, 2); tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var shortestPathsData = GetAlgorithm(tx, graph, node1).Execute(); var shortestNodePath = shortestPathsData.GetShortestPathToNode(node4).ToList(); shortestNodePath.Should().ContainInOrder(node1.Key, node2.Key, node4.Key); } }
public void Simple_shortest_path_with_varying_edge_weight_should_work() { var graph = new GraphStorage("TestGraph", Env); Node node1, node2, node3; using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { node1 = graph.Commands.CreateNode(tx, JsonFromValue(1)); node2 = graph.Commands.CreateNode(tx, JsonFromValue(2)); node3 = graph.Commands.CreateNode(tx, JsonFromValue(3)); node1.ConnectWith(tx, node2, graph, 2); node1.ConnectWith(tx, node3, graph, 10); node2.ConnectWith(tx, node3, graph, 2); tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var shortestPathsData = GetAlgorithm(tx, graph, node1).Execute(); var shortestNodePath = shortestPathsData.GetShortestPathToNode(node3).ToList(); shortestNodePath.Should().ContainInOrder(node1.Key, node2.Key, node3.Key); } }
public void Read_and_writing_system_metadata_should_work() { var graph = new GraphStorage("TestGraph", Env); using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { graph.Commands.PutToSystemMetadata(tx, "Foo", "Bar"); graph.Commands.PutToSystemMetadata(tx, "FooNum", 123); graph.Commands.PutToSystemMetadata(tx, "FooBoolean", false); tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var bar = graph.Queries.GetFromSystemMetadata<string>(tx, "Foo"); var fooNum = graph.Queries.GetFromSystemMetadata<int>(tx, "FooNum"); var fooBoolean = graph.Queries.GetFromSystemMetadata<bool>(tx, "FooBoolean"); Assert.AreEqual("Bar", bar); Assert.AreEqual(123, fooNum); Assert.AreEqual(false, fooBoolean); } }
public static Task<List<Edge>> GetEdges(this Node node, Transaction tx, GraphStorage storage, CancellationToken token) { return storage.AdminQueries.GetEdgesOfNode(tx, node, token); }
public static Edge ConnectWith(this Node node,Transaction tx,Node otherNode, GraphStorage storage,short weight = 1) { return storage.Commands.CreateEdgeBetween(tx,node,otherNode,edgeWeight:weight); }
public void Can_Iterate_On_Nearest_Nodes() { var graph = new GraphStorage("TestGraph", Env); long centerNodeKey = 0; centerNodeKey = Create2DepthHierarchy(graph); using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var centerNode = graph.Queries.LoadNode(tx, centerNodeKey); var nodeValues = new Dictionary<string, string>(); string curEdgeVal; string curNodeVal; foreach (var curNode in graph.Queries.GetAdjacentOf(tx, centerNode)) { var curEdge = graph.Queries.GetEdgesBetween(tx, centerNode, curNode).FirstOrDefault(); Assert.IsNotNull(curEdge); curEdgeVal = curEdge.Data.Value<string>("Value"); curNodeVal = curNode.Data.Value<string>("Value"); nodeValues.Add(curNodeVal, curEdgeVal); } nodeValues.Values.Should().NotContain("grandchild"); Assert.AreEqual(nodeValues.Count, 5); } }
public void No_path_between_nodes_should_result_in_null() { var graph = new GraphStorage("TestGraph", Env); Node node1, node2; using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { node1 = graph.Commands.CreateNode(tx, JsonFromValue(1)); node2 = graph.Commands.CreateNode(tx, JsonFromValue(2)); tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var shortestPathsData = GetAlgorithm(tx, graph, node1).Execute(); var shortestNodePath = shortestPathsData.GetShortestPathToNode(node2); shortestNodePath.Should().BeNull(); } }
public void Get_edges_between_two_nonexisting_nodes_should_return_empty_collection() { var graph = new GraphStorage("TestGraph", Env); using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { var node1 = new Node(-1,JsonFromValue("node1")); var node2 = new Node(-2,JsonFromValue("node2")); var edgesList = graph.Queries.GetEdgesBetween(tx, node1, node2); edgesList.Should().BeEmpty(); } }
protected abstract IMultiDestinationShortestPath GetAlgorithm(Transaction tx, GraphStorage graph, Node rootNode);
public async Task BFS_FindMany_with_connected_root_returns_correct_results() { var graph = new GraphStorage("TestGraph", Env); using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { var node1 = graph.Commands.CreateNode(tx, JsonFromValue("test1")); var node2 = graph.Commands.CreateNode(tx, JsonFromValue("test2")); var node3 = graph.Commands.CreateNode(tx, JsonFromValue("test3")); var node4 = graph.Commands.CreateNode(tx, JsonFromValue("test4")); graph.Commands.CreateEdgeBetween(tx, node3, node1); graph.Commands.CreateEdgeBetween(tx, node3, node2); graph.Commands.CreateEdgeBetween(tx, node3, node4); graph.Commands.CreateEdgeBetween(tx, node2, node2); graph.Commands.CreateEdgeBetween(tx, node2, node4); graph.Commands.CreateEdgeBetween(tx, node1, node3); tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var bfs = new BreadthFirstSearch(graph, CancelTokenSource.Token); var nodes = await bfs.FindMany(tx, data => ValueFromJson<string>(data).Contains("2") || ValueFromJson<string>(data).Contains("4")); nodes.Select(x => ValueFromJson<string>(x.Data)).Should().Contain("test2", "test4"); } }
public void Cheap_long_path_over_short_expensive_path_should_be_chosen() { var graph = new GraphStorage("TestGraph", Env); Node node1, node2, node3, node4; using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { node1 = graph.Commands.CreateNode(tx, JsonFromValue(1)); node2 = graph.Commands.CreateNode(tx, JsonFromValue(2)); node3 = graph.Commands.CreateNode(tx, JsonFromValue(3)); node4 = graph.Commands.CreateNode(tx, JsonFromValue(4)); node1.ConnectWith(tx, node2, graph, 1); node2.ConnectWith(tx, node3, graph, 1); node3.ConnectWith(tx, node4, graph, 1); node1.ConnectWith(tx, node4, graph, 10); tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var shortestPathsData = GetAlgorithm(tx, graph, node1).Execute(); var shortestNodePath = shortestPathsData.GetShortestPathToNode(node4); shortestNodePath.Should().ContainInOrder(node1.Key, node2.Key, node3.Key, node4.Key); } }
public async Task Can_Avoid_Duplicate_Nodes_InParallel_Adds() { var graph = new GraphStorage("TestGraph",Env); Parallel.For(0, 100, i => { using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { graph.Commands.CreateNode(tx, JsonFromValue("newNode" + i)); tx.Commit(); } }); var fetchedKeys = new List<long>(); using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var nodesList = await graph.AdminQueries.GetAllNodes(tx, CancelTokenSource.Token); nodesList.Select(node => node.Key).Should().OnlyHaveUniqueItems(); } }
public void Get_edges_between_existing_and_nonexisting_node_should_return_empty_collection() { var graph = new GraphStorage("TestGraph", Env); long node1Id = 0; using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { var node1 = graph.Commands.CreateNode(tx, JsonFromValue("node1")); Assert.IsNotNull(node1); node1Id = node1.Key; tx.Commit(); } using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { Node node1 = graph.Queries.LoadNode(tx, node1Id); Node node2 = new Node(-2, JsonFromValue("node2")); var edgesList = graph.Queries.GetEdgesBetween(tx, node1, node2); edgesList.Should().BeEmpty(); } }
protected override Algorithms.ShortestPath.ISingleDestinationShortestPath GetAlgorithm(Transaction tx, GraphStorage graph, Node rootNode, Node targetNode) { return new DijkstraShortestPath(tx, graph, rootNode, targetNode, cancelTokenSource.Token); }
public void Load_nonexisting_node_should_return_null() { var graph = new GraphStorage("TestGraph", Env); using (var tx = graph.NewTransaction(TransactionFlags.ReadWrite)) { var illegalNode = graph.Commands.CreateNode(tx,JsonFromValue("onlyNode")); illegalNode.Should().NotBeNull(); } using (var tx = graph.NewTransaction(TransactionFlags.Read)) { var noneExistingNode = graph.Queries.LoadNode(tx, 1); noneExistingNode.Should().BeNull(); } }
Project() { data = null; graphSettings = null; name = DateTime.Now.ToString(); }