Example #1
0
        public void PropertyPriorityAdjustment()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Ensure that PriorityAdjustment reports 0.
            Assert.That(queue.PriorityAdjustment, Is.EqualTo(0.0));

            // Enqueue an element in the queue.
            queue.Enqueue(1.0, 1);

            // Ensure that PriorityAdjustment reports 1.
            Assert.That(queue.PriorityAdjustment, Is.EqualTo(1L * ConcurrentPriorityQueue <int> .EPSILON));

            // Enqueue an element in the queue.
            queue.Enqueue(1.0, 1);

            // Ensure that PriorityAdjustment reports 2.
            Assert.That(queue.PriorityAdjustment, Is.EqualTo(2L * ConcurrentPriorityQueue <int> .EPSILON));

            // Clear the queue.
            queue.Clear();

            // Ensure that PriorityAdjustment reports 0.
            Assert.That(queue.PriorityAdjustment, Is.EqualTo(0.0));
        }
Example #2
0
        public void PropertyNumQueuedItems()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Ensure that NumQueuedItems reports 0.
            Assert.That(queue.NumQueuedItems, Is.EqualTo(0L));

            // Enqueue an element in the queue.
            queue.Enqueue(1.0, 1);

            // Ensure that NumQueuedItems reports 1.
            Assert.That(queue.NumQueuedItems, Is.EqualTo(1L));

            // Enqueue an element in the queue.
            queue.Enqueue(1.0, 1);

            // Ensure that NumQueuedItems reports 2.
            Assert.That(queue.NumQueuedItems, Is.EqualTo(2L));

            // Clear the queue.
            queue.Clear();

            // Ensure that NumQueuedItems reports 0.
            Assert.That(queue.NumQueuedItems, Is.EqualTo(0L));
        }
Example #3
0
        public void Disconnect(bool requested = true)
        {
            resetEvent.Reset();
            lock (queue)
                queue.Clear();

            rcon.Disconnect();
            Disconnected?.Invoke(this, requested);
        }
Example #4
0
        Clear()
        {
            // Clear the priority queue.
            __queue.Clear();

            // Lock the thread -- CRITICAL SECTION BEGIN
            Monitor.Enter(__runningCriticalTasksLock);
            try
            {
                __runningCriticalTasks = 0;
            }
            finally
            {
                Monitor.Exit(__runningCriticalTasksLock);
                // Unlock the thread -- CRITICAL SECTION END
            }

            // Lock the thread -- CRITICAL SECTION BEGIN
            Monitor.Enter(__runningNoncriticalTasksLock);
            try
            {
                __runningNoncriticalTasks = 0;
            }
            finally
            {
                Monitor.Exit(__runningNoncriticalTasksLock);
                // Unlock the thread -- CRITICAL SECTION END
            }

            // Lock the thread -- CRITICAL SECTION BEGIN
            Monitor.Enter(__waitingCriticalTasksLock);
            try
            {
                __waitingCriticalTasks = 0;
            }
            finally
            {
                Monitor.Exit(__waitingCriticalTasksLock);
                // Unlock the thread -- CRITICAL SECTION END
            }

            // Lock the thread -- CRITICAL SECTION BEGIN
            Monitor.Enter(__waitingNoncriticalTasksLock);
            try
            {
                __waitingNoncriticalTasks = 0;
            }
            finally
            {
                Monitor.Exit(__waitingNoncriticalTasksLock);
                // Unlock the thread -- CRITICAL SECTION END
            }
        }
Example #5
0
        /// <summary>
        /// Removes all loaded tiles and requests
        /// </summary>
        public void Purge()
        {
            lock (lockObj) {
                requestQueue.Clear();

                VTTile t;

                while (loadedTiles.TryDequeue(out t))
                {
                }
            }
        }
        public void ConcurrentReadWritePerformance()
        {
            const int count = 10;
            var times = new int[count];
            var c = new ConcurrentPriorityQueue<int>();
            for (var i = 0; i < count; i++)
            {
                var t = new CollectionReadWritePerformance(c, 10, 5, 10000);
                times[i] = t.Run().Milliseconds;
                c.Clear();
            }

            Console.WriteLine("Avg: {0}, Min: {1}, Max: {2}", times.Average(), times.Min(), times.Max());
            Console.WriteLine(string.Join(" ", times));
        }
Example #7
0
        public void ConcurrentReadWritePerformance()
        {
            const int count = 10;
            var       times = new int[count];
            var       c     = new ConcurrentPriorityQueue <int>();

            for (var i = 0; i < count; i++)
            {
                var t = new CollectionReadWritePerformance(c, 10, 5, 10000);
                times[i] = t.Run().Milliseconds;
                c.Clear();
            }

            Console.WriteLine("Avg: {0}, Min: {1}, Max: {2}", times.Average(), times.Min(), times.Max());
            Console.WriteLine(string.Join(" ", times));
        }
        public void FunctionsAsNormalList_ForSingleThreadedAccess()
        {
            // Because nothing interesting happens when the reservoir's item count is below the size limit, it seems reasonable to just wrap all of the basic list API tests into one test
            var eventsToAdd = new[]
            {
                Create(0.3f),
                Create(0.2f),
                Create(0.1f),
            };

            // Add
            foreach (var ev in eventsToAdd)
            {
                ConcurrentPriorityQueue.Add(ev);
            }

            // GetEnumerator
            var index = 0;
            var nongenericEnumerator = ((IEnumerable)ConcurrentPriorityQueue).GetEnumerator();

            while (index < eventsToAdd.Length && nongenericEnumerator.MoveNext())
            {
                Assert.AreEqual(eventsToAdd[index++], nongenericEnumerator.Current);
            }
            Assert.AreEqual(eventsToAdd.Length, index);

            // Count
            Assert.AreEqual(ConcurrentPriorityQueue.Count, eventsToAdd.Length);

            // CopyTo
            var actualEvents   = ConcurrentPriorityQueue.Select(node => node.Data).ToArray();
            var expectedEvents = eventsToAdd.Select(node => node.Data).ToArray();

            Assert.That(actualEvents, Is.EquivalentTo(expectedEvents));

            // Contains
            Assert.True(eventsToAdd.All(ConcurrentPriorityQueue.Contains));

            // Clear
            ConcurrentPriorityQueue.Clear();
            Assert.AreEqual(0, ConcurrentPriorityQueue.Count);
            Assert.False(eventsToAdd.Any(ConcurrentPriorityQueue.Contains));
        }
Example #9
0
        public void Clear()
        {
            // Create a new priority queue.
            ConcurrentPriorityQueue <int> queue = new ConcurrentPriorityQueue <int>();

            // Enqueue a few elements into the queue.
            queue.Enqueue(1.0, 2);
            queue.Enqueue(3.0, 6);
            queue.Enqueue(2.0, 4);

            // Ensure that 3 elements have been added to the queue.
            Assert.That(queue.Count, Is.EqualTo(3));

            // Clear the queue.
            queue.Clear();

            // Ensure that all of the elements have been removed.
            Assert.That(queue.Count, Is.EqualTo(0));
        }
Example #10
0
        public void Close()
        {
            if (!ConnectionInfo.RakSessions.TryRemove(EndPoint, out _))
            {
                return;
            }

            State   = ConnectionState.Unconnected;
            Evicted = true;
            CustomMessageHandler = null;

            // Send with high priority, bypass queue
            SendDirectPacket(DisconnectionNotification.CreateObject());

            SendQueueAsync(500).Wait();

            _cancellationToken.Cancel();
            _packetQueuedWaitEvent.Set();
            _packetHandledWaitEvent.Set();
            _orderingBufferQueue.Clear();

            _packetSender.Close(this);

            try
            {
                _orderedQueueProcessingThread = null;
                _cancellationToken.Dispose();
                _packetQueuedWaitEvent.Close();
                _packetHandledWaitEvent.Close();
            }
            catch
            {
                // ignored
            }

            if (Log.IsDebugEnabled)
            {
                Log.Info($"Closed network session for player {Username}");
            }
        }
Example #11
0
        public List <ISpatialmHGResult> SpatialmHGWrapper3D(List <Tuple <double, double, double, bool> > input, bool runViaAzure = false)
        {
            var        coordinates = input.Select(c => (ICoordinate) new Coordinate3D(c.Item1, c.Item2, c.Item3)).ToList();
            Normalizer nrm         = new Normalizer(coordinates);
            var        normcoords  = nrm.Normalize(coordinates).Select(c => (Coordinate3D)c).ToList();
            var        labels      = input.Select(c => c.Item4).ToList();

            InitializeMHG(labels);
            int idx       = -1;
            var solutions = new ConcurrentPriorityQueue <double, SpatialmHGResult3D>();
            var planeList = new ConcurrentPriorityQueue <double, Plane>(); //minheap based, smaller is better

            //Foreach perpendicular bisector plane
            for (var i = 0; i < coordinates.Count; i++)
            {
                for (var j = 0; j < coordinates.Count; j++)
                {
                    if (labels[i] != labels[j])
                    {
                        //Reduce to 2D problem
                        var plane = Plane.Bisector(normcoords[i], normcoords[j]);
                        planeList.Enqueue(1.0, plane);
                    }
                }
            }

            var numPlanes = planeList.Count();

            if ((Config.ActionList & Actions.Search_EmpricalSampling) != 0)
            {
                var problem     = normcoords.Zip(labels, (a, b) => new Tuple <ICoordinate, bool>(a, b)).ToList();
                var gr          = new Gridding();
                var problemSize = MathExtensions.Binomial(numPlanes, 3) + MathExtensions.Binomial(numPlanes, 2) + numPlanes + 1;
                gr.GenerateEmpricialDensityGrid((long)Math.Min(problemSize, 100000), problem);
                var results = new ConcurrentPriorityQueue <double, ISpatialmHGResult>();
                Parallel.ForEach(gr.GetPivots(), pivot =>
                {
                    var binvec = problem.OrderBy(c => c.Item1.EuclideanDistance(pivot)).Select(c => c.Item2).ToArray();
                    var res    = mHGJumper.minimumHypergeometric(binvec);
                    results.Enqueue(res.Item1, new SpatialmHGResult3D(res.Item1, res.Item2, (Coordinate3D)pivot));
                    while (results.Count > Config.GetTopKResults)
                    {
                        results.TryDequeue(out var junk);
                    }
                });
                return(results.Select(v => v.Value).ToList());
            }

            if ((Config.ActionList & Actions.Search_CellSkipping) != 0)
            {
                if (runViaAzure)
                {
                    var fileList = new List <string>();
                    foreach (var file in Directory.EnumerateFiles(@"3D\Planes\"))
                    {
                        File.Delete(file);
                    }
                    foreach (var file in Directory.EnumerateFiles(@"3D\2dProblems\"))
                    {
                        File.Delete(file);
                    }
                    var asList = planeList.ToList();
                    Parallel.ForEach(asList, currPlane =>
                    {
                        var currIdx = Interlocked.Increment(ref idx);
                        Console.Write($"\r\r\r\r\r\rGenerating 2D projection {currIdx}/{numPlanes}.");
                        var plane = currPlane.Value;

                        if (StaticConfigParams.WriteToCSV)
                        {
                            Config.Log.WriteLine("Selected plane {0}/{1} at distance {2}", currIdx, numPlanes, currPlane.Key);
                        }
                        var subProblemIn2D  = plane.ProjectOntoAndRotate(normcoords, out PrincipalComponentAnalysis pca);
                        pca.NumberOfOutputs = 3; //project back to 3D
                        pca.Save($@"3D\PCA\pca{currIdx}.bin");
                        Generics.SaveToCSV(plane, $@"3D\Planes\plane{currIdx}.csv", true);
                        Generics.SaveToCSV(subProblemIn2D.Zip(labels, (c, l) => c.ToString() + "," + l), $@"3D\2dProblems\coords{currIdx}.csv", true);
                        fileList.Add($@"3D\2dProblems\coords{currIdx}.csv");
                    });
                    Console.WriteLine(@"Done. Initializing Batch pool.");
                    AzureBatchExecution.MainAsync(fileList).Wait();
                }
                else
                {
                    while (planeList.TryDequeue(out var currPlane))
                    {
                        var plane = currPlane.Value;
                        idx++;
                        if (StaticConfigParams.WriteToCSV)
                        {
                            Generics.SaveToCSV(plane, $@"Planes\plane{idx}.csv", true);
                        }
                        Config.Log.WriteLine("Selected plane {0}/{1} at distance {2}", idx, numPlanes, currPlane.Key);
                        var subProblemIn2D = plane.ProjectOntoAndRotate(normcoords, out PrincipalComponentAnalysis pca);
                        pca.NumberOfOutputs = 3; //project back to 3D
                                                 //Solve 2D problem
                        StaticConfigParams.filenamesuffix = idx.ToString();
                        var res = Solve2DProblem(subProblemIn2D, labels, normcoords, pca);
                        foreach (var mHGresult2D in res)
                        {
                            var projectedResult = new SpatialmHGResult3D(mHGresult2D, pca, idx);
                            solutions.Enqueue(projectedResult.pvalue, projectedResult);
                        }
                        solutions.TryPeek(out var bestCell);
                        var bestCellCenter  = bestCell.Value.GetCenter();
                        var remainingPlanes = planeList.Select(t => t.Value).ToList();
                        planeList.Clear();
                        foreach (var p in remainingPlanes)
                        {
                            planeList.Enqueue(bestCellCenter.DistanceToPlane(p), p);
                        }
                    }
                }

                //Combine 2D solutions
                var combinedResultsNaive = new List <SpatialmHGResult3D>();
                for (var i = 0; i < Config.GetTopKResults; i++)
                {
                    KeyValuePair <double, SpatialmHGResult3D> bestCell;
                    solutions.TryDequeue(out bestCell);
                    if (bestCell.Key <= Config.SIGNIFICANCE_THRESHOLD)
                    {
                        bestCell.Value.Denormalize(nrm);
                        combinedResultsNaive.Add(bestCell.Value);
                    }
                    else
                    {
                        break;
                    }
                }
                Config.Log.updater?.Wait();
                return(combinedResultsNaive.Cast <ISpatialmHGResult>().ToList());
            }

            return(null);
        }
Example #12
0
 public void Clear() => Queue.Clear();
Example #13
0
 internal void Clear()
 {
     _queue.Clear();
 }