示例#1
0
        private void ExpandClusterOrder(List <ClusterOrderEntry <T> > clusterOrder, HashSet <T> processed, T dataObject)
        {
            var priorityQueue = new PriorityQueue <double, T>();

            priorityQueue.Enqueue(double.PositiveInfinity, dataObject);
            while (!priorityQueue.IsEmpty)
            {
                PriorityQueueNode <double, T> node = priorityQueue.Dequeue();
                double reachability = node.Priority;
                T      current      = node.Item;
                processed.Add(current);

                List <Tuple <T, double> > neighbors = _getNeighbors(current).OrderBy(n => n.Item2).ToList();
                double coreDistance = double.PositiveInfinity;
                if (neighbors.Count >= _minPoints)
                {
                    coreDistance = neighbors[_minPoints - 1].Item2;
                    foreach (Tuple <T, double> neighbor in neighbors)
                    {
                        if (!processed.Contains(neighbor.Item1))
                        {
                            priorityQueue.Enqueue(Math.Max(neighbor.Item2, coreDistance), neighbor.Item1);
                        }
                    }
                }

                clusterOrder.Add(new ClusterOrderEntry <T>(current, reachability, coreDistance));
            }
        }
示例#2
0
        // Swaps the nodes at the given indexes.
        private void Swap(int index1, int index2)
        {
            PriorityQueueNode temp = m_heap[index1];

            m_heap[index1] = m_heap[index2];
            m_heap[index2] = temp;
        }
        private void Swap(int i, int j)
        {
            PriorityQueueNode temp = _heap[i];

            _heap[i] = _heap[j];
            _heap[j] = temp;
        }
示例#4
0
        /// <summary>
        /// Enqueue work item.
        /// </summary>
        /// <remarks>
        /// Enqueuing is O(n), but since we re-enqueue the oldest originating time many times as it is processed by the pipeline,
        /// the dominant operation is to enqueue at the beginning of the queue
        /// </remarks>
        /// <param name="workitem">Work item to enqueue.</param>
        public void Enqueue(T workitem)
        {
            // reset the empty signal as needed
            if (this.count == 0)
            {
                this.empty.Reset();
            }

            // take the head of the empty list
            int retries = this.emptyHead.Lock();
            var newNode = this.emptyHead.Next;

            if (newNode != null)
            {
                this.emptyHead.Next = newNode.Next;
            }
            else
            {
                newNode = new PriorityQueueNode(Interlocked.Increment(ref this.nextId));
            }

            this.emptyHead.Release();

            newNode.Workitem = workitem;

            // insert it in the right place
            retries += this.Enqueue(newNode);
            this.counters?.Increment(PriorityQueueCounters.EnqueueingCount);
            this.counters?.Increment(PriorityQueueCounters.WorkitemCount);
            this.counters?.IncrementBy(PriorityQueueCounters.EnqueueingRetries, retries);
        }
示例#5
0
        private int Enqueue(PriorityQueueNode node)
        {
            // we'll insert the node between "previous" and "next"
            var previous = this.head;
            int retries  = previous.Lock();
            var next     = this.head.Next;

            while (next != null && this.comparer(node.Workitem, next.Workitem) > 0)
            {
                retries += next.Lock();
                previous.Release();
                previous = next;
                next     = previous.Next;
            }

            node.Next     = previous.Next;
            previous.Next = node;

            // increment the count and signal the empty queue if needed, before releasing the previous node
            // If we didn't and this was a 0-1 transition of this.count, another thread could dequeue and go to -1,
            // we would still bring it back to 0, but we would miss signaling the empty queue.
            if (Interlocked.Increment(ref this.count) == 1)
            {
                this.empty.Reset();
            }

            previous.Release();
            return(retries);
        }
示例#6
0
        public void TestContains()
        {
            PriorityQueueNode node1 = new PriorityQueueNode();
            PriorityQueueNode node2 = new PriorityQueueNode();
            PriorityQueueNode node3 = new PriorityQueueNode();
            int priority1           = this.RandomValue();
            int priority2           = this.RandomValue();

            // A newly created priority queue contains no elements.
            Assert.IsFalse(this.PriorityQueue.Contains(node1, priority1));

            // Once a node is added to the priority queue with a certain priority, it's contained in it
            // but only for the specified priority.
            this.PriorityQueue.Enqueue(node1, priority1);
            Assert.IsTrue(this.PriorityQueue.Contains(node1, priority1));
            Assert.IsFalse(this.PriorityQueue.Contains(node1, priority2));

            this.PriorityQueue.Enqueue(node2, priority2);
            Assert.IsTrue(this.PriorityQueue.Contains(node1, priority1));
            Assert.IsFalse(this.PriorityQueue.Contains(node1, priority2));
            Assert.IsTrue(this.PriorityQueue.Contains(node2, priority2));
            Assert.IsFalse(this.PriorityQueue.Contains(node2, priority1));

            this.PriorityQueue.Enqueue(node3, priority1);
            Assert.IsTrue(this.PriorityQueue.Contains(node1, priority1));
            Assert.IsFalse(this.PriorityQueue.Contains(node1, priority2));
            Assert.IsTrue(this.PriorityQueue.Contains(node2, priority2));
            Assert.IsFalse(this.PriorityQueue.Contains(node2, priority1));
            Assert.IsTrue(this.PriorityQueue.Contains(node3, priority1));
            Assert.IsFalse(this.PriorityQueue.Contains(node3, priority2));
        }
示例#7
0
    internal void InsertFront(T new_data, U new_comparable)//if data needs to be put at front
    {
        PriorityQueueNode <T, U> new_node = new PriorityQueueNode <T, U>(new_data, new_comparable);

        new_node.next = this.head;
        this.head     = new_node;
    }
示例#8
0
        public void PriorityQueueFillAndEmpty()
        {
            List <PriorityQueueNode> nodesToEnqueue = new List <PriorityQueueNode>()
            {
                new Node(new NodeData(uniqueKey: 0.ToString(), name: "A"), priority: 3),
                new Node(new NodeData(uniqueKey: 1.ToString(), name: "B"), priority: 2),
                new Node(new NodeData(uniqueKey: 2.ToString(), name: "C"), priority: 1),
            };

            PriorityQueue pq = PriorityQueueFactory.CreatePriorityQueue();

            foreach (Node node in nodesToEnqueue)
            {
                pq.Enqueue(node);
            }
            int expectedCount = pq.Count();

            Assert.AreEqual(expectedCount, nodesToEnqueue.Count);

            int expectedPriority = 1;

            while (pq.Count() > 0)
            {
                PriorityQueueNode peek = pq.Peek();
                PriorityQueueNode n    = pq.Dequeue();

                Assert.AreEqual(peek.Data.UniqueKey, n.Data.UniqueKey);

                Assert.AreEqual(n.Priority, expectedPriority);
                expectedPriority++;

                expectedCount--;
                Assert.AreEqual(pq.Count(), expectedCount);
            }
        }
示例#9
0
 public void RemoveBuildUnit(PriorityQueueNode <AssetBuildUnit> node)
 {
     lock (queueLock)
     {
         queue.Remove(node);
     }
 }
示例#10
0
        public void Enqueue(PriorityQueueNode node)
        {
            int lastIndex = Count();
            PriorityQueueNodeWrapper wrapper = new PriorityQueueNodeWrapper(node);

            AttachNodeAtIndex(wrapper, lastIndex);
            SiftUp(lastIndex);
        }
示例#11
0
        private void SwapAndUpdateMap(int index1, int index2)
        {
            PriorityQueueNode node1 = this.minHeap[index1];
            PriorityQueueNode node2 = this.minHeap[index2];

            MapSwap(node1, node2);

            ArrayUtility.Swap(this.minHeap, index1, index2);
        }
示例#12
0
        // TODO: We will need a better API than exposing PriorityQueueNode<SchedulerEntry> before we can make this public.
        internal void Add(Action simpleAction, int priority = 0, object token = null)
        {
            var schedulerEntryNode = new PriorityQueueNode <SchedulerEntry>(new SchedulerEntry(simpleAction, priority)
            {
                Token = token
            });

            Schedule(schedulerEntryNode, ScheduleMode.Last);
        }
示例#13
0
        private void MapSwap(PriorityQueueNode node1, PriorityQueueNode node2)
        {
            int tmp = this.nodeUniqueKeyToHeapIndexMap[node1.Data.UniqueKey];

            this.nodeUniqueKeyToHeapIndexMap[node1.Data.UniqueKey] =
                this.nodeUniqueKeyToHeapIndexMap[node2.Data.UniqueKey];

            this.nodeUniqueKeyToHeapIndexMap[node2.Data.UniqueKey] = tmp;
        }
        public void Enqueue(T item, int priority)
        {
            EnsureCapacity();

            int index = _count;

            _count++;
            _heap[index] = new PriorityQueueNode(item, priority);
            HeapifyUp(index);
        }
示例#15
0
 public MicroThread(Scheduler scheduler, MicroThreadFlags flags = MicroThreadFlags.None)
 {
     Id        = Interlocked.Increment(ref globalCounterId);
     Scheduler = scheduler;
     ScheduledLinkedListNode = new PriorityQueueNode <MicroThread>(this);
     AllLinkedListNode       = new LinkedListNode <MicroThread>(this);
     ScheduleMode            = ScheduleMode.Last;
     Flags = flags;
     Tags  = new PropertyContainer(this);
 }
示例#16
0
 internal void Unschedule(PriorityQueueNode <SchedulerEntry> schedulerEntry)
 {
     lock (ScheduledEntries)
     {
         if (schedulerEntry.Index != -1)
         {
             ScheduledEntries.Remove(schedulerEntry);
         }
     }
 }
    private PriorityQueueNode <Chunk> GetNode(Chunk chunk)
    {
        PriorityQueueNode <Chunk> node;

        if (!c_nodes.TryGetValue(chunk.hashcode, out node))
        {
            node = new PriorityQueueNode <Chunk>(chunk);
        }
        return(node);
    }
示例#18
0
        // TODO: We will need a better API than exposing PriorityQueueNode<SchedulerEntry> before we can make this public.
        internal PriorityQueueNode <SchedulerEntry> Add(Action simpleAction, int priority = 0, object token = null, ProfilingKey profilingKey = null)
        {
            var schedulerEntryNode = new PriorityQueueNode <SchedulerEntry>(new SchedulerEntry(simpleAction, priority)
            {
                Token = token, ProfilingKey = profilingKey
            });

            Schedule(schedulerEntryNode, ScheduleMode.Last);
            return(schedulerEntryNode);
        }
        public Graph GetTree()
        {
            // initialize the graph that will hold the MST
            Graph mst = new KevinGraph();

            // initialize the priority queue that will hold the vertices outside the MST
            PriorityQueue remainingVertices = new KevinPriorityQueue();

            foreach (GraphVertex v in weightedGraph.GetAllVertices())
            {
                remainingVertices.Enqueue(new MSTPriorityQueueNode(data: v, priority: int.MaxValue));
            }

            Dictionary <string, GraphEdge> lowestCostEdgeForVertex = new Dictionary <string, GraphEdge>();

            while (remainingVertices.Count() > 0)
            {
                // Get the vertex with the lowest code to add to the MST
                // The first vertex is chosen arbitrarily because all vertices start with max cost.
                PriorityQueueNode currentNode   = remainingVertices.Dequeue();
                GraphVertex       currentVertex = currentNode.Data as GraphVertex;

                // Add the vertex and its lowest cost edge (if any) to the MST
                mst.AddVertex(currentVertex.UniqueKey);
                if (lowestCostEdgeForVertex.ContainsKey(currentVertex.UniqueKey))
                {
                    GraphEdge lowestCostEdge = lowestCostEdgeForVertex[currentVertex.UniqueKey];
                    // TO-DO: why?
                    mst.AddEdge(lowestCostEdge.SourceVertexUniqueKey, lowestCostEdge.TargetVertexUniqueKey, lowestCostEdge.Weight);
                    mst.AddEdge(lowestCostEdge.TargetVertexUniqueKey, lowestCostEdge.SourceVertexUniqueKey, lowestCostEdge.Weight);
                }

                // update the minimum cost for each adjacent vertex, and the associated edge
                foreach (GraphEdge edge in currentVertex.GetIncidentEdges())
                {
                    GraphVertex edgeTarget = weightedGraph.GetVertexByUniqueKey(edge.TargetVertexUniqueKey);

                    if (!remainingVertices.Contains(edgeTarget.UniqueKey))
                    {
                        continue;
                    }

                    int newCost = edge.Weight;
                    PriorityQueueNode targetNode = remainingVertices.Peek(edgeTarget.UniqueKey);
                    if (newCost < targetNode.Priority)
                    {
                        remainingVertices.ChangePriority(targetNode.Data.UniqueKey, newCost);
                        lowestCostEdgeForVertex[edgeTarget.UniqueKey] = edge;
                    }
                }
            }

            return(mst);
        }
示例#20
0
 public MicroThread(Scheduler scheduler, MicroThreadFlags flags = MicroThreadFlags.None)
 {
     Id        = Interlocked.Increment(ref globalCounterId);
     Scheduler = scheduler;
     ScheduledLinkedListNode = new PriorityQueueNode <SchedulerEntry>(new SchedulerEntry(this));
     AllLinkedListNode       = new LinkedListNode <MicroThread>(this);
     ScheduleMode            = ScheduleMode.Last;
     Flags = flags;
     Tags  = new PropertyContainer(this);
     cancellationTokenSource = new CancellationTokenSource();
 }
    /// <summary>
    /// The build (third) pass of the chunk manager.
    /// The Priority Queue for generation is rebuilt here.
    /// </summary>
    private void BuildPass(int offset_x, int offset_z)
    {
        this.chunkQueue.Clear();

        foreach (Chunk chunk in this.c_generate.Values)
        {
            PriorityQueueNode <Chunk> node = GetNode(chunk);
            this.chunkQueue.Enqueue(node, (int)Distance(new Tuple <int, int>(offset_x, offset_z),
                                                        new Tuple <int, int>(chunk.coordinates.GetX(CoordinateSpace.Chunk),
                                                                             chunk.coordinates.GetZ(CoordinateSpace.Chunk))));
        }
    }
示例#22
0
        public List <GraphVertex> FindShortestPath(
            string startVertexUniqueKey,
            string targetVertexUniqueKey)
        {
            GraphVertex startVertex  = weightedGraph.GetVertexByUniqueKey(startVertexUniqueKey);
            GraphVertex targetVertex = weightedGraph.GetVertexByUniqueKey(targetVertexUniqueKey);

            // initialize the 'prev' data structure that will hold the path
            Dictionary <string, GraphVertex> prev = new Dictionary <string, GraphVertex>();

            // initialize the priority queue
            PriorityQueue remainingVertices = new KevinPriorityQueue();

            foreach (GraphVertex v in weightedGraph.GetAllVertices())
            {
                int totalPathWeightThroughCurrentVertex = v.UniqueKey == startVertex.UniqueKey ?
                                                          0 :
                                                          int.MaxValue;
                remainingVertices.Enqueue(
                    new ShortestPathPriorityQueueNode(data: v, priority: totalPathWeightThroughCurrentVertex));
            }

            while (remainingVertices.Count() > 0)
            {
                PriorityQueueNode currentNode   = remainingVertices.Dequeue();
                GraphVertex       currentVertex = currentNode.Data as GraphVertex;

                foreach (GraphEdge edge in currentVertex.GetIncidentEdges())
                {
                    GraphVertex edgeTarget = weightedGraph.GetVertexByUniqueKey(edge.TargetVertexUniqueKey);

                    if (!remainingVertices.Contains(edgeTarget.UniqueKey))
                    {
                        continue;
                    }

                    int newDist = currentNode.Priority + edge.Weight;
                    PriorityQueueNode targetNode = remainingVertices.Peek(edgeTarget.UniqueKey);
                    if (newDist < targetNode.Priority)
                    {
                        remainingVertices.ChangePriority(targetNode.Data.UniqueKey, newDist);
                        prev[edgeTarget.UniqueKey] = currentVertex;
                    }
                }

                if (currentVertex.UniqueKey == targetVertex.UniqueKey)
                {
                    break;
                }
            }

            return(BuildPath(prev, startVertexUniqueKey, targetVertexUniqueKey));
        }
示例#23
0
        internal void Schedule(PriorityQueueNode <SchedulerEntry> schedulerEntry, ScheduleMode scheduleMode)
        {
            var nextCounter = SchedulerCounter++;

            if (scheduleMode == ScheduleMode.First)
            {
                nextCounter = -nextCounter;
            }

            schedulerEntry.Value.SchedulerCounter = nextCounter;

            scheduledEntries.Enqueue(schedulerEntry);
        }
示例#24
0
        public void TestDequeue()
        {
            PriorityQueueNode node1 = new PriorityQueueNode();
            PriorityQueueNode node2 = new PriorityQueueNode();
            PriorityQueueNode node3 = new PriorityQueueNode();
            int priority            = this.RandomValue();

            this.PriorityQueue.Enqueue(node1, priority);
            this.PriorityQueue.Enqueue(node2, priority + 1);
            Assert.AreEqual(node1, this.PriorityQueue.Dequeue());

            this.PriorityQueue.Enqueue(node3, priority + 1);
            Assert.AreEqual(node2, this.PriorityQueue.Dequeue());
        }
        private void EnsureCapacity()
        {
            int capacity = _heap.Length;

            if (_count < capacity)
            {
                return;
            }

            var resized = new PriorityQueueNode[capacity * 2];

            Array.Copy(_heap, 0, resized, 0, _count);
            _heap = resized;
        }
示例#26
0
        public void Update(Grid grid)
        {
            if (_startRow >= grid.RowCount || _startColumn >= grid.ColumnCount)
            {
                throw new ArgumentException("The grid is too small to hold source cell index", nameof(grid));
            }

            GridCell sourceCell = grid[_startRow, _startColumn];

            sourceCell.Tags.Add(PriorityNodeKey, CreatePriorityNode(sourceCell, 0));

            foreach (GridCell cell in grid.GetCells().Where(cell => !sourceCell.Equals(cell)))
            {
                PriorityQueueNode <int, CellNodeValue> priorityQueueNode = CreatePriorityNode(cell, int.MaxValue);
                cell.Tags.Add(PriorityNodeKey, priorityQueueNode);
            }

            var priorityQueue = new PriorityQueue <CellNodeValue, int>(grid.Size);

            foreach (GridCell cell in grid.GetCells())
            {
                PriorityQueueNode <int, CellNodeValue> cellTag = GetPriorityNodeOnCell(cell);
                priorityQueue.Enqueue(cellTag, cellTag.Priority);
            }

            while (priorityQueue.Count > 0)
            {
                PriorityQueueNode <int, CellNodeValue> minDistanceNode = priorityQueue.Dequeue();
                GridCell minDistanceCell = minDistanceNode.Value.Current;
                foreach (GridCell neighbor in minDistanceCell.Links)
                {
                    int altDistance = minDistanceNode.Priority + 1;
                    PriorityQueueNode <int, CellNodeValue> neighborNode = GetPriorityNodeOnCell(neighbor);
                    if (altDistance < neighborNode.Priority)
                    {
                        neighborNode.Value.Previous = minDistanceCell;
                        priorityQueue.UpdatePriority(neighborNode, altDistance);
                    }
                }
            }

            foreach (GridCell cell in grid.GetCells())
            {
                PriorityQueueNode <int, CellNodeValue> node = GetPriorityNodeOnCell(cell);
                cell.Tags.Remove(PriorityNodeKey);
                cell.Tags[ResolvingDistance] = node.Priority;
            }
        }
示例#27
0
        public void TestEnumeration()
        {
            const int NodeCount = 18;
            var       q         = new AlternativePriorityQueue <double, object>(NodeCount);

            var random = new Random();
            var nodes  = new PriorityQueueNode <double, object> [NodeCount];

            for (int i = 0; i < NodeCount; i++)
            {
                nodes[i] = new PriorityQueueNode <double, object>((object)null);
                q.Enqueue(nodes[i], random.NextDouble());
            }

            CollectionAssert.AreEquivalent(nodes, q);
        }
示例#28
0
        public void ChangePriority(string nodeUniqueKey, int priority)
        {
            int heapIndex          = GetPriorityQueueNodeIndex(nodeUniqueKey);
            PriorityQueueNode node = minHeap[heapIndex];

            if (priority < node.Priority)
            {
                node.Priority = priority;
                SiftUp(heapIndex);
            }
            else if (priority > node.Priority)
            {
                node.Priority = priority;
                SiftDown(heapIndex);
            }
        }
 public void Add(T new_data, U new_compareable)                          //sorted add
 {
     if (next == null)                                                   //is this the end of the list
     {
         next = new PriorityQueueNode <T, U>(new_data, new_compareable); //append data
     }
     else if (next.compareable.CompareTo(new_compareable) < 0)           //is the new data larger than next?
     {
         next.Add(new_data, new_compareable);                            //pass it to the next node to check
     }
     else//current value is smaller than next so needs to be linked in here
     {
         PriorityQueueNode <T, U> temp = new PriorityQueueNode <T, U>(new_data, new_compareable);
         temp.next = next;
         next      = temp;
     }
 }
示例#30
0
        public void TestContainsConsistency()
        {
            var q = new AlternativePriorityQueue <int, int>();

            addRandomItems(q, 150);

            var missingNode = new PriorityQueueNode <int, int>(14);
            var presentNode = new PriorityQueueNode <int, int>(14);

            q.Enqueue(presentNode, 75);

            Assert.True(q.Contains(presentNode));
            Assert.False(q.Contains(missingNode));

            q.Remove(presentNode);
            Assert.False(q.Contains(presentNode));
            CheckOrder(q);
        }