Esempio n. 1
0
 public static int distance(bool[,] passable, int startX, int startY, int goalX, int goalY)
 {
     int[,] distanceMatrix = new int[passable.GetLength(0), passable.GetLength(1)];
     for (int i = 0; i < distanceMatrix.GetLength(0); i++)
     {
         for (int j = 0; j < distanceMatrix.GetLength(1); j++)
         {
             distanceMatrix[i, j] = -1;
         }
     }
     distanceMatrix[startX, startY] = 0;
     PriorityQueue<Node> openSet = new PriorityQueue<Node>();
     Node initial = new Node(startX, startY, 0, euclideanDistance(startX, startY, goalX, goalY));
     openSet.Add(initial);
     while (true)
     {
         if (openSet.IsEmpty())
         {
             // we failed to find the goal
             return -1;
         }
         Node current = openSet.PopFront();
         if (current.x == goalX && current.y == goalY)
         {
             // we found it!
             return current.costToGetHere;
         }
         // search all the neighbours
         List<Node> neighbours = current.generateNeighbours(passable, distanceMatrix, goalX, goalY);
         openSet.AddRange(neighbours);
     }
 }
Esempio n. 2
0
        public static SearchResult Search(AbstractNode initialNode, IKnowledgeBase kb)
        {
            var frontier = new PriorityQueue<AbstractNode>();
            var explored = new List<AbstractState>();
            var statesSearched = 0; //Bliver kun brugt af os af ren interesse
            var end = initialNode.Target;
            frontier.Add(initialNode);
            explored.Add(initialNode.State);

            while (frontier.Count > 0)
            {
                // Chooses the lowest-cost node in the frontier
                var currentNode = frontier.Pop();
                statesSearched++;
                if (currentNode.State.Equals(end))
                    return new SearchResult(currentNode, statesSearched, true);

                var actions = kb.ActionsForNode(currentNode);
            //Explore /expand the current node
                foreach (var action in actions)
                {
                    var child = kb.Resolve(currentNode, action, end);
                    //System.Console.WriteLine("Frontier.Count: " + frontier.Count);

                    if (!explored.Contains(child.State) && !frontier.Contains(child))
                    {
                        explored.Add(child.State);
                        frontier.Add(child);

                    }
                    else if(true)
                    {
                        for (int i = 0; i < frontier.Count; i++)
                        {
                            var frontierNode = frontier[i];
                            if (frontierNode.State.Equals(child.State) && frontierNode.PathCost > child.PathCost)
                            {
                                frontier[i] = child;
                                break;
                            }
                        }
                    }
                }
            }

            return new SearchResult(null, statesSearched, false);
        }
Esempio n. 3
0
        public static Path findPath(Node startNode, Node destination)
        {
            List<Node> closedList = new List<Node>();
            PriorityQueue<Node> openList = new PriorityQueue<Node>();

            Dictionary<Node, int> gScore = new Dictionary<Node,int>();
            gScore[startNode] = 0;

            Dictionary<Node, int> fScore = new Dictionary<Node,int>();
            fScore[startNode] = startNode.HeuristicDistance(destination);

            Dictionary<Node, Node> prevNode = new Dictionary<Node, Node>();

            openList.Add(fScore[startNode], startNode);

            while (openList.Count > 0)
            {
                Node current = openList.RemoveMin();
                if (current.Equals(destination))
                {
                    return getPath(prevNode, destination);
                }
                else
                {
                    closedList.Add(current);
                    Node[] neighbours = current.GetNeighbours();
                    foreach (Node next in neighbours)
                    {
                        if (closedList.Contains(next))
                            continue;

                        int newGScore = gScore[current] + current.distanceBetween(next);

                        if (!openList.Contains(next) || newGScore < gScore[next])
                        {
                            prevNode[next] = current;
                            gScore[next] = newGScore;
                            fScore[next] = gScore[next] + next.HeuristicDistance(destination);
                            if (!openList.Contains(next))
                                openList.Add(fScore[next], next);
                        }
                    }
                }
            }

            return null;
        }
Esempio n. 4
0
 public List<Vector2> AStar(Vector2 startPosition, Vector2 targetPosition)
 {
     DNode2 startNode = graph.GetNode(startPosition);
     DNode2 targetNode = graph.GetNode(targetPosition);
     List<Vector2> positions = new List<Vector2>();
     PriorityQueue<DNode2> pq = new PriorityQueue<DNode2>();
     foreach (DNode2 d in graph.adjList.Keys)
     {
         d.Weight = 9999999;
         pq.Add(d);
     }
     startNode.Weight = 0;
     while (!pq.Empty())
     {
         DNode2 n = pq.Remove();
         positions.Add(n.Coords);
         if (n.Coords == targetPosition + new Vector2(80, 80))
         {
             positions.TrimExcess();
             return positions;
         }
         foreach (Edge e in graph.adjList[n])
         {
             DNode2 z = e.GetOpposite(n);
             double r = e.Weight + Vector2.Distance(z.Coords, targetPosition);
             if (r < z.Weight)
             {
                 z.Weight = r;
                 try
                 {
                     pq.Remove(z);
                 }
                 catch (ArgumentException)
                 {
                     continue;
                 }
                 pq.Add(z);
             }
         }
     }
     return positions;
 }
Esempio n. 5
0
        public void AStarSearch(Vector2 sourcePoint, Vector2 destinationPoint, out Vector2 nextNode)
        {
            //Console.WriteLine("Going from (" + sourcePoint.X + ", " + sourcePoint.Y + ") to (" + destinationPoint.X + ", " + destinationPoint.Y + ")");
            Node source = adjacencyList[(int)(columns * sourcePoint.X + sourcePoint.Y)];
            Node destination = adjacencyList[(int)(columns * destinationPoint.X + destinationPoint.Y)];

            PriorityQueue <Node> Q = new PriorityQueue<Node>();
            source.Distance = 0;
            Q.Add(source.Priority, source);

            while (Q.Count > 0)
            {
                Node current = Q.RemoveMin();

                if (current == destination)
                {
                    Node pathParent = current.Parent;
                    Stack<Node> path = new Stack<Node>();
                    path.Push(current);
                    while (pathParent != null)
                    {
                        path.Push(pathParent);
                        pathParent = pathParent.Parent;
                    }

                    Thread t = new Thread(new ParameterizedThreadStart(DrawPath));
                    t.Start(path);

                    path.Pop();
                    nextNode = new Vector2(path.Peek().X * 32, path.Peek().Y * 32);

                    return;
                }

                List<Node> allAdjacent = new List<Node>();
                allAdjacent.AddRange(current.AdjacentNodes);
                allAdjacent.AddRange(current.CornerNodes);
                foreach (Node n in allAdjacent)
                {
                    Node node = adjacencyList[columns * n.X + n.Y];
                    if (node.Distance == int.MaxValue)
                    {
                        node.Distance = current.Distance + 1;
                        node.Parent = current;
                        node.Visited = true;
                        node.Priority = (int)(destinationPoint - sourcePoint).Length() + node.Distance;
                        Q.Add(node.Priority, node);
                    }
                }
            }
            nextNode = new Vector2(-1);
        }
Esempio n. 6
0
        public void AddMax()
        {
            PriorityQueue<int> q = new PriorityQueue<int>((i, j) => j.CompareTo(i));

            q.Storage = new List<int> { 11, 5, 8, 3, 4 };

            q.Add(15);

            Assert.AreEqual(6, q.Storage.Count);
            Assert.AreEqual(15, q.Storage[0]);
            Assert.AreEqual(11, q.Storage[2]);
            Assert.AreEqual(8, q.Storage[5]);
        }
Esempio n. 7
0
        public static int Search(List<State> states, List<Action> actions, State start, Tile target)
        {
            var found = 0;

            PriorityQueue<BFNode> frontier = new PriorityQueue<BFNode>();
            List<State> explored = new List<State>();

            frontier.Add(new BFNode(start));

            while (frontier.Count > 0)
            {
            // Chooses the lowest-cost node in the frontier
            BFNode currentBFNode = frontier.Pop();

            // Win condition
            if (currentBFNode.State.Type.Equals(target))
            found++;

            explored.Add(currentBFNode.State);

            // Filter actions to the ones connected to the current node
            foreach (Action action in actions.Where(a => a.StateA.Equals(currentBFNode.State)))
            {
            // One of A or B will be the currentBFNode's action
            // but it won't be added to the frontier since it
            // is already in explored
            var childA = new BFNode(currentBFNode, action, action.StateA);
            var childB = new BFNode(currentBFNode, action, action.StateB);

            if (!explored.Contains(childA.State) && !frontier.Any(n => n.State == childA.State))
            frontier.Add(childA);

            if (!explored.Contains(childB.State) && !frontier.Any(n => n.State == childB.State))
            frontier.Add(childB);
            }
            }
            return found;
        }
Esempio n. 8
0
        public void AddMin()
        {
            PriorityQueue<int> q = new PriorityQueue<int>((i, j) => i.CompareTo(j));

            q.Storage = new List<int> { 4, 4, 8, 9, 4, 12, 9, 11, 13 };

            q.Add(7);

            Assert.AreEqual(10, q.Storage.Count);
            Assert.AreEqual(7, q.Storage[9]);

            q.Add(10);

            Assert.AreEqual(11, q.Storage.Count);
            Assert.AreEqual(10, q.Storage[10]);

            q.Add(5);

            Assert.AreEqual(12, q.Storage.Count);
            Assert.AreEqual(5, q.Storage[2]);
            Assert.AreEqual(8, q.Storage[5]);
            Assert.AreEqual(12, q.Storage[11]);
        }
Esempio n. 9
0
        public static INode Search(List<State> states, List<Action> actions, State start, State end)
        {
            PriorityQueue<Node> frontier = new PriorityQueue<Node>();
            List<State> explored = new List<State>();

            frontier.Add(new Node(start, end));

            while (frontier.Count > 0)
            {
            // Chooses the lowest-cost node in the frontier
            Node currentNode = frontier.Pop();

            // Win condition
            if (currentNode.State.Equals(end))
            return currentNode;

            // Add currentNode to list of explored
            explored.Add(currentNode.State);

            // Filter actions to the ones connected to the current node
            foreach (Action action in actions.Where(a => a.StateA.Equals(currentNode.State) || a.StateB.Equals(currentNode.State)))
            {
            // One of A or B will be the currentNode's action
            // but it won't be added to the frontier since it
            // is already in explored
            var childA = new Node(currentNode, action, action.StateA, end);
            if (!explored.Contains(childA.State))
            frontier.Add(childA);

            var childB = new Node(currentNode, action, action.StateB, end);
            if (!explored.Contains(childB.State))
            frontier.Add(childB);
            }
            }

            return null;
        }
Esempio n. 10
0
        public IEnumerable <SimpleTreeNode <T> > GetPriorityFirstEnumerable(IComparer <SimpleTreeNode <T> > comparer)
        {
            var queue = new PriorityQueue <SimpleTreeNode <T> >(comparer);

            queue.Add(this);

            while (queue.Count > 0)
            {
                GridSolver.MoveCount++;

                SimpleTreeNode <T> node = queue.Take();

                foreach (SimpleTreeNode <T> child in node.Children)
                {
                    queue.Add(child);
                    if (queue.Count % 1000 == 0)
                    {
                        Log.Debug("Queue size: {QueueSize}", queue.Count);
                    }
                }

                yield return(node);
            }
        }
 public PriorityQueue<Pattern> GetHeap()
 {
     if (subPatternCheck)
     {
         PriorityQueue<Pattern> ret = new PriorityQueue<Pattern>(maxSize);
         foreach (Pattern p in queue)
         {
             if (patternIndex[p.Support].Contains(p))
             {
                 ret.Add(p);
             }
         }
         return ret;
     }
     return queue;
 }
Esempio n. 12
0
        public List<Point> runDijstra()
        {
            foreach (KeyValuePair<Point, List<Point>> pair in adjList)
            {
                dist[pair.Key] = 10000000;
                visited[pair.Key] = false;
                prev[pair.Key] = new Point(-1,-1);
            }
            dist[start] = 0;
            PriorityQueue<dijkstraPoint> queue = new PriorityQueue<dijkstraPoint>();
            queue.Add(new dijkstraPoint(start));
            while (queue.Count>0)
            {
                dijkstraPoint u = queue.Dequeue();
                visited[u.point] = true;

                foreach (Point v in adjList[u.point])
                {
                    int alt = dist[u.point] + (int)Utilities.distance(u.point, v);
                    if (alt < dist[v])
                    {
                        dist[v] = alt;
                        prev[v] = u.point;
                        if (!visited[v])
                            queue.Enqueue(new dijkstraPoint(v));
                    }
                }
            }
            if (dist[dest] == 10000000)
                return null;
            List<Point> path = new List<Point>();
            Point curr = dest;
            while (curr != new Point(-1, -1))
            {
                path.Add(curr);
                curr = prev[curr];
            }
            path.Reverse();
            return path;
        }
        public void TestWithPrimitiveType()
        {
            var priorityQueueInts = new PriorityQueue<int>();

            priorityQueueInts.Add(5);
            priorityQueueInts.Add(10);
            priorityQueueInts.Add(-5);
            priorityQueueInts.Add(1);
            priorityQueueInts.Add(13);
            priorityQueueInts.Add(13);
            priorityQueueInts.Add(0);
            priorityQueueInts.Add(25);

            var numbersActualOrder = new List<int>();

            while (priorityQueueInts.Count > 0)
            {
                numbersActualOrder.Add(priorityQueueInts.RemoveFirst());  
            }

            var numbersExpectedOrder = new List<int>() { -5, 0, 1, 5, 10, 13, 13, 25 };

            CollectionAssert.AreEqual(numbersExpectedOrder, numbersActualOrder);
        }
Esempio n. 14
0
        /// <summary>
        /// For given 'center' point returns a subset of 'm' stored points that are
        /// closer to the center than others.
        /// 
        /// E.g. Stored: (0, 1) (0, 2) (0, 3) (0, 4) (0, 5)
        /// 
        /// Find(new Point(0, 0), 3) -> (0, 1), (0, 2), (0, 3)
        /// 
        /// Seems like we can do this in two ways
        /// 
        ///     Quick select - as we do quick sort on distance from center point,
        ///         stop is pivot index == m, then everything on left is closest m
        ///         complexity will be n log n
        ///     
        ///     Max - Heap - reprocess the points into a max - heap with bounded size of m
        ///         Since everything in heap is smaller than max value, this will also ensure we
        ///         get m closet points. complexity will be n log m
        /// </summary>
        /// <param name="point"></param>
        /// <param name="k"></param>
        public static List<int[]> Find(List<int[]> points, int[] centerPoint, int m)
        {
            PriorityQueue<int[]> maxHeap = new PriorityQueue<int[]>((i, j) =>
                //since this is a max heap, we want to compare j against i
                //and we are comparing distance (sqrt(x^2 + y^2)) from the point
                (System.Math.Pow(j[0] - centerPoint[0], 2) + System.Math.Pow(j[1] - centerPoint[1], 2))
                    .CompareTo(System.Math.Pow(i[0] - centerPoint[0], 2) + System.Math.Pow(i[1] - centerPoint[1], 2))
            );

            foreach(int[] point in points) {
                maxHeap.Add(point);
                if (maxHeap.Storage.Count > m)
                {
                    maxHeap.ExtractRoot();
                }
            }

            List<int[]> result = new List<int[]>();
            while(maxHeap.Storage.Count > 0)
            {
                result.Add(maxHeap.ExtractRoot());
            }
            return result;
        }
        static void Main(string[] args)
        {
            // ------------------- Variable Declarations
            string inputText = ""; // text to be encoded and decoded.

            // ------------------- Input
            Console.Write("Enter a string to be huffman encoded: ");
            inputText = Console.ReadLine();
            Console.WriteLine("The text you entered is: \"{0}\"", inputText);

            // ------------------- Processing
            // Group the characters into a collection of Keys (the characters) and Counts (frequencies)
            var aggregatedCharacters = inputText.GroupBy(character => character).Select(group => new { character = group.Key, frequency = group.Count() });

            // Priority Queue of HuffmanNodes of CharFreqPairs
            var charFreqPriorityQueue = new PriorityQueue<HuffmanNode<CharFreqPair>>(aggregatedCharacters.Count());

            // Add the Character:Frequency pairs to the Priority Queue
            foreach (var aggregatedCharacter in aggregatedCharacters)
                charFreqPriorityQueue.Add(new HuffmanNode<CharFreqPair>(new CharFreqPair(aggregatedCharacter.frequency, aggregatedCharacter.character)));

            // Create HuffmanTree object
            var huffmanTree = new HuffmanTree(charFreqPriorityQueue);

            string testing = huffmanTree.EncodeText(inputText);
            Console.WriteLine("The encoded text is: \"{0}\"", testing);

            testing = huffmanTree.DecodeText(testing);
            Console.WriteLine("The decoded text is: \"{0}\"", testing);

            //huffmanTree.Print();

            // Pause before exiting
            Console.WriteLine("Press return to exit...");
            Console.ReadLine();
        }
        public void TestWithClassHumanImplementsIComparableByAge()
        {
            // Test with class Human implements IComparable (by Age):
            var priorityQueueHumans = new PriorityQueue<Human>();

            priorityQueueHumans.Add(new Human("Ivan", 25));
            priorityQueueHumans.Add(new Human("Georgi", 13));
            priorityQueueHumans.Add(new Human("Cvetelina", 18));
            priorityQueueHumans.Add(new Human("Plamena", 22));
            priorityQueueHumans.Add(new Human("Gergana", 23));
            priorityQueueHumans.Add(new Human("Qna", 21));

            var numbersActualOrder = new List<string>();

            while (priorityQueueHumans.Count > 0)
            {
                numbersActualOrder.Add(priorityQueueHumans.RemoveFirst().Name);
            }

            var numbersExpectedOrder = new List<string>() { "Georgi", "Cvetelina", "Qna", "Plamena", "Gergana", "Ivan" };

            CollectionAssert.AreEqual(numbersExpectedOrder, numbersActualOrder);
        }
Esempio n. 17
0
        private void Update(List<KNNPoint> neighbors,
            VectorDataOptics centerObject, PriorityQueue<VectorDataOptics> orderSeeds)
        {
            var cDist = centerObject.CoreDistance;

            foreach (var obj in neighbors)
            {
                var op = obj.Data as VectorDataOptics;
                if (!op.Visited)
                {
                    var newRDistance = Math.Max(cDist, DistanceFunction
                            .CalculateDistance(op, centerObject));

                    if (double.IsPositiveInfinity(op.ReachabilityDistance))
                    {
                        op.ReachabilityDistance = newRDistance;
                        orderSeeds.Add(op);
                    }
                    else
                    {
                        if (newRDistance < op.ReachabilityDistance)
                        {
                            op.ReachabilityDistance = newRDistance;
                            orderSeeds.Remove(op);
                            orderSeeds.Add(op);
                        }
                    }
                }
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Generates a scheduled search plan for a given search plan graph
        /// </summary>
        public ScheduledSearchPlan ScheduleSearchPlan(SearchPlanGraph spGraph,
            PatternGraph patternGraph, bool isNegativeOrIndependent)
        {
            // the schedule
            List<SearchOperation> operations = new List<SearchOperation>();
            
            // a set of search plan edges representing the currently reachable not yet visited elements
            PriorityQueue<SearchPlanEdge> activeEdges = new PriorityQueue<SearchPlanEdge>();

            // first schedule all preset elements
            foreach(SearchPlanEdge edge in spGraph.Root.OutgoingEdges)
            {
                if(edge.Target.IsPreset && edge.Type != SearchOperationType.DefToBeYieldedTo)
                {
                    foreach(SearchPlanEdge edgeOutgoingFromPresetElement in edge.Target.OutgoingEdges)
                        activeEdges.Add(edgeOutgoingFromPresetElement);

                    // note: here a normal preset is converted into a neg/idpt preset operation if in negative/independent pattern
                    SearchOperation newOp = new SearchOperation(
                        isNegativeOrIndependent ? SearchOperationType.NegIdptPreset : edge.Type,
                        edge.Target, spGraph.Root, 0);
                    operations.Add(newOp);
                }
            }

            // then schedule the initialization of all def to be yielded to elements and variables,
            // must come after the preset elements, as they may be used in the def initialization
            foreach(SearchPlanEdge edge in spGraph.Root.OutgoingEdges)
            {
                if(edge.Type == SearchOperationType.DefToBeYieldedTo
                    && (!isNegativeOrIndependent || (edge.Target.PatternElement.pointOfDefinition == patternGraph && edge.Target.PatternElement.originalElement==null)))
                {
                    SearchOperation newOp = new SearchOperation(
                        SearchOperationType.DefToBeYieldedTo,
                        edge.Target, spGraph.Root, 0);
                    newOp.Expression = edge.Target.PatternElement.Initialization;
                    operations.Add(newOp);
                }
            }
            foreach(PatternVariable var in patternGraph.variablesPlusInlined)
            {
                if(var.defToBeYieldedTo
                    && (!isNegativeOrIndependent || var.pointOfDefinition == patternGraph && var.originalVariable == null))
                {
                    SearchOperation newOp = new SearchOperation(
                        SearchOperationType.DefToBeYieldedTo,
                        var, spGraph.Root, 0);
                    newOp.Expression = var.initialization;
                    operations.Add(newOp);
                }
            }

            // then schedule all map with storage / pick from index / pick from storage / pick from name index elements not depending on other elements
            foreach(SearchPlanEdge edge in spGraph.Root.OutgoingEdges)
            {
                if(edge.Type == SearchOperationType.MapWithStorage)
                {
                    foreach(SearchPlanEdge edgeOutgoingFromPickedElement in edge.Target.OutgoingEdges)
                        activeEdges.Add(edgeOutgoingFromPickedElement);

                    SearchOperation newOp = new SearchOperation(edge.Type,
                        edge.Target, spGraph.Root, 0);
                    newOp.Storage = edge.Target.PatternElement.Storage;
                    newOp.StorageIndex = edge.Target.PatternElement.StorageIndex;
                    operations.Add(newOp);
                }
            }
            foreach(SearchPlanEdge edge in spGraph.Root.OutgoingEdges)
            {
                if(edge.Type == SearchOperationType.PickFromStorage)
                {
                    foreach(SearchPlanEdge edgeOutgoingFromPickedElement in edge.Target.OutgoingEdges)
                        activeEdges.Add(edgeOutgoingFromPickedElement);

                    SearchOperation newOp = new SearchOperation(edge.Type,
                        edge.Target, spGraph.Root, 0);
                    newOp.Storage = edge.Target.PatternElement.Storage;
                    operations.Add(newOp);
                }
            }
            foreach(SearchPlanEdge edge in spGraph.Root.OutgoingEdges)
            {
                if(edge.Type == SearchOperationType.PickFromIndex)
                {
                    foreach(SearchPlanEdge edgeOutgoingFromPickedElement in edge.Target.OutgoingEdges)
                        activeEdges.Add(edgeOutgoingFromPickedElement);

                    SearchOperation newOp = new SearchOperation(edge.Type,
                        edge.Target, spGraph.Root, 0);
                    newOp.IndexAccess = edge.Target.PatternElement.IndexAccess;
                    operations.Add(newOp);
                }
            }
            foreach(SearchPlanEdge edge in spGraph.Root.OutgoingEdges)
            {
                if(edge.Type == SearchOperationType.PickByName)
                {
                    foreach(SearchPlanEdge edgeOutgoingFromPickedElement in edge.Target.OutgoingEdges)
                        activeEdges.Add(edgeOutgoingFromPickedElement);

                    SearchOperation newOp = new SearchOperation(edge.Type,
                        edge.Target, spGraph.Root, 0);
                    newOp.NameLookup = edge.Target.PatternElement.NameLookup;
                    operations.Add(newOp);
                }
            }
            foreach(SearchPlanEdge edge in spGraph.Root.OutgoingEdges)
            {
                if(edge.Type == SearchOperationType.PickByUnique)
                {
                    foreach(SearchPlanEdge edgeOutgoingFromPickedElement in edge.Target.OutgoingEdges)
                        activeEdges.Add(edgeOutgoingFromPickedElement);

                    SearchOperation newOp = new SearchOperation(edge.Type,
                        edge.Target, spGraph.Root, 0);
                    newOp.UniqueLookup = edge.Target.PatternElement.UniqueLookup;
                    operations.Add(newOp);
                }
            }

            // iterate over all reachable elements until the whole graph has been scheduled(/visited),
            // choose next cheapest operation, update the reachable elements and the search plan costs
            SearchPlanNode lastNode = spGraph.Root;
            for(int i = 0; i < spGraph.Nodes.Length - spGraph.NumPresetElements - spGraph.NumIndependentStorageIndexElements; ++i)
            {
                foreach(SearchPlanEdge edge in lastNode.OutgoingEdges)
                {
                    if(edge.Target.IsPreset)
                        continue;
                    if(edge.Target.PatternElement.Storage != null 
                        && edge.Target.PatternElement.GetPatternElementThisElementDependsOnOutsideOfGraphConnectedness()==null)
                        continue;
                    if(edge.Target.PatternElement.IndexAccess != null
                        && edge.Target.PatternElement.GetPatternElementThisElementDependsOnOutsideOfGraphConnectedness()==null)
                        continue;
                    if(edge.Target.PatternElement.NameLookup != null
                        && edge.Target.PatternElement.GetPatternElementThisElementDependsOnOutsideOfGraphConnectedness()==null)
                        continue;
                    if(edge.Target.PatternElement.UniqueLookup != null
                        && edge.Target.PatternElement.GetPatternElementThisElementDependsOnOutsideOfGraphConnectedness()==null)
                        continue;
                    CostDecreaseForLeavingInlinedIndependent(edge);
                    activeEdges.Add(edge);
                }

                SearchPlanEdge minEdge = activeEdges.DequeueFirst();
                lastNode = minEdge.Target;

                SearchOperation newOp = new SearchOperation(minEdge.Type,
                    lastNode, minEdge.Source, minEdge.Cost);
                newOp.Storage = minEdge.Target.PatternElement.Storage;
                newOp.StorageIndex = minEdge.Target.PatternElement.StorageIndex;
                newOp.IndexAccess = minEdge.Target.PatternElement.IndexAccess;
                newOp.NameLookup = minEdge.Target.PatternElement.NameLookup;
                newOp.UniqueLookup = minEdge.Target.PatternElement.UniqueLookup;

                foreach(SearchOperation op in operations)
                    op.CostToEnd += minEdge.Cost;

                operations.Add(newOp);
            }

            // remove the elements stemming from inlined independents
            // they were added in the hope that they might help in matching this pattern,
            // they don't if they are matched after the elements of this pattern (in fact they only increase the costs then)
            RemoveInlinedIndependentElementsAtEnd(operations);

            // insert inlined element identity check into the schedule in case neither of the possible assignments was scheduled
            InsertInlinedElementIdentityCheckIntoSchedule(patternGraph, operations);

            // insert inlined variable assignments into the schedule
            InsertInlinedVariableAssignmentsIntoSchedule(patternGraph, operations);

            // insert conditions into the schedule
            InsertConditionsIntoSchedule(patternGraph.ConditionsPlusInlined, operations);

            float cost = operations.Count > 0 ? operations[0].CostToEnd : 0;
            return new ScheduledSearchPlan(patternGraph, operations.ToArray(), cost);
        }
        /// <summary>
        /// Initializes the simulation and sets all variables to their start state
        /// TODO: find a better way to do this; probably just create a new data object once Model is made
        /// </summary>
        private void InitializeSimulation()
        {
            JobIcon.Opacity = 1;
            JobIcon.Visibility = Visibility.Visible;
            SimClock = 0;
            completedJobs = 0;
            jobQueue = new PriorityQueue<double, Job>();
            jobsDone = 0;
            warmUpValues.Set(false, 0, 0, 0, 0);
            totalJobTime = 0;
            printerJobs = 0;
            totalJobsInSystemArea = 0;
            prevJobsInSystem = 0;
            prevJobsTime = 0;
            jobsInSystem = 0;
            Mac.Data.TotalTimeIdle = 0;
            Mac.Data.TimeIdleAgain = 0;
            Mac.Data.JobQueue.Clear();
            Mac.Data.NumJobs = 0;
            NeXT.Data.TotalTimeIdle = 0;
            NeXT.Data.TimeIdleAgain = 0;
            NeXT.Data.JobQueue.Clear();
            NeXT.Data.NumJobs = 0;
            Printer.Data.TotalTimeIdle = 0;
            Printer.Data.TimeIdleAgain = 0;
            Printer.Data.JobQueue.Clear();
            Printer.Data.NumJobs = 0;
            ExitSystem.Data.JobQueue.Clear();
            ExitSystem.Data.CompletedJobs = 0;
            ResetTimers();

            // Initializations
            Job uG1Job = UserGroup1.Data.GenerateArrival(SimClock);
            jobQueue.Add(new KeyValuePair<double, Job>(uG1Job.ArrivalTime, uG1Job));
            Job uG2Job = UserGroup2.Data.GenerateArrival(SimClock);
            jobQueue.Add(new KeyValuePair<double, Job>(uG2Job.ArrivalTime, uG2Job));
            Job uG3Job = UserGroup3.Data.GenerateArrival(SimClock);
            jobQueue.Add(new KeyValuePair<double, Job>(uG3Job.ArrivalTime, uG3Job));

            initialized = true;
        }
        static void WorkWithPriorityQueue()
        {
            PriorityQueue<int> numbers = new PriorityQueue<int>();
            try
            {
                Console.WriteLine("Count = {0}", numbers.Count());
                //Console.WriteLine(numbers.First());
                //Console.WriteLine(numbers.Last());
                //numbers.Add(10);
               // Print(numbers);
                numbers.Enqueue(1, 5);
                numbers.Enqueue(2, 11);
                numbers.Enqueue(1, 1);
               // Print(numbers);
                numbers.Enqueue(2, 1);
                numbers.Enqueue(3, 1);
                numbers.Enqueue(15, 2);
                numbers.Enqueue(25, 2);
                numbers.Enqueue(21, 2);
              //  Print(numbers);
                numbers.Enqueue(1021, 3);
                numbers.Enqueue(375, 5);
                numbers.Enqueue(124243323, 8);
              //  Print(numbers);
                Console.WriteLine("Count = {0}", numbers.Count());
                Console.WriteLine("Count with priority 1= {0}", numbers.GetCount(1));
                Console.WriteLine("Count with priority 2= {0}", numbers.GetCount(2));
                Console.WriteLine("Count with priority 3= {0}", numbers.GetCount(3));
                Console.WriteLine("Count with priority 4= {0}", numbers.GetCount(4));
                Console.WriteLine("Count with priority 5= {0}", numbers.GetCount(5));
                Console.WriteLine("Count with priority 8= {0}", numbers.GetCount(8));
                Console.WriteLine("Count with priority 11= {0}", numbers.GetCount(11));
                Console.WriteLine(numbers.First());
                Console.WriteLine(numbers.Last());
                Console.WriteLine(numbers.Dequeue());
             //   Print(numbers);
                Console.WriteLine(numbers.Dequeue());
                Console.WriteLine(numbers.Dequeue());
                Console.WriteLine(numbers.Dequeue());
              //  Print(numbers);
                Console.WriteLine(numbers.Dequeue());
                Console.WriteLine(numbers.Dequeue());
                Console.WriteLine(numbers.Dequeue());
             //   Print(numbers);
                Console.WriteLine("Count = {0}", numbers.Count());
                Console.WriteLine("Count with priority 1= {0}", numbers.GetCount(1));
                Console.WriteLine("Count with priority 2= {0}", numbers.GetCount(2));
                Console.WriteLine("Count with priority 3= {0}", numbers.GetCount(3));
                Console.WriteLine("Count with priority 4= {0}", numbers.GetCount(4));
                Console.WriteLine("Count with priority 5= {0}", numbers.GetCount(5));
                Console.WriteLine("Count with priority 8= {0}", numbers.GetCount(8));
                Console.WriteLine("Count with priority 11= {0}", numbers.GetCount(11));
                numbers.Clear();
                Console.WriteLine("Count = {0}", numbers.Count<int>());
             //   Print(numbers);

                numbers.Add(10);
                numbers.Add(11);
                Console.WriteLine(numbers.First());
                Console.WriteLine(numbers.Last());
                Console.WriteLine();
                numbers.Enqueue(1, 5);
                numbers.Add(5);
                Print(numbers);
                Console.WriteLine();
            }
            catch
            {
                Console.WriteLine("Is Exeption");
            }
            Console.ReadKey();
        }
Esempio n. 21
0
        public void AstarRun()
        {
            Console.WriteLine("A* starts!");
            NavigateNode start = new NavigateNode(2, 2, NavigateNode.StateEnum.NAVIGABLE);
            NavigateNode end = new NavigateNode(goalX, goalY, NavigateNode.StateEnum.NAVIGABLE);

            PriorityQueue<NavigateNode> openSet = new PriorityQueue<NavigateNode>();
            PriorityQueue<NavigateNode> closeSet = new PriorityQueue<NavigateNode>();

            openSet.Add(start);

            while (!openSet.Empty) {
                // get from open set
                NavigateNode current = openSet.Pop();

                // add to close set
                closeSet.Add(current);

                // goal found
                if (current.IsSameLocation(end)) {
                    while (current.Parent != null) {
                        mMap[current.X, current.Y].State = NavigateNode.StateEnum.PATH;
                        current = current.Parent;
                    }
                    return;
                }
                else {
                    List<NavigateNode> neighbors = GetNeighbors(current);

                    foreach (NavigateNode n in neighbors) {
                        if (closeSet.IsMember(n)) {
                            continue;
                        }
                        else {
                            if (!openSet.IsMember(n)) {
                                n.Parent = current;
                                n.DirectCost = current.DirectCost + GetDirectCost(current, n);
                                n.HeuristicCost = GetHeuristicCost(n, end);
                                n.TotalCost = n.DirectCost + n.HeuristicCost;

                                // add to open set
                                openSet.Add(n);
                            }
                            else {
                                double costFromThisPathToM = current.DirectCost + GetDirectCost(current, n);
                                // we found a better path
                                if (costFromThisPathToM < n.DirectCost) {
                                    n.Parent = current;                                   // change parent to n
                                    n.DirectCost = costFromThisPathToM;             // recalculate direct cost
                                    n.TotalCost = n.HeuristicCost + n.DirectCost;   // recalculate total cost
                                }
                            }
                        }
                    }
                }
            }

            Console.WriteLine("end here?");
        }
Esempio n. 22
0
 //todo: remove dijkstra from this file, use the one in Utility?  (do I have UpdateDijkstra in Utility?)
 public static PosArray<int> GetDijkstraMap(int height,int width,BooleanLocationDelegate is_blocked,IntLocationDelegate get_cost,List<cell> sources)
 {
     PriorityQueue<cell> frontier = new PriorityQueue<cell>(c => -c.value);
     PosArray<int> map = new PosArray<int>(height,width);
     for(int i=0;i<height;++i){
         for(int j=0;j<width;++j){
             if(is_blocked(i,j)){
                 map[i,j] = U.DijkstraMin;
             }
             else{
                 map[i,j] = U.DijkstraMax;
             }
         }
     }
     foreach(cell c in sources){
         map[c.row,c.col] = c.value;
         frontier.Add(c);
     }
     while(frontier.list.Count > 0){
         cell c = frontier.Pop();
         for(int s=-1;s<=1;++s){
             for(int t=-1;t<=1;++t){
                 if(c.row+s >= 0 && c.row+s < height && c.col+t >= 0 && c.col+t < width){
                     int cost = get_cost(c.row+s,c.col+t);
                     if(map[c.row+s,c.col+t] > c.value+cost){
                         map[c.row+s,c.col+t] = c.value+cost;
                         frontier.Add(new cell(c.row+s,c.col+t,c.value+cost));
                     }
                 }
             }
         }
     }
     for(int i=0;i<height;++i){
         for(int j=0;j<width;++j){
             if(map[i,j] == U.DijkstraMax){
                 map[i,j] = U.DijkstraMin; //any unreachable areas are marked unpassable
             }
         }
     }
     return map;
 }
Esempio n. 23
0
 public static void UpdateDijkstraMap(PosArray<int> map,IntLocationDelegate get_cost)
 {
     PriorityQueue<cell> frontier = new PriorityQueue<cell>(c => -c.value);
     int height = map.objs.GetLength(0);
     int width = map.objs.GetLength(1);
     for(int i=0;i<height;++i){
         for(int j=0;j<width;++j){
             if(map[i,j] != U.DijkstraMin){
                 int v = map[i,j];
                 bool good = true;
                 for(int s=-1;s<=1 && good;++s){
                     for(int t=-1;t<=1 && good;++t){
                         if(i+s >= 0 && i+s < height && j+t >= 0 && j+t < width){
                             if(map[i+s,j+t] < v && map[i+s,j+t] != U.DijkstraMin){
                                 good = false;
                             }
                         }
                     }
                 }
                 if(good){ //find local minima and add them to the frontier
                     frontier.Add(new cell(i,j,v));
                 }
             }
         }
     }
     while(frontier.list.Count > 0){
         cell c = frontier.Pop();
         for(int s=-1;s<=1;++s){
             for(int t=-1;t<=1;++t){
                 if(c.row+s >= 0 && c.row+s < height && c.col+t >= 0 && c.col+t < width){
                     int cost = get_cost(c.row+s,c.col+t);
                     if(map[c.row+s,c.col+t] > c.value+cost){
                         map[c.row+s,c.col+t] = c.value+cost;
                         frontier.Add(new cell(c.row+s,c.col+t,c.value+cost));
                     }
                 }
             }
         }
     }
 }
        /// <summary>
        ///       ----------------
        ///       - A* Algorithm -
        ///       ----------------
        ///       
        /// OPEN = priority queue contain START
        /// CLOSED = empty set
        /// 
        /// while lowest rank in OPEN is not the GOAL:
        ///     current = remove lowest rank item from OPEN
        ///     add current to CLOSED
        ///     
        ///     for neighbors of current
        ///         cost = g(current) + movement_cost(current, neighbor)
        ///         
        ///         if neighbor in OPEN and cost less than g(neighbor)
        ///             remove neighbor from OPEN, because new path is better
        ///             
        ///         if neighbor in CLOSED and cost less than g(neighbor)
        ///             remove neighbor from CLOSED
        ///             
        ///         if neighbor not in OPEN and neighbor not in CLOSED
        ///             set g(neighbor) to cost
        ///             add neighbor to OPEN
        ///             set priority queue rank to g(neighbor) + h(neighbor)
        ///             set neighbor's parent to current
        ///             
        /// 
        /// reconstruct reverse path from goal to start
        /// by following parent pointers
        ///  
        /// </summary>
        /// <param name="startPostion">start</param>
        /// <param name="goalPosition">destination</param>
        /// <param name="nodeType">color of node</param>
        /// <returns></returns>
        private List<NavNode> MakeAStarPath(Vector3 startPostion, Vector3 goalPosition, NavNode.NavNodeEnum nodeType)
        {
            /**
             * A* implementation
             *      Summary:
             *              1) Add the starting node to the open set
             *              2) Repeat the following:
             *                      a) Look for the lowest F cost on the open set.
             *                      b) Move it to the closed set
             *                      c) For each of the 8 adjacency node to the current node:
             *                              + If it is NOT walkable or if it is on the CLOSED SET, just ignore it.
             *                              + Otherwise:
             *                                  - If it is NOT on the OPEN SET, add it to the OPEN SET. Make the "current node" as
             *                                    parent of this adjacency node. Record F, G, H for this node.
             *                                  - If it is on the OPEN SET already, check to see if this path to that square is
             *                                    better using G cost as the measure. A lower G means that this is a better path.
             *                                    If so, change the parent of the node to the "current node", and recalculate
             *                                    the G and F cost of the node.
             *                      d) Stop when we:
             *                              + Add the goal node to the closed set, in which case the path has been found.
             *                              + Fail to find the goal node, and the open set is empty. In this case, there is NO path.
             */
            // spacing between node on map (= 150)
            int spacing = stage.Terrain.Spacing;

            /**
             * A* path
             *      this is our final path
             */
            List<NavNode> path = new List<NavNode>();

            /**
             * The starting point
             */
            NavNode start = new NavNode(startPostion);
            start.DistanceFromSource = 0.0;
            start.DistanceToGoal = 0.0;
            start.Distance = 0.0;
            start.Parent = null;

            /**
             * The goal
             */
            NavNode goal = new NavNode(goalPosition);
            goal.DistanceFromSource = 0.0;
            goal.DistanceToGoal = 0.0;
            goal.Distance = 0.0;
            goal.Parent = null;

            // open set
            PriorityQueue<NavNode> openSet = new PriorityQueue<NavNode>();

            // close set
            PriorityQueue<NavNode> closedSet = new PriorityQueue<NavNode>();

            // add starting point to open set (part 1)
            openSet.Add(start);

            while (!openSet.Empty) {

                // get the current node with lowest cost F and remove it from open set
                NavNode current = openSet.Pop();

                // add current to close set
                closedSet.Add(current);

                // if it's equal to our goal, we're done (part d)
                if (current.IsSameLocation(goal)) {
                    while (current.Parent != null) {
                        path.Add(current);
                        current.Navigatable = nodeType;
                        current = current.Parent;
                    }
                    path.Reverse();
                    return path;
                }
                else {
                    // for each of the 8 adjacency neighbors
                    // NOTE: the neighbor list already removed un-walkable nodes
                    List<NavNode> neighbors = GetNeighbors(current.Translation);

                    foreach (NavNode n in neighbors) {
                        // if it's on the closed set, just ignore it
                        if (IsNodeIn(n, closedSet)) {
                            continue;
                        }
                        else {
                            if (!IsNodeIn(n, openSet)) {
                                // make the "current node" as parent of this neighbor
                                n.Parent = current;
                                // record new F, G, H
                                n.DistanceFromSource = current.DistanceFromSource + CalculateDistanceFromSource(current, n);
                                n.DistanceToGoal = CalculateHeuristicDinstanceToGoal(n, goal);
                                n.Distance = n.DistanceFromSource + n.DistanceToGoal;

                                // add this neighbor to the OPEN SET
                                openSet.Add(n);
                            }
                            else { // it's already on the OPEN SET
                                double costFromThisPathToN = current.DistanceFromSource + CalculateDistanceFromSource(current, n);
                                // we have a better path, going from "current node"
                                if (costFromThisPathToN < n.DistanceFromSource) {
                                    // recalculate G and F for this neighbor
                                    n.Parent = current;
                                    n.DistanceFromSource = costFromThisPathToN;
                                    n.Distance = n.DistanceFromSource + n.DistanceToGoal;
                                }
                            }
                        }
                    }
                }
            }

            return path;
        }
Esempio n. 25
0
        public void PriorityQueueRandomAddElementsDequeueReturnsInPriorityOrder()
        {
            const int testSize = 500;
            const int testTimes = 5;
            var r = new Random(AnyInt);

            for (var t = 0; t < testTimes; t++)
            {
                var q = new PriorityQueue<int>();
                var testArr = new int[testSize];
                for (var i = 0; i < testSize; i++)
                {
                    var num = r.Next();
                    testArr[i] = num;
                    q.Add(num);
                }
                
                Array.Sort(testArr);
                for (var i = 0; i < testSize; i++)
                {
                    Assert.Equal(testSize - i, q.Count);
                    Assert.Equal(testArr[i], q.Dequeue());
                }

                Assert.Equal(q.Count, 0);
            }
        }
Esempio n. 26
0
        public void PriorityQueueRandomAddDequeueInterweave()
        {
            const int addSize = 500;
            const int testTimes = 5;
            var r = new Random(AnyInt);

            for (var t = 0; t < testTimes; t++)
            {
                var q = new PriorityQueue<int>();
                var testList = new List<int>();
                for (var i = 0; i < addSize; i++)
                {
                    var num = r.Next();
                    testList.Add(num);
                    q.Add(num);

                    var shouldRemove = r.Next(0, 10) >= 5;
                    if (shouldRemove)
                    {
                        var removed = q.Dequeue();
                        Assert.Equal(testList.Min(), removed);
                        testList.Remove(removed);
                    }
                }

                testList.Sort();

                var testListSize = testList.Count;
                Assert.Equal(testListSize, q.Count);

                for (var i = 0; i < testListSize; i++)
                {
                    Assert.Equal(testListSize - i, q.Count);
                    Assert.Equal(testList[i], q.Dequeue());
                }

                Assert.Equal(q.Count, 0);
            }
        }
Esempio n. 27
0
        int[,] WaterShed(int[,] image)
        {
            int[,] watershedLine = new int[InputImage.Size.Width, InputImage.Size.Height];
            int[,] localMinima = new int[InputImage.Size.Width, InputImage.Size.Height];
            int[,] erosion = Erosion(image, 5);
            for (int y = InputImage.Size.Height - 1; y >= 0; y--)
            {
                for (int x = InputImage.Size.Width - 1; x >= 0; x--)
                {
                    bool lower = false;
                    for (int sx = -1; sx <= 1; sx++)
                    {
                        for (int sy = -1; sy <= 1; sy++)
                        {
                            if (x + sx > 0 && x + sx < image.GetLength(0) && y + sy > 0 && y + sy < image.GetLength(1) && image[x, y] < image[sx + x, sy + y])
                            {
                                lower = true;
                            }
                        }

                        if (erosion[x, y] == image[x, y] && lower)
                        {
                            localMinima[x, y] = 255;
                        }
                    }
                }
            }

            int[,] labeledMinima = FindObjects(localMinima);

            PriorityQueue q = new PriorityQueue();
            for (int y = InputImage.Size.Height - 1; y >= 0; y--)
            {
                for (int x = InputImage.Size.Width - 1; x >= 0; x--)
                {
                    if (labeledMinima[x, y] > 0)
                        q.Add(x, y, image[x, y], labeledMinima[x, y]);
                }
            }

            Tuple<int, int, int, int> min = q.ExtractMin();
            
            while(min!= null)
            {
                int x = min.Item1;
                int y = min.Item2;

                for (int sx = -1; sx <= 1; sx++)
                {
                    for (int sy = -1; sy <= 1; sy++)
                    {
                        if (x + sx > 0 && x + sx < image.GetLength(0) && y + sy > 0 && y + sy < image.GetLength(1))
                        {
                            if(labeledMinima[x+sx,y+sy] == 0 && image[x+sx,y+sy] != 255)
                            {
                                labeledMinima[x + sx, y + sy] = min.Item4;
                                q.Add(x + sx,y + sy,image[x,y],labeledMinima[x,y]);
                            }
                            else
                            {
                                if (labeledMinima[x + sx, y + sy] != labeledMinima[x, y] && labeledMinima[x+sx,y+sy] != 0)
                                    watershedLine[x + sx, y + sy] = 255;
                            }
                        }
                    }
                }
                min = q.ExtractMin();
            }
            
            return watershedLine;
        }