protected override void SetupActivities()
        {
            var partitioner = new Partitioner(8, new Murmur3UnsafeHashGenerator());

            AddActivityContext<TestActivity, TestArguments, TestLog>(() => new TestActivity(), h => h.UsePartitioner(partitioner, args => args.Arguments.Value),
                h => h.UsePartitioner(partitioner, args => args.Log.OriginalValue));
        }
예제 #2
0
        public float doallmoves(Playfield playf)
        {
            print = playf.print;
            this.isLethalCheck = playf.isLethalCheck;
            enoughCalculations = false;
            botBase            = Ai.Instance.botBase;
            this.posmoves.Clear();
            this.twoturnfields.Clear();
            this.addToPosmoves(playf);
            bool             havedonesomething = true;
            List <Playfield> temp = new List <Playfield>();
            int deep = 0;

            this.calculated = 0;
            Playfield bestold = null;

            bestoldval = -20000000;
            while (havedonesomething)
            {
                if (this.printNormalstuff)
                {
                    Helpfunctions.Instance.logg("ailoop");
                }
                GC.Collect();
                temp.Clear();
                temp.AddRange(this.posmoves);
                this.posmoves.Clear();
                havedonesomething  = false;
                threadnumberGlobal = 0;

                if (print)
                {
                    startEnemyTurnSimThread(temp, 0, temp.Count);
                }
                else
                {
                    Parallel.ForEach(Partitioner.Create(0, temp.Count),
                                     range =>
                    {
                        startEnemyTurnSimThread(temp, range.Item1, range.Item2);
                    });
                }

                foreach (Playfield p in temp)
                {
                    if (this.totalboards > 0)
                    {
                        this.calculated += p.nextPlayfields.Count;
                    }
                    if (this.calculated <= this.totalboards)
                    {
                        this.posmoves.AddRange(p.nextPlayfields);
                        p.nextPlayfields.Clear();
                    }

                    //get the best Playfield
                    float pVal = botBase.getPlayfieldValue(p);
                    if (pVal > bestoldval)
                    {
                        bestoldval = pVal;
                        bestold    = p;
                        bestoldDuplicates.Clear();
                    }
                    else if (pVal == bestoldval)
                    {
                        bestoldDuplicates.Add(p);
                    }
                }
                if (isLethalCheck && bestoldval >= 10000)
                {
                    this.posmoves.Clear();
                }
                if (this.posmoves.Count > 0)
                {
                    havedonesomething = true;
                }

                if (this.printNormalstuff)
                {
                    int donec = 0;
                    foreach (Playfield p in posmoves)
                    {
                        if (p.complete)
                        {
                            donec++;
                        }
                    }
                    Helpfunctions.Instance.logg("deep " + deep + " len " + this.posmoves.Count + " dones " + donec);
                }

                cuttingposibilities(isLethalCheck);

                if (this.printNormalstuff)
                {
                    Helpfunctions.Instance.logg("cut to len " + this.posmoves.Count);
                }
                deep++;
                temp.Clear();

                if (this.calculated > this.totalboards)
                {
                    enoughCalculations = true;
                }
                if (deep >= this.maxdeep)
                {
                    enoughCalculations = true;
                }
            }

            if (this.dirtyTwoTurnSim > 0 && !twoturnfields.Contains(bestold))
            {
                twoturnfields.Add(bestold);
            }
            this.posmoves.Clear();
            this.posmoves.Add(bestold);
            this.posmoves.AddRange(bestoldDuplicates);

            // search the best play...........................................................
            //do dirtytwoturnsim first :D
            if (!isLethalCheck && bestoldval < 10000)
            {
                doDirtyTwoTurnsim();
            }

            if (posmoves.Count >= 1)
            {
                posmoves.Sort((a, b) => botBase.getPlayfieldValue(b).CompareTo(botBase.getPlayfieldValue(a)));
                Playfield bestplay = posmoves[0];
                float     bestval  = botBase.getPlayfieldValue(bestplay);
                int       pcount   = posmoves.Count;
                for (int i = 1; i < pcount; i++)
                {
                    float val = botBase.getPlayfieldValue(posmoves[i]);
                    if (bestval > val)
                    {
                        break;
                    }
                    if (posmoves[i].cardsPlayedThisTurn > bestplay.cardsPlayedThisTurn)
                    {
                        continue;
                    }
                    else if (posmoves[i].cardsPlayedThisTurn == bestplay.cardsPlayedThisTurn)
                    {
                        if (bestplay.optionsPlayedThisTurn > posmoves[i].optionsPlayedThisTurn)
                        {
                            continue;
                        }
                        else if (bestplay.optionsPlayedThisTurn == posmoves[i].optionsPlayedThisTurn && bestplay.enemyHero.Hp <= posmoves[i].enemyHero.Hp)
                        {
                            continue;
                        }
                    }
                    bestplay = posmoves[i];
                    bestval  = val;
                }
                this.bestmove                 = bestplay.getNextAction();
                this.bestmoveValue            = bestval;
                this.bestboard                = new Playfield(bestplay);
                this.bestboard.guessingHeroHP = bestplay.guessingHeroHP;
                this.bestboard.value          = bestplay.value;
                this.bestboard.hashcode       = bestplay.hashcode;
                bestoldDuplicates.Clear();
                return(bestval);
            }
            this.bestmove      = null;
            this.bestmoveValue = -100000;
            this.bestboard     = playf;

            return(-10000);
        }
예제 #3
0
        private cImage _RunLoop(Rectangle?filterRegion, byte scaleX, byte scaleY, Action <PixelWorker <sPixel> > scaler)
        {
            var startX = filterRegion == null ? 0 : Math.Max(0, filterRegion.Value.Left);
            var startY = filterRegion == null ? 0 : Math.Max(0, filterRegion.Value.Top);

            var endX = filterRegion == null ? this.Width : Math.Min(this.Width, filterRegion.Value.Right);
            var endY = filterRegion == null ? this.Height : Math.Min(this.Height, filterRegion.Value.Bottom);

            var width = endX - startX;

            var result = new cImage(width * scaleX, (endY - startY) * scaleY);

            Parallel.ForEach(
                Partitioner.Create(startY, endY),
                () => 0,
                (range, _, threadStorage) => {
                var threadSrcMinY = range.Item1;
                var threadSrcMaxY = range.Item2;

                var targetY = (threadSrcMinY - startY) * scaleY;
                for (var sourceY = threadSrcMinY; sourceY < threadSrcMaxY; ++sourceY)
                {
                    var worker = new PixelWorker <sPixel>(
                        this.GetImageData(),
                        startX,
                        sourceY,
                        this._width,
                        this._height,
                        this._horizontalOutOfBoundsHandler,
                        this._verticalOutOfBoundsHandler,
                        result.GetImageData(),
                        0,
                        targetY,
                        result._width
                        );
                    var xRange = width;
                    while (xRange >= 64)
                    {
                        xRange -= 64;
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                        scaler(worker);
                        worker.IncrementX(scaleX);
                    }
                    for (; xRange > 0; --xRange)
                    {
                        scaler(worker);
                        worker.IncrementX(scaleX);
                    }

                    targetY += scaleY;
                }
                return(threadStorage);
            },
                _ => { }
                );

            return(result);
        }
예제 #4
0
 public static ParallelLoopResult ForEach <TSource, TLocal> (Partitioner <TSource> source, Func <TLocal> localInit,
                                                             Func <TSource, ParallelLoopState, TLocal, TLocal> body,
                                                             Action <TLocal> localFinally)
 {
     return(ForEach <TSource, TLocal> (source, ParallelOptions.Default, localInit, body, localFinally));
 }
예제 #5
0
        /// <summary>
        /// Ensure that the range partitioner doesn't chunk up elements i.e. uses chunk size = 1
        /// </summary>
        /// <param name="from"></param>
        /// <param name="count"></param>
        /// <param name="rangeSize"></param>
        public static void RangePartitionerDynamicChunking(int from, int count, int rangeSize)
        {
            int to = from + count;

            var partitioner = (rangeSize == -1) ? Partitioner.Create(from, to) : Partitioner.Create(from, to, rangeSize);

            // Check static partitions
            var partitions = partitioner.GetDynamicPartitions();
            var partition1 = partitions.GetEnumerator();
            var partition2 = partitions.GetEnumerator();

            // Initialize the from / to values from the first element
            if (!partition1.MoveNext())
            {
                return;
            }
            Assert.True(from == partition1.Current.Item1);
            if (rangeSize == -1)
            {
                rangeSize = partition1.Current.Item2 - partition1.Current.Item1;
            }

            int nextExpectedFrom = partition1.Current.Item2;
            int nextExpectedTo   = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);

            // Ensure that each partition gets one range only
            // we check this by alternating partitions asking for elements and make sure
            // that we get ranges in a sequence. If chunking were to happen then we wouldn't see a sequence
            int actualCount = partition1.Current.Item2 - partition1.Current.Item1;

            while (true)
            {
                if (!partition1.MoveNext())
                {
                    break;
                }

                Assert.Equal(nextExpectedFrom, partition1.Current.Item1);
                Assert.Equal(nextExpectedTo, partition1.Current.Item2);
                nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
                nextExpectedTo   = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
                actualCount     += partition1.Current.Item2 - partition1.Current.Item1;

                if (!partition2.MoveNext())
                {
                    break;
                }

                Assert.Equal(nextExpectedFrom, partition2.Current.Item1);
                Assert.Equal(nextExpectedTo, partition2.Current.Item2);
                nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
                nextExpectedTo   = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
                actualCount     += partition2.Current.Item2 - partition2.Current.Item1;

                if (!partition2.MoveNext())
                {
                    break;
                }

                Assert.Equal(nextExpectedFrom, partition2.Current.Item1);
                Assert.Equal(nextExpectedTo, partition2.Current.Item2);
                nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
                nextExpectedTo   = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
                actualCount     += partition2.Current.Item2 - partition2.Current.Item1;

                if (!partition1.MoveNext())
                {
                    break;
                }

                Assert.Equal(nextExpectedFrom, partition1.Current.Item1);
                Assert.Equal(nextExpectedTo, partition1.Current.Item2);
                nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
                nextExpectedTo   = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
                actualCount     += partition1.Current.Item2 - partition1.Current.Item1;
            }

            // Verifying that all items are there
            Assert.Equal(count, actualCount);
        }
        /// <summary>
        ///     Selects an item (such as Max or Min).
        /// </summary>
        /// <param name="array">The array to iterate over.</param>
        /// <param name="select">The function to select items over a subset.</param>
        /// <param name="reduce">The function to select the item of selection from the subsets.</param>
        /// <returns>The selected value.</returns>
        public static TOut Aggregate <T, TOut>(T[] array, Func <int, T, TOut> select, Func <TOut[], TOut> reduce)
        {
            if (select == null)
            {
                throw new ArgumentNullException(nameof(select));
            }

            if (reduce == null)
            {
                throw new ArgumentNullException(nameof(reduce));
            }

            // Special case: no action
            if (array == null || array.Length == 0)
            {
                return(reduce(new TOut[0]));
            }

            // Special case: single action, inline
            if (array.Length == 1)
            {
                return(reduce(new[] { select(0, array[0]) }));
            }

            // Special case: straight execution without parallelism
            if (Control.MaxDegreeOfParallelism < 2)
            {
                var mapped = new TOut[array.Length];
                for (var k = 0; k < mapped.Length; k++)
                {
                    mapped[k] = select(k, array[k]);
                }

                return(reduce(mapped));
            }

            // Common case
            var intermediateResults = new List <TOut>();
            var syncLock            = new object();

            Parallel.ForEach(
                Partitioner.Create(0, array.Length),
                CreateParallelOptions(),
                () => new List <TOut>(),
                (range, loop, localData) =>
            {
                var mapped = new TOut[range.Item2 - range.Item1];
                for (var k = 0; k < mapped.Length; k++)
                {
                    mapped[k] = select(k + range.Item1, array[k + range.Item1]);
                }

                localData.Add(reduce(mapped));
                return(localData);
            },
                localResult =>
            {
                lock (syncLock)
                {
                    intermediateResults.Add(reduce(localResult.ToArray()));
                }
            });

            return(reduce(intermediateResults.ToArray()));
        }
예제 #7
0
        private Partitioner <TElement> _partitioner; // The partitioner to use as data source.

        internal PartitionerQueryOperator(Partitioner <TElement> partitioner)
            : base(false, QuerySettings.Empty)
        {
            _partitioner = partitioner;
        }
예제 #8
0
        /// <summary>
        /// Validate After and Before fill the quantities for Stock Exit in Livestock Matrix
        /// </summary>
        /// <param name="beforeQuantities"></param>
        /// <returns></returns>
        public bool ValidateLivestockExit(bool beforeQuantities)
        {
            if (beforeQuantities)
            {
                if (selectedRow.Equals(0))
                {
                    UIApplication.ShowMessageBox("Selecionar Cliente");
                    return(false);
                }

                if (String.IsNullOrEmpty(cbxType.Value))
                {
                    return(false);
                }

                if (cbxType.Value.Equals("Facturación Subasta"))
                {
                    return(false);
                }

                if (cbOutAll.Checked)
                {
                    if (UIApplication.ShowOptionBox("Estas seguro se sar salida a todo el ganado") == 2)
                    {
                        return(false);
                    }
                }

                if (!pendingInvoices[selectedRow - 1].Debt.Equals(0))
                {
                    UIApplication.ShowMessageBox("No se puede dar salida al ganado sin haber facturado la deuda");
                    return(false);
                }
            }
            else   //Validate the Quantities

            {
                var appraisalImport = 0.0;
                var debtImport      = 0.0;

                if (livestock.Where(l => l.Quantity == 0).AsParallel().Count() == livestock.Count)
                {
                    UIApplication.ShowMessageBox("No se ha ingresado cantidad para dar salida al ganado");
                    return(false);
                }

                //This task validate that the Quantity have to be less or equal than Existence
                var task = Task.Factory.StartNew(() => {
                    var cts = new CancellationTokenSource();
                    var po  = new ParallelOptions();
                    po.CancellationToken = cts.Token;

                    ParallelLoopResult result = Parallel.ForEach(Partitioner.Create(0, livestock.Count), (range, state) => {
                        for (int i = range.Item1; i < range.Item2; i++)
                        {
                            if (livestock[i].Quantity > livestock[i].Exist)
                            {
                                cts.Cancel(); //cancel the loop
                            }
                        }
                    });
                    if (cts.IsCancellationRequested)
                    {
                        return(false);
                    }
                    return(true);
                });

                task.Wait();

                if (!task.Result)
                {
                    UIApplication.ShowMessageBox("La cantidad no debe ser mayor que la existencia");
                    return(false);
                }

                //Validate Appraisal Import and Debt Import
                var task2 = Task.Factory.StartNew(() => { appraisalImport = CalculateAppraisalImport(livestock); });
                var task3 = Task.Factory.StartNew(() => { debtImport = massInvoicingDAO.GetDebtImport(pendingInvoices[selectedRow - 1].Code, user.WhsCode); });
                Task.WaitAll(task2, task3);

                if (appraisalImport < debtImport)
                {
                    if (UIApplication.ShowOptionBox("El importe avaluo es menor que el importe deuda, estas seguro de dar salida al ganado") == 2)
                    {
                        mBoolAuthP = false;
                        return(false);
                    }
                    else
                    {
                        mBoolAuthP = true;
                        user.AppraisalValidation = true;
                    }
                }
            }

            return(true);
        }
예제 #9
0
        // This is the entry point after the root node has been pushed into the queue
        // and the first change to the game has occurred
        public override async Task PostProcess(GameTree <GameNode> t)
        {
            // Breadth-first processing loop
            do
            {
                // Merge the TLS lists into the main lists
                foreach (var sq in tlsSearchQueue.Values)
                {
                    foreach (var qi in sq)
                    {
                        if (!searchQueue.ContainsKey(qi.Key))
                        {
                            searchQueue.Add(qi.Key, qi.Value);
                        }
                        else
                        {
                            searchQueue[qi.Key].Probability += qi.Value.Probability;
                        }
                    }
                }
                foreach (var ug in tlsUniqueGames.Values)
                {
                    foreach (var qi in ug)
                    {
                        if (!uniqueGames.ContainsKey(qi.Key))
                        {
                            uniqueGames.Add(qi.Key, qi.Value);
                        }
                        else
                        {
                            uniqueGames[qi.Key].Probability += qi.Value.Probability;
                        }
                    }
                }
#if _TREE_DEBUG
                DebugLog.WriteLine("QUEUE SIZE: " + searchQueue.Count);
#endif
                // Wipe the TLS lists
                tlsSearchQueue = new ThreadLocal <Dictionary <Game, ProbabilisticGameNode> >(() => new Dictionary <Game, ProbabilisticGameNode>(new FuzzyGameComparer()), trackAllValues: true);
                tlsUniqueGames = new ThreadLocal <Dictionary <Game, ProbabilisticGameNode> >(() => new Dictionary <Game, ProbabilisticGameNode>(new FuzzyGameComparer()), trackAllValues: true);

                // Quit if we have processed all nodes and none of them have children (all leaf nodes)
                if (searchQueue.Count == 0)
                {
                    break;
                }

                // Copy the search queue and clear the current one; it will be refilled
                var nextQueue = new Dictionary <Game, ProbabilisticGameNode>(searchQueue);
                searchQueue.Clear();

                // Only parallelize if there are sufficient nodes to do so
                if (nextQueue.Count >= MinNodesToParallelize && ((RandomOutcomeSearch)t).Parallel && MaxDegreesOfParallelism > 1)
                {
                    // Process each game's action queue until it is interrupted by OnAction above
                    await Task.WhenAll(
                        // Split search queue into MaxDegreesOfParallelism partitions
                        from partition in Partitioner.Create(nextQueue).GetPartitions(MaxDegreesOfParallelism)
                        // Run each partition in its own task
                        select Task.Run(async delegate {
#if _TREE_DEBUG
                        var count = 0;
                        DebugLog.WriteLine("Start partition run with " + MaxDegreesOfParallelism + " degrees of parallelism");
#endif
                        using (partition)
                            while (partition.MoveNext())
                            {
                                // Process each node
                                var kv = partition.Current;
                                await kv.Key.ActionQueue.ProcessAllAsync(kv.Value);
#if _TREE_DEBUG
                                count++;
#endif
                            }
#if _TREE_DEBUG
                        DebugLog.WriteLine("End run with partition size {0}", count);
#endif
                    }));

#if _TREE_DEBUG
                    DebugLog.WriteLine("=======================");
                    DebugLog.WriteLine("CLONES SO FAR: " + t.NodeCount + " / " + t.LeafNodeCount);
                    DebugLog.WriteLine("UNIQUE GAMES SO FAR: " + uniqueGames.Count);
                    DebugLog.WriteLine("NEW QUEUE SIZE: " + searchQueue.Count + "\r\n");
#endif
                }
                else
                {
#if _TREE_DEBUG
                    DebugLog.WriteLine("Start single-threaded run");
#endif
                    // Process each node in the search queue sequentially
                    foreach (var kv in nextQueue)
                    {
                        await kv.Key.ActionQueue.ProcessAllAsync(kv.Value);
                    }
#if _TREE_DEBUG
                    DebugLog.WriteLine("End single-threaded run");
#endif
                }
            } while (true);
        }
예제 #10
0
        static int Main(string[] args)
        {
            var softwareUnderTest = args[0];

            _logFile = args[1];
            _logFile = _logFile.Replace("%TIMESTAMP%", DateTime.Now.ToString("yyyy-MM-dd HHmmss"));

            if (!File.Exists(softwareUnderTest))
            {
                LogText(string.Format("The file {0} does not exist.", softwareUnderTest));
                return(-1);
            }

            LogText("Loading test suite...");

            // Load static container of all tests.
            List <TestEnvironment> listEnvironments = new List <TestEnvironment>();

            TestEnvironments.AddAll(listEnvironments);

            int testIndex = 0;

            var f = TaskScheduler.Default;

            var options = new ParallelOptions()
            {
                MaxDegreeOfParallelism = 4,
            };

            // We can run tests on XP and Vista/2003/2008 at the same time since it's separate VMware images.
            var environmentsGroupedByVmwareImage = listEnvironments.GroupBy(item => item.VMwarePath).ToList();

            var partitioner = Partitioner.Create(environmentsGroupedByVmwareImage, EnumerablePartitionerOptions.NoBuffering);

            Parallel.ForEach(partitioner, options, environmentGroup =>
            {
                foreach (var environment in environmentGroup)
                {
                    int localIndex;

                    lock (_lockCounterTest)
                    {
                        localIndex = ++testIndex;

                        string message =
                            string.Format("{0}: {1}/{2} - Test: {3} on {4} with db {5}. Image: {6} (Snapshot: {7})",
                                          DateTime.Now,
                                          localIndex,
                                          listEnvironments.Count,
                                          environment.Description,
                                          environment.OperatingSystem,
                                          environment.DatabaseType,
                                          Path.GetFileName(environment.VMwarePath),
                                          environment.SnapshotName);

                        LogText(message);
                    }

                    var runner = new TestRunner(true, environment, false, softwareUnderTest);

                    try
                    {
                        runner.Run();
                        LogText(string.Format("{0}: Test {1} completed successfully.", DateTime.Now, localIndex));
                    }
                    catch (Exception ex)
                    {
                        LogText(string.Format("{0}: Test {1} failed.", DateTime.Now, localIndex));
                        LogText(ex.ToString());

                        throw;
                    }
                }
            });

            System.Console.WriteLine("All tests completed succesfully.");
            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Console.WriteLine("Press Enter to exit.");
                System.Console.ReadLine();
            }

            return(0);
        }
예제 #11
0
        public void TestJsonDictThreading()
        {
            var jsonResolver = new RefResolve();
            var settings     = new JsonSerializerSettings {
                ReferenceResolverProvider = () => jsonResolver
            };

            var rnd      = new Random(123);
            var examples = new List <Context>();

            var id = 0;

            // different reference objects
            for (int i = 0; i < 10; i++)
            {
                var data = Enumerable.Range(1, 5).Select(_ => (float)rnd.Next(10)).ToArray();

                // referencing the same data
                for (int j = 0; j < 5; j++)
                {
                    examples.Add(new Context(data, id++, settings));
                }
            }

            for (int i = 0; i < 4; i++)
            {
                Permute(examples, rnd);

                for (int maxDegreeOfParallelism = 1; maxDegreeOfParallelism < 4; maxDegreeOfParallelism++)
                {
                    var examplesFound = 0;
                    using (var vw = new VowpalWabbit(new VowpalWabbitSettings {
                        EnableStringExampleGeneration = true, EnableThreadSafeExamplePooling = true
                    }))
                        using (var resolver = new VowpalWabbitJsonReferenceResolver(serializer =>
                        {
                            using (var example = serializer.CreateExamples())
                            {
                                ValidateExample(example, (Context)serializer.UserContext);
                            }

                            serializer.Dispose();

                            Interlocked.Increment(ref examplesFound);
                        }))
                        {
                            Parallel.ForEach(
                                Partitioner.Create(0, examples.Count),
                                new ParallelOptions {
                                MaxDegreeOfParallelism = maxDegreeOfParallelism
                            },
                                range =>
                            {
                                for (int j = range.Item1; j < range.Item2; j++)
                                {
                                    var ctx        = examples[j];
                                    var serializer = new VowpalWabbitJsonSerializer(vw, resolver)
                                    {
                                        UserContext = ctx
                                    };

                                    var example = serializer.ParseAndCreate(ctx.JSON);

                                    // example not ready yet
                                    if (example == null)
                                    {
                                        continue;
                                    }

                                    ValidateExample(example, ctx);

                                    example.Dispose();
                                    serializer.Dispose();

                                    Interlocked.Increment(ref examplesFound);
                                }
                            });
                        }

                    Assert.AreEqual(examples.Count, examplesFound);
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ClusterState"/> class.
        /// </summary>
        public ClusterState(IClusterOptions options, string clusterName, string clientName, Partitioner partitioner, ILoggerFactory loggerFactory)
        {
            Options       = options;
            ClusterName   = clusterName;
            ClientName    = clientName;
            Partitioner   = partitioner;
            LoggerFactory = loggerFactory;

            _stateChangeQueue = new StateChangeQueue(loggerFactory);
        }
예제 #13
0
        public BitmapFont(Canvas canvas, string path)
        {
            this.canvas = canvas;

#if UNCOMPRESSED_CONTENT
            string png = PathOp.Combine(DualityApp.DataDirectory, "Animations", path + ".png");
#else
            string png = PathOp.Combine(DualityApp.DataDirectory, "Main.dz", "Animations", path + ".png");
#endif
            string pathFont = png + ".font";

            int textureHeight;

            using (Stream s = FileOp.Open(png, FileAccessMode.Read)) {
                PixelData pixelData = new Png(s).GetPixelData();
                textureHeight = pixelData.Height;

                ColorRgba[] palette = ContentResolver.Current.Palette.Res.BasePixmap.Res.MainLayer.Data;

                ColorRgba[] data = pixelData.Data;
#if !DISABLE_ASYNC
                Parallel.ForEach(Partitioner.Create(0, data.Length), range => {
                    for (int i = range.Item1; i < range.Item2; i++) {
#else
                    for (int i = 0; i < data.Length; i++) {
#endif
                        int colorIdx = data[i].R;
                        data[i] = palette[colorIdx].WithAlpha(palette[colorIdx].A * data[i].A / (255f * 255f));
                    }
#if !DISABLE_ASYNC
                });
#endif

                Texture texture = new Texture(new Pixmap(pixelData), TextureSizeMode.NonPowerOfTwo, TextureMagFilter.Linear, TextureMinFilter.Linear);

                materialPlain = new Material(DrawTechnique.Alpha, texture);
                materialColor = new Material(ContentResolver.Current.RequestShader("Colorize"), texture);
            }

            using (Stream s = FileOp.Open(pathFont, FileAccessMode.Read)) {
                byte[] internalBuffer = new byte[128];

                byte flags = s.ReadUInt8(ref internalBuffer);
                ushort width = s.ReadUInt16(ref internalBuffer);
                ushort height = s.ReadUInt16(ref internalBuffer);
                byte cols = s.ReadUInt8(ref internalBuffer);
                int rows = textureHeight / height;
                short spacing = s.ReadInt16(ref internalBuffer);
                int asciiFirst = s.ReadUInt8(ref internalBuffer);
                int asciiCount = s.ReadUInt8(ref internalBuffer);

                s.Read(internalBuffer, 0, asciiCount);

                int i = 0;
                for (; i < asciiCount; i++) {
                    asciiChars[i + asciiFirst] = new Rect(
                        (float)(i % cols) / cols,
                        (float)(i / cols) / rows,
                        internalBuffer[i],
                        height);
                }

                UTF8Encoding enc = new UTF8Encoding(false, true);

                int unicodeCharCount = asciiCount + s.ReadInt32(ref internalBuffer);
                for (; i < unicodeCharCount; i++) {
                    s.Read(internalBuffer, 0, 1);

                    int remainingBytes =
                        ((internalBuffer[0] & 240) == 240) ? 3 : (
                        ((internalBuffer[0] & 224) == 224) ? 2 : (
                        ((internalBuffer[0] & 192) == 192) ? 1 : -1
                    ));
                    if (remainingBytes == -1) {
                        throw new InvalidDataException("Char \"" + (char)internalBuffer[0] + "\" is not UTF-8");
                    }

                    s.Read(internalBuffer, 1, remainingBytes);
                    char c = enc.GetChars(internalBuffer, 0, remainingBytes + 1)[0];
                    byte charWidth = s.ReadUInt8(ref internalBuffer);

                    unicodeChars[c] = new Rect(
                        (float)(i % cols) / cols,
                        (float)(i / cols) / rows,
                        charWidth,
                        height);
                }

                this.charHeight = height;
                this.baseSpacing = spacing;
            }
        }
예제 #14
0
        protected override MetaMorpheusEngineResults RunSpecific()
        {
            double       progress           = 0;
            int          oldPercentProgress = 0;
            TerminusType terminusType       = ProductTypeMethod.IdentifyTerminusType(lp);

            // digest database
            HashSet <CompactPeptide> peptideToId = new HashSet <CompactPeptide>();

            Parallel.ForEach(Partitioner.Create(0, proteinList.Count), new ParallelOptions {
                MaxDegreeOfParallelism = commonParams.MaxThreadsToUsePerFile
            }, range =>
            {
                for (int i = range.Item1; i < range.Item2; i++)
                {
                    foreach (var digestionParams in CollectionOfDigestionParams)
                    {
                        foreach (var pepWithSetMods in proteinList[i].Digest(digestionParams, fixedModifications, variableModifications))
                        {
                            CompactPeptide compactPeptide = pepWithSetMods.CompactPeptide(terminusType);

                            var observed = peptideToId.Contains(compactPeptide);
                            if (observed)
                            {
                                continue;
                            }
                            lock (peptideToId)
                            {
                                observed = peptideToId.Contains(compactPeptide);
                                if (observed)
                                {
                                    continue;
                                }
                                peptideToId.Add(compactPeptide);
                            }
                        }
                    }

                    progress++;
                    var percentProgress = (int)((progress / proteinList.Count) * 100);

                    if (percentProgress > oldPercentProgress)
                    {
                        oldPercentProgress = percentProgress;
                        ReportProgress(new ProgressEventArgs(percentProgress, "Digesting proteins...", nestedIds));
                    }
                }
            });

            // sort peptides by mass
            var peptidesSortedByMass = peptideToId.AsParallel().WithDegreeOfParallelism(commonParams.MaxThreadsToUsePerFile).OrderBy(p => p.MonoisotopicMassIncludingFixedMods).ToList();

            peptideToId = null;

            // create fragment index
            List <int>[] fragmentIndex;

            try
            {
                fragmentIndex = new List <int> [(int)Math.Ceiling(maxFragmentSize) * fragmentBinsPerDalton + 1];
            }
            catch (OutOfMemoryException)
            {
                throw new MetaMorpheusException("Max fragment mass too large for indexing engine; try \"Classic Search\" mode, or make the maximum fragment mass smaller");
            }

            // populate fragment index
            progress           = 0;
            oldPercentProgress = 0;
            for (int peptideId = 0; peptideId < peptidesSortedByMass.Count; peptideId++)
            {
                var validFragments = peptidesSortedByMass[peptideId].ProductMassesMightHaveDuplicatesAndNaNs(lp).Distinct().Where(p => !Double.IsNaN(p));

                foreach (var theoreticalFragmentMass in validFragments)
                {
                    if (theoreticalFragmentMass < maxFragmentSize)
                    {
                        int fragmentBin = (int)Math.Round(theoreticalFragmentMass * fragmentBinsPerDalton);

                        if (fragmentIndex[fragmentBin] == null)
                        {
                            fragmentIndex[fragmentBin] = new List <int> {
                                peptideId
                            }
                        }
                        ;
                        else
                        {
                            fragmentIndex[fragmentBin].Add(peptideId);
                        }
                    }
                }

                progress++;
                var percentProgress = (int)((progress / peptidesSortedByMass.Count) * 100);

                if (percentProgress > oldPercentProgress)
                {
                    oldPercentProgress = percentProgress;
                    ReportProgress(new ProgressEventArgs(percentProgress, "Creating fragment index...", nestedIds));
                }
            }

            return(new IndexingResults(peptidesSortedByMass, fragmentIndex, this));
        }
예제 #15
0
        private async Task <IList <ArmorSetSearchResult> > SearchArmorSetsInternal(
            ISolverData data,
            CancellationToken cancellationToken
            )
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            var heads     = new List <IArmorPiece>();
            var chests    = new List <IArmorPiece>();
            var gloves    = new List <IArmorPiece>();
            var waists    = new List <IArmorPiece>();
            var legs      = new List <IArmorPiece>();
            var allCharms = new List <ICharmLevel>();

            var results = new List <ArmorSetSearchResult>();

            var generator = new EquipmentCombinationGenerator(
                searchEquipmentsObjectPool,
                data.AllHeads.Where(x => x.IsSelected).Select(x => x.Equipment),
                data.AllChests.Where(x => x.IsSelected).Select(x => x.Equipment),
                data.AllGloves.Where(x => x.IsSelected).Select(x => x.Equipment),
                data.AllWaists.Where(x => x.IsSelected).Select(x => x.Equipment),
                data.AllLegs.Where(x => x.IsSelected).Select(x => x.Equipment),
                data.AllCharms.Where(x => x.IsSelected).Select(x => x.Equipment)
                );

            long hh = data.AllHeads.Count(x => x.IsSelected);
            long cc = data.AllChests.Count(x => x.IsSelected);
            long gg = data.AllGloves.Count(x => x.IsSelected);
            long ww = data.AllWaists.Count(x => x.IsSelected);
            long ll = data.AllLegs.Count(x => x.IsSelected);
            long ch = data.AllCharms.Count(x => x.IsSelected);

            long combinationCount =
                Math.Max(hh, 1) *
                Math.Max(cc, 1) *
                Math.Max(gg, 1) *
                Math.Max(ww, 1) *
                Math.Max(ll, 1) *
                Math.Max(ch, 1);

            await Task.Yield();

            var parallelOptions = new ParallelOptions
            {
                //MaxDegreeOfParallelism = 1, // to ease debugging
                MaxDegreeOfParallelism = Environment.ProcessorCount
            };

            currentCombinations = 0;
            totalCombinations   = combinationCount;

            ParallelLoopResult parallelResult;

            try
            {
                const int batchSize = 4096;

                using (var equipmentBatchObjectPool = new ObjectPool <EquipmentBatch>(() => EquipmentBatch.Create(batchSize)))
                {
                    OrderablePartitioner <EquipmentBatch> partitioner = Partitioner.Create(generator.AllBatch(equipmentBatchObjectPool, cancellationToken), EnumerablePartitionerOptions.NoBuffering);

                    parallelResult = Parallel.ForEach(partitioner, parallelOptions, equipmentBatch =>
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            equipmentBatchObjectPool.PutObject(equipmentBatch);
                            return;
                        }

                        for (int i = 0; i < equipmentBatch.Size; i++)
                        {
                            EvaluateArmorSet(equipmentBatch.Equipment[i], data, results);
                        }

                        equipmentBatchObjectPool.PutObject(equipmentBatch);
                    });
                }
            }
            finally
            {
                generator.Reset();
            }

            return(results);
        }
예제 #16
0
        public void RunMap(string inputSplit, int numReducers, bool pipedInputs)
        {
            this.inputSplit = inputSplit;

            reader = factory.CreateRecordReader(this);

            if (reader != null)
            {
                valuee = new byte[0];
            }

            mapper = factory.CreateMapper(this);
            this.numReducers = numReducers;

            if (numReducers != 0)
            {
                reducer = factory.CreateCombiner(this);
                partitioner = factory.CreatePartitioner(this);
            }

            if (reducer != null)
            {
                long spillSize = 100;

                if (jobConf.ContainsKey("io.sort.mb"))
                {
                    spillSize = Convert.ToInt64(jobConf["io.sort.mb"]);
                }

                // TODO writer  = new CombineRunner (
            }

            hasTask = true;
        }
예제 #17
0
        public static void WVELcalculate(int NI, int NJ, int NK)
        {
            if (Program.ICW)
            {
                //computation of Coriolis-term
                Parallel.For(2, NI, Program.pOptions, i =>
                {
                    int NK_P = NK; int NJ_P = NJ;
                    for (int j = 2; j <= NJ_P - 1; j++)
                    {
                        float[] AP0_L   = Program.AP0[i][j];
                        double[] W2_L   = Program.W2[i][j];
                        double[] DIMW_L = Program.DIMW[i][j];
                        double[] W1_L   = Program.W1[i][j];
                        float[] F1W_L   = Program.F1W[i][j];
                        float[] F2W_L   = Program.F2W[i][j];
                        double[] QBZ_L  = Program.QBZ[i][j];
                        double[] QUN_L  = Program.QUN[i][j];
                        float[] RHO_L   = Program.RHO[i][j];
                        float[] RHOBZ_L = Program.RHOBZ[i][j];
                        double[] TBZ_L  = Program.TBZ[i][j];
                        double[] TN_L   = Program.TN[i][j];
                        double[] U1N_L  = Program.U1N[i][j];
                        float[] VOL_L   = Program.VOL[i][j];
                        double f1, f2;

                        for (int kn = 1; kn <= 2 * (NK_P - 1); kn++)
                        {
                            int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)

                            f1 = RHO_L[k] * Program.FH * U1N_L[k] * 0.5F * VOL_L[k];
                            f2 = 0;
                            if (Program.ICPSI == false)
                            {
                                f2 = 0.5F * VOL_L[k] * ((TN_L[k] + Program.TBZ1) * (1 + 0.00061 * QUN_L[k]) - (TBZ_L[k] * (1 + 0.00061 * QBZ_L[k]))) /
                                     (TBZ_L[k] * (1 + 0.00061 * QBZ_L[k])) * RHOBZ_L[k] * Program.GERD;
                            }


                            //no bouyancy, where terrain is smoothed at the border

                            /*
                             * if ((i < nr_cell_smooth) || (i > NI - nr_cell_smooth)||(j < nr_cell_smooth) || (j > NJ - nr_cell_smooth))
                             * {
                             *  f2 = 0;
                             * }
                             */

                            f1       += f2;
                            f1       += DIMW_L[kn];
                            F1W_L[kn] = (float)(AP0_L[k] * W1_L[k] + f1);
                            F2W_L[kn] = (float)(AP0_L[k] * W2_L[k] + f1);
                        }
                    }
                });

                int range_parallel = (int)(NI / Program.pOptions.MaxDegreeOfParallelism - (ITIME % 3) * 2);
                range_parallel = Math.Max(30 - (ITIME % 3) * 2, range_parallel); // min. 30 steps per processor
                range_parallel = Math.Min(NI, range_parallel);                   // if NI < range_parallel
                //Iterative solution using an implicit scheme and the TDMA or Thomas-Algorithm
                //Parallel.For(2, NI, Program.pOptions, i =>
                Parallel.ForEach(Partitioner.Create(2, NI, range_parallel), range =>
                {
                    int NK_P = NK; int NJ_P = NJ;
                    double DIM;
                    double[] PIM = new double[2 * NK];
                    double[] QIM = new double[2 * NK];
                    double help;

                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        for (int j = 2; j <= NJ_P - 1; j++)
                        {
                            float relaxv     = (float)(Program.RELAXV * Program.Relax_Border_factor[i][j]);
                            float[] AE2_L    = Program.AE2[i][j];
                            float[] AN2_L    = Program.AN2[i][j];
                            float[] AIM_L    = Program.AIM[i][j];
                            float[] AREAZX_L = Program.AREAZX[i][j];
                            float[] AREAZY_L = Program.AREAZY[i][j];
                            float[] AS1_L    = Program.AS1[i][j];
                            float[] AW1_L    = Program.AW1[i][j];
                            float[] BIM_L    = Program.BIM[i][j];
                            float[] CIM_L    = Program.CIM[i][j];
                            float[] F1W_L    = Program.F1W[i][j];
                            float[] F2W_L    = Program.F2W[i][j];
                            float[] RHO_L    = Program.RHO[i][j];
                            double[] W1N_L   = Program.W1N[i][j]; double[] W1Ni_L = Program.W1N[i + 1][j]; double[] W1NJ_P_L = Program.W1N[i][j + 1];
                            double[] W2N_L   = Program.W2N[i][j]; double[] W2Ni_L = Program.W2N[i - 1][j]; double[] W2NJ_P_L = Program.W2N[i][j - 1];
                            float USTxUSTV   = (float)(Program.UST[i][j] * Program.USTV[i][j]);

                            int m = 2;
                            for (int kn = 1; kn <= 2 * (NK_P - 1); kn++)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                                      //Coefficients for the lower half-cell
                                if (m == 2)
                                {
                                    DIM = AW1_L[k] * W2Ni_L[k] + AS1_L[k] * W2NJ_P_L[k] + F1W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W1N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }

                                    //Recurrence formula
                                    if (k > 1)
                                    {
                                        help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    }
                                    else
                                    {
                                        help    = 1 / AIM_L[kn];
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = DIM * help;
                                    }
                                    m--;
                                }

                                //Coefficients for the upper half-cell
                                else
                                {
                                    DIM = AE2_L[k] * W1Ni_L[k] + AN2_L[k] * W1NJ_P_L[k] + F2W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W2N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }

                                    //Recurrence formula
                                    help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                    PIM[kn] = BIM_L[kn] * help;
                                    QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    m       = 2;
                                }
                            }

                            //Obtain new W-components
                            m = 1;
                            for (int kn = 2 * (NK_P - 1); kn >= 1; kn--)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                if (m == 2)
                                {
                                    W1N_L[k] += (relaxv * (PIM[kn] * W2N_L[k] + QIM[kn] - W1N_L[k]));
                                    m--;
                                }
                                else
                                {
                                    W2N_L[k] += (relaxv * (PIM[kn] * W1N_L[k + 1] + QIM[kn] - W2N_L[k]));
                                    m         = 2;
                                }
                            }
                        }
                    }
                });

                range_parallel = (int)(NI / Program.pOptions.MaxDegreeOfParallelism - (ITIME % 3) * 2);
                range_parallel = Math.Max(30 - (ITIME % 3) * 2, range_parallel); // min. 30 steps per processor
                range_parallel = Math.Min(NI, range_parallel);                   // if NI < range_parallel
                //Iterative solution using an implicit scheme and the TDMA or Thomas-Algorithm
                // Parallel.For(2, NI, Program.pOptions, ih =>
                Parallel.ForEach(Partitioner.Create(2, NI, range_parallel), range =>
                {
                    int NK_P = NK; int NJ_P = NJ;
                    double DIM;
                    double[] PIM = new double[2 * NK_P];
                    double[] QIM = new double[2 * NK_P];
                    double help;

                    for (int ih = range.Item1; ih < range.Item2; ih++)
                    {
                        int i = NI + 1 - ih;
                        for (int j = NJ_P - 1; j >= 2; j--)
                        {
                            float relaxv     = (float)(Program.RELAXV * Program.Relax_Border_factor[i][j]);
                            float[] AE2_L    = Program.AE2[i][j];
                            float[] AN2_L    = Program.AN2[i][j];
                            float[] AIM_L    = Program.AIM[i][j];
                            float[] AREAZX_L = Program.AREAZX[i][j];
                            float[] AREAZY_L = Program.AREAZY[i][j];
                            float[] AS1_L    = Program.AS1[i][j];
                            float[] AW1_L    = Program.AW1[i][j];
                            float[] BIM_L    = Program.BIM[i][j];
                            float[] CIM_L    = Program.CIM[i][j];
                            float[] F1W_L    = Program.F1W[i][j];
                            float[] F2W_L    = Program.F2W[i][j];
                            float[] RHO_L    = Program.RHO[i][j];
                            double[] W1N_L   = Program.W1N[i][j]; double[] W1Ni_L = Program.W1N[i + 1][j]; double[] W1NJ_P_L = Program.W1N[i][j + 1];
                            double[] W2N_L   = Program.W2N[i][j]; double[] W2Ni_L = Program.W2N[i - 1][j]; double[] W2NJ_P_L = Program.W2N[i][j - 1];
                            float USTxUSTV   = (float)(Program.UST[i][j] * Program.USTV[i][j]);

                            int m = 2;
                            for (int kn = 1; kn <= 2 * (NK_P - 1); kn++)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                                      //Coefficients for the lower half-cell
                                if (m == 2)
                                {
                                    DIM = AW1_L[k] * W2Ni_L[k] + AS1_L[k] * W2NJ_P_L[k] + F1W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W1N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }


                                    //Recurrence formula
                                    if (k > 1)
                                    {
                                        help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    }
                                    else
                                    {
                                        help    = 1 / AIM_L[kn];
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = DIM * help;
                                    }
                                    m--;
                                }

                                //Coefficients for the upper half-cell
                                else
                                {
                                    DIM = AE2_L[k] * W1Ni_L[k] + AN2_L[k] * W1NJ_P_L[k] + F2W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W2N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }

                                    //Recurrence formula
                                    help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                    PIM[kn] = BIM_L[kn] * help;
                                    QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    m       = 2;
                                }
                            }

                            //Obtain new W-components
                            m = 1;
                            for (int kn = 2 * (NK_P - 1); kn >= 1; kn--)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                if (m == 2)
                                {
                                    W1N_L[k] += (relaxv * (PIM[kn] * W2N_L[k] + QIM[kn] - W1N_L[k]));
                                    m--;
                                }
                                else
                                {
                                    W2N_L[k] += (relaxv * (PIM[kn] * W1N_L[k + 1] + QIM[kn] - W2N_L[k]));
                                    m         = 2;
                                }
                            }
                        }
                    }
                });

                range_parallel = (int)(NJ / Program.pOptions.MaxDegreeOfParallelism - (ITIME % 3) * 2);
                range_parallel = Math.Max(30 - (ITIME % 3) * 2, range_parallel); // min. 30 steps per processor
                range_parallel = Math.Min(NJ, range_parallel);                   // if NI < range_parallel
                //Iterative solution using an implicit scheme and the TDMA or Thomas-Algorithm
                //Parallel.For(2, NJ, Program.pOptions, jh =>
                Parallel.ForEach(Partitioner.Create(2, NJ, range_parallel), range =>
                {
                    int NK_P = NK; int NI_P = NI;
                    double DIM;
                    double[] PIM = new double[2 * NK_P];
                    double[] QIM = new double[2 * NK_P];
                    double help;

                    for (int jh = range.Item1; jh < range.Item2; jh++)
                    {
                        int j = NJ + 1 - jh;
                        for (int i = NI_P - 1; i >= 2; i--)
                        {
                            float relaxv     = (float)(Program.RELAXV * Program.Relax_Border_factor[i][j]);
                            float[] AE2_L    = Program.AE2[i][j];
                            float[] AN2_L    = Program.AN2[i][j];
                            float[] AIM_L    = Program.AIM[i][j];
                            float[] AREAZX_L = Program.AREAZX[i][j];
                            float[] AREAZY_L = Program.AREAZY[i][j];
                            float[] AS1_L    = Program.AS1[i][j];
                            float[] AW1_L    = Program.AW1[i][j];
                            float[] BIM_L    = Program.BIM[i][j];
                            float[] CIM_L    = Program.CIM[i][j];
                            float[] F1W_L    = Program.F1W[i][j];
                            float[] F2W_L    = Program.F2W[i][j];
                            float[] RHO_L    = Program.RHO[i][j];
                            double[] W1N_L   = Program.W1N[i][j]; double[] W1Ni_L = Program.W1N[i + 1][j]; double[] W1NJ_P_L = Program.W1N[i][j + 1];
                            double[] W2N_L   = Program.W2N[i][j]; double[] W2Ni_L = Program.W2N[i - 1][j]; double[] W2NJ_P_L = Program.W2N[i][j - 1];
                            float USTxUSTV   = (float)(Program.UST[i][j] * Program.USTV[i][j]);

                            int m = 2;
                            for (int kn = 1; kn <= 2 * (NK_P - 1); kn++)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                                      //Coefficients for the lower half-cell
                                if (m == 2)
                                {
                                    DIM = AW1_L[k] * W2Ni_L[k] + AS1_L[k] * W2NJ_P_L[k] + F1W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W1N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }

                                    //Recurrence formula
                                    if (k > 1)
                                    {
                                        help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    }
                                    else
                                    {
                                        help    = 1 / AIM_L[kn];
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = DIM * help;
                                    }
                                    m--;
                                }

                                //Coefficients for the upper half-cell
                                else
                                {
                                    DIM = AE2_L[k] * W1Ni_L[k] + AN2_L[k] * W1NJ_P_L[k] + F2W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W2N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }

                                    //Recurrence formula
                                    help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                    PIM[kn] = BIM_L[kn] * help;
                                    QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    m       = 2;
                                }
                            }

                            //Obtain new W-components
                            m = 1;
                            for (int kn = 2 * (NK_P - 1); kn >= 1; kn--)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                if (m == 2)
                                {
                                    W1N_L[k] += (relaxv * (PIM[kn] * W2N_L[k] + QIM[kn] - W1N_L[k]));
                                    m--;
                                }
                                else
                                {
                                    W2N_L[k] += (relaxv * (PIM[kn] * W1N_L[k + 1] + QIM[kn] - W2N_L[k]));
                                    m         = 2;
                                }
                            }
                        }
                    }
                });

                range_parallel = (int)(NJ / Program.pOptions.MaxDegreeOfParallelism - (ITIME % 3) * 2);
                range_parallel = Math.Max(30 - (ITIME % 3) * 2, range_parallel); // min. 30 steps per processor
                range_parallel = Math.Min(NJ, range_parallel);                   // if NI < range_parallel
                                                                                 //Iterative solution using an implicit scheme and the TDMA or Thomas-Algorithm
                                                                                 // Parallel.For(2, NJ, Program.pOptions, j =>
                Parallel.ForEach(Partitioner.Create(2, NJ, range_parallel), range =>
                {
                    int NK_P = NK; int NI_P = NI;
                    double DIM;
                    double[] PIM = new double[2 * NK_P];
                    double[] QIM = new double[2 * NK_P];
                    double help;

                    for (int j = range.Item1; j < range.Item2; j++)
                    {
                        for (int i = 2; i <= NI_P - 1; i++)
                        {
                            float relaxv     = (float)(Program.RELAXV * Program.Relax_Border_factor[i][j]);
                            float[] AE2_L    = Program.AE2[i][j];
                            float[] AN2_L    = Program.AN2[i][j];
                            float[] AIM_L    = Program.AIM[i][j];
                            float[] AREAZX_L = Program.AREAZX[i][j];
                            float[] AREAZY_L = Program.AREAZY[i][j];
                            float[] AS1_L    = Program.AS1[i][j];
                            float[] AW1_L    = Program.AW1[i][j];
                            float[] BIM_L    = Program.BIM[i][j];
                            float[] CIM_L    = Program.CIM[i][j];
                            float[] F1W_L    = Program.F1W[i][j];
                            float[] F2W_L    = Program.F2W[i][j];
                            float[] RHO_L    = Program.RHO[i][j];
                            double[] W1N_L   = Program.W1N[i][j]; double[] W1Ni_L = Program.W1N[i + 1][j]; double[] W1NJ_P_L = Program.W1N[i][j + 1];
                            double[] W2N_L   = Program.W2N[i][j]; double[] W2Ni_L = Program.W2N[i - 1][j]; double[] W2NJ_P_L = Program.W2N[i][j - 1];
                            float USTxUSTV   = (float)(Program.UST[i][j] * Program.USTV[i][j]);

                            int m = 2;
                            for (int kn = 1; kn <= 2 * (NK_P - 1); kn++)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                                      //Coefficients for the lower half-cell
                                if (m == 2)
                                {
                                    DIM = AW1_L[k] * W2Ni_L[k] + AS1_L[k] * W2NJ_P_L[k] + F1W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W1N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }

                                    //Recurrence formula
                                    if (k > 1)
                                    {
                                        help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    }
                                    else
                                    {
                                        help    = 1 / AIM_L[kn];
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = DIM * help;
                                    }
                                    m--;
                                }

                                //Coefficients for the upper half-cell
                                else
                                {
                                    DIM = AE2_L[k] * W1Ni_L[k] + AN2_L[k] * W1NJ_P_L[k] + F2W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W2N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }

                                    //Recurrence formula
                                    help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                    PIM[kn] = BIM_L[kn] * help;
                                    QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    m       = 2;
                                }
                            }

                            //Obtain new W-components
                            m = 1;
                            for (int kn = 2 * (NK_P - 1); kn >= 1; kn--)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                if (m == 2)
                                {
                                    W1N_L[k] += (relaxv * (PIM[kn] * W2N_L[k] + QIM[kn] - W1N_L[k]));
                                    m--;
                                }
                                else
                                {
                                    W2N_L[k] += (relaxv * (PIM[kn] * W1N_L[k + 1] + QIM[kn] - W2N_L[k]));
                                    m         = 2;
                                }
                            }
                        }
                    }
                });

                range_parallel = (int)(NI / Program.pOptions.MaxDegreeOfParallelism - (ITIME % 3) * 2);
                range_parallel = Math.Max(30 - (ITIME % 3) * 2, range_parallel); // min. 30 steps per processor
                range_parallel = Math.Min(NI, range_parallel);                   // if NI < range_parallel
                                                                                 //Iterative solution using an implicit scheme and the TDMA or Thomas-Algorithm
                                                                                 //Parallel.For(2, NI, Program.pOptions, ih =>
                Parallel.ForEach(Partitioner.Create(2, NI, range_parallel), range =>
                {
                    int NK_P = NK; int NJ_P = NJ;
                    double DIM;
                    double[] PIM = new double[2 * NK_P];
                    double[] QIM = new double[2 * NK_P];
                    double help;

                    for (int ih = range.Item1; ih < range.Item2; ih++)
                    {
                        int i = NI + 1 - ih;
                        for (int j = 2; j <= NJ_P - 1; j++)
                        {
                            float relaxv     = (float)(Program.RELAXV * Program.Relax_Border_factor[i][j]);
                            float[] AE2_L    = Program.AE2[i][j];
                            float[] AN2_L    = Program.AN2[i][j];
                            float[] AIM_L    = Program.AIM[i][j];
                            float[] AREAZX_L = Program.AREAZX[i][j];
                            float[] AREAZY_L = Program.AREAZY[i][j];
                            float[] AS1_L    = Program.AS1[i][j];
                            float[] AW1_L    = Program.AW1[i][j];
                            float[] BIM_L    = Program.BIM[i][j];
                            float[] CIM_L    = Program.CIM[i][j];
                            float[] F1W_L    = Program.F1W[i][j];
                            float[] F2W_L    = Program.F2W[i][j];
                            float[] RHO_L    = Program.RHO[i][j];
                            double[] W1N_L   = Program.W1N[i][j]; double[] W1Ni_L = Program.W1N[i + 1][j]; double[] W1NJ_P_L = Program.W1N[i][j + 1];
                            double[] W2N_L   = Program.W2N[i][j]; double[] W2Ni_L = Program.W2N[i - 1][j]; double[] W2NJ_P_L = Program.W2N[i][j - 1];
                            float USTxUSTV   = (float)(Program.UST[i][j] * Program.USTV[i][j]);

                            int m = 2;
                            for (int kn = 1; kn <= 2 * (NK_P - 1); kn++)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                                      //Coefficients for the lower half-cell
                                if (m == 2)
                                {
                                    DIM = AW1_L[k] * W2Ni_L[k] + AS1_L[k] * W2NJ_P_L[k] + F1W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W1N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }

                                    //Recurrence formula
                                    if (k > 1)
                                    {
                                        help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    }
                                    else
                                    {
                                        help    = 1 / AIM_L[kn];
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = DIM * help;
                                    }
                                    m--;
                                }

                                //Coefficients for the upper half-cell
                                else
                                {
                                    DIM = AE2_L[k] * W1Ni_L[k] + AN2_L[k] * W1NJ_P_L[k] + F2W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W2N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }

                                    //Recurrence formula
                                    help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                    PIM[kn] = BIM_L[kn] * help;
                                    QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    m       = 2;
                                }
                            }

                            //Obtain new W-components
                            m = 1;
                            for (int kn = 2 * (NK_P - 1); kn >= 1; kn--)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                if (m == 2)
                                {
                                    W1N_L[k] += (relaxv * (PIM[kn] * W2N_L[k] + QIM[kn] - W1N_L[k]));
                                    m--;
                                }
                                else
                                {
                                    W2N_L[k] += (relaxv * (PIM[kn] * W1N_L[k + 1] + QIM[kn] - W2N_L[k]));
                                    m         = 2;
                                }
                            }
                        }
                    }
                });

                range_parallel = (int)(NI / Program.pOptions.MaxDegreeOfParallelism - (ITIME % 3) * 2);
                range_parallel = Math.Max(30 - (ITIME % 3) * 2, range_parallel); // min. 30 steps per processor
                range_parallel = Math.Min(NI, range_parallel);                   // if NI < range_parallel
                                                                                 //Iterative solution using an implicit scheme and the TDMA or Thomas-Algorithm
                Parallel.For(2, NI, Program.pOptions, i =>
                {
                    int NK_P = NK; int NJ_P = NJ;
                    double DIM;
                    double[] PIM = new double[2 * NK_P];
                    double[] QIM = new double[2 * NK_P];
                    double help;

                    for (int j = NJ_P - 1; j >= 2; j--)
                    {
                        float relaxv     = (float)(Program.RELAXV * Program.Relax_Border_factor[i][j]);
                        float[] AE2_L    = Program.AE2[i][j];
                        float[] AN2_L    = Program.AN2[i][j];
                        float[] AIM_L    = Program.AIM[i][j];
                        float[] AREAZX_L = Program.AREAZX[i][j];
                        float[] AREAZY_L = Program.AREAZY[i][j];
                        float[] AS1_L    = Program.AS1[i][j];
                        float[] AW1_L    = Program.AW1[i][j];
                        float[] BIM_L    = Program.BIM[i][j];
                        float[] CIM_L    = Program.CIM[i][j];
                        float[] F1W_L    = Program.F1W[i][j];
                        float[] F2W_L    = Program.F2W[i][j];
                        float[] RHO_L    = Program.RHO[i][j];
                        double[] W1N_L   = Program.W1N[i][j]; double[] W1Ni_L = Program.W1N[i + 1][j]; double[] W1NJ_P_L = Program.W1N[i][j + 1];
                        double[] W2N_L   = Program.W2N[i][j]; double[] W2Ni_L = Program.W2N[i - 1][j]; double[] W2NJ_P_L = Program.W2N[i][j - 1];
                        float USTxUSTV   = (float)(Program.UST[i][j] * Program.USTV[i][j]);

                        int m = 2;
                        for (int kn = 1; kn <= 2 * (NK_P - 1); kn++)
                        {
                            int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                            //Coefficients for the lower half-cell
                            if (m == 2)
                            {
                                DIM = AW1_L[k] * W2Ni_L[k] + AS1_L[k] * W2NJ_P_L[k] + F1W_L[kn];
                                if (k == 1)
                                {
                                    DIM -= RHO_L[k] * W1N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                }

                                //Recurrence formula
                                if (k > 1)
                                {
                                    help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                    PIM[kn] = BIM_L[kn] * help;
                                    QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                }
                                else
                                {
                                    help    = 1 / AIM_L[kn];
                                    PIM[kn] = BIM_L[kn] * help;
                                    QIM[kn] = DIM * help;
                                }
                                m--;
                            }

                            //Coefficients for the upper half-cell
                            else
                            {
                                DIM = AE2_L[k] * W1Ni_L[k] + AN2_L[k] * W1NJ_P_L[k] + F2W_L[kn];
                                if (k == 1)
                                {
                                    DIM -= RHO_L[k] * W2N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                }

                                //Recurrence formula
                                help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                PIM[kn] = BIM_L[kn] * help;
                                QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                m       = 2;
                            }
                        }

                        //Obtain new W-components
                        m = 1;
                        for (int kn = 2 * (NK_P - 1); kn >= 1; kn--)
                        {
                            int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                            if (m == 2)
                            {
                                W1N_L[k] += (relaxv * (PIM[kn] * W2N_L[k] + QIM[kn] - W1N_L[k]));
                                m--;
                            }
                            else
                            {
                                W2N_L[k] += (relaxv * (PIM[kn] * W1N_L[k + 1] + QIM[kn] - W2N_L[k]));
                                m         = 2;
                            }
                        }
                    }
                });

                range_parallel = (int)(NJ / Program.pOptions.MaxDegreeOfParallelism - (ITIME % 3) * 2);
                range_parallel = Math.Max(30 - (ITIME % 3) * 2, range_parallel); // min. 30 steps per processor
                range_parallel = Math.Min(NJ, range_parallel);                   // if NI < range_parallel
                //Iterative solution using an implicit scheme and the TDMA or Thomas-Algorithm
                //Parallel.For(2, NJ, Program.pOptions, jh =>
                Parallel.ForEach(Partitioner.Create(2, NJ, range_parallel), range =>
                {
                    int NK_P = NK; int NI_P = NI;
                    double DIM;
                    double[] PIM = new double[2 * NK_P];
                    double[] QIM = new double[2 * NK_P];
                    double help;

                    for (int jh = range.Item1; jh < range.Item2; jh++)
                    {
                        int j = NJ + 1 - jh;
                        for (int i = 2; i <= NI_P - 1; i++)
                        {
                            float relaxv     = (float)(Program.RELAXV * Program.Relax_Border_factor[i][j]);
                            float[] AE2_L    = Program.AE2[i][j];
                            float[] AN2_L    = Program.AN2[i][j];
                            float[] AIM_L    = Program.AIM[i][j];
                            float[] AREAZX_L = Program.AREAZX[i][j];
                            float[] AREAZY_L = Program.AREAZY[i][j];
                            float[] AS1_L    = Program.AS1[i][j];
                            float[] AW1_L    = Program.AW1[i][j];
                            float[] BIM_L    = Program.BIM[i][j];
                            float[] CIM_L    = Program.CIM[i][j];
                            float[] F1W_L    = Program.F1W[i][j];
                            float[] F2W_L    = Program.F2W[i][j];
                            float[] RHO_L    = Program.RHO[i][j];
                            double[] W1N_L   = Program.W1N[i][j]; double[] W1Ni_L = Program.W1N[i + 1][j]; double[] W1NJ_P_L = Program.W1N[i][j + 1];
                            double[] W2N_L   = Program.W2N[i][j]; double[] W2Ni_L = Program.W2N[i - 1][j]; double[] W2NJ_P_L = Program.W2N[i][j - 1];
                            float USTxUSTV   = (float)(Program.UST[i][j] * Program.USTV[i][j]);

                            int m = 2;
                            for (int kn = 1; kn <= 2 * (NK_P - 1); kn++)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                                      //Coefficients for the lower half-cell
                                if (m == 2)
                                {
                                    DIM = AW1_L[k] * W2Ni_L[k] + AS1_L[k] * W2NJ_P_L[k] + F1W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W1N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }

                                    //Recurrence formula
                                    if (k > 1)
                                    {
                                        help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    }
                                    else
                                    {
                                        help    = 1 / AIM_L[kn];
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = DIM * help;
                                    }
                                    m--;
                                }

                                //Coefficients for the upper half-cell
                                else
                                {
                                    DIM = AE2_L[k] * W1Ni_L[k] + AN2_L[k] * W1NJ_P_L[k] + F2W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W2N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }

                                    //Recurrence formula
                                    help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                    PIM[kn] = BIM_L[kn] * help;
                                    QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    m       = 2;
                                }
                            }

                            //Obtain new W-components
                            m = 1;
                            for (int kn = 2 * (NK_P - 1); kn >= 1; kn--)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                if (m == 2)
                                {
                                    W1N_L[k] += (relaxv * (PIM[kn] * W2N_L[k] + QIM[kn] - W1N_L[k]));
                                    m--;
                                }
                                else
                                {
                                    W2N_L[k] += (relaxv * (PIM[kn] * W1N_L[k + 1] + QIM[kn] - W2N_L[k]));
                                    m         = 2;
                                }
                            }
                        }
                    }
                });

                range_parallel = (int)(NJ / Program.pOptions.MaxDegreeOfParallelism - (ITIME % 3) * 2);
                range_parallel = Math.Max(30 - (ITIME % 3) * 2, range_parallel); // min. 30 steps per processor
                range_parallel = Math.Min(NJ, range_parallel);                   // if NI < range_parallel
                                                                                 //Iterative solution using an implicit scheme and the TDMA or Thomas-Algorithm
                                                                                 //Parallel.For(2, NJ, Program.pOptions, j =>
                Parallel.ForEach(Partitioner.Create(2, NJ, range_parallel), range =>
                {
                    int NK_P = NK; int NI_P = NI;
                    double DIM;
                    double[] PIM = new double[2 * NK_P];
                    double[] QIM = new double[2 * NK_P];
                    double help;

                    for (int j = range.Item1; j < range.Item2; j++)
                    {
                        for (int i = 2; i <= NI_P - 1; i++)
                        {
                            float relaxv     = (float)(Program.RELAXV * Program.Relax_Border_factor[i][j]);
                            float[] AE2_L    = Program.AE2[i][j];
                            float[] AN2_L    = Program.AN2[i][j];
                            float[] AIM_L    = Program.AIM[i][j];
                            float[] AREAZX_L = Program.AREAZX[i][j];
                            float[] AREAZY_L = Program.AREAZY[i][j];
                            float[] AS1_L    = Program.AS1[i][j];
                            float[] AW1_L    = Program.AW1[i][j];
                            float[] BIM_L    = Program.BIM[i][j];
                            float[] CIM_L    = Program.CIM[i][j];
                            float[] F1W_L    = Program.F1W[i][j];
                            float[] F2W_L    = Program.F2W[i][j];
                            float[] RHO_L    = Program.RHO[i][j];
                            double[] W1N_L   = Program.W1N[i][j]; double[] W1Ni_L = Program.W1N[i + 1][j]; double[] W1NJ_P_L = Program.W1N[i][j + 1];
                            double[] W2N_L   = Program.W2N[i][j]; double[] W2Ni_L = Program.W2N[i - 1][j]; double[] W2NJ_P_L = Program.W2N[i][j - 1];
                            float USTxUSTV   = (float)(Program.UST[i][j] * Program.USTV[i][j]);

                            int m = 2;
                            for (int kn = 1; kn <= 2 * (NK_P - 1); kn++)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                                      //Coefficients for the lower half-cell
                                if (m == 2)
                                {
                                    DIM = AW1_L[k] * W2Ni_L[k] + AS1_L[k] * W2NJ_P_L[k] + F1W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W1N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }

                                    //Recurrence formula
                                    if (k > 1)
                                    {
                                        help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    }
                                    else
                                    {
                                        help    = 1 / AIM_L[kn];
                                        PIM[kn] = BIM_L[kn] * help;
                                        QIM[kn] = DIM * help;
                                    }
                                    m--;
                                }

                                //Coefficients for the upper half-cell
                                else
                                {
                                    DIM = AE2_L[k] * W1Ni_L[k] + AN2_L[k] * W1NJ_P_L[k] + F2W_L[kn];
                                    if (k == 1)
                                    {
                                        DIM -= RHO_L[k] * W2N_L[k] * USTxUSTV * MathF.Sqrt(Pow2(AREAZX_L[k]) + Pow2(AREAZY_L[k]));
                                    }

                                    //Recurrence formula
                                    help    = 1 / (AIM_L[kn] - CIM_L[kn] * PIM[kn - 1]);
                                    PIM[kn] = BIM_L[kn] * help;
                                    QIM[kn] = (DIM + CIM_L[kn] * QIM[kn - 1]) * help;
                                    m       = 2;
                                }
                            }

                            //Obtain new W-components
                            m = 1;
                            for (int kn = 2 * (NK_P - 1); kn >= 1; kn--)
                            {
                                int k = 1 + kn >> 1;  // (int) (kn * 0.5F + 0.5F)
                                if (m == 2)
                                {
                                    W1N_L[k] += (relaxv * (PIM[kn] * W2N_L[k] + QIM[kn] - W1N_L[k]));
                                    m--;
                                }
                                else
                                {
                                    W2N_L[k] += (relaxv * (PIM[kn] * W1N_L[k + 1] + QIM[kn] - W2N_L[k]));
                                    m         = 2;
                                }
                            }
                        }
                    }
                });
            }
        }
예제 #18
0
 public static IEnumerable <object[]> AggregateExceptionData(int[] counts)
 {
     foreach (object[] results in UnorderedSources.Ranges(counts.Cast <int>()))
     {
         Labeled <ParallelQuery <int> > query = (Labeled <ParallelQuery <int> >)results[0];
         if (query.ToString().StartsWith("Partitioner"))
         {
             yield return(new object[] { Labeled.Label(query.ToString(), Partitioner.Create(UnorderedSources.GetRangeArray(0, (int)results[1]), false).AsParallel()), results[1] });
         }
         else if (query.ToString().StartsWith("Enumerable.Range"))
         {
             yield return(new object[] { Labeled.Label(query.ToString(), new StrictPartitioner <int>(Partitioner.Create(Enumerable.Range(0, (int)results[1]), EnumerablePartitionerOptions.None), (int)results[1]).AsParallel()), results[1] });
         }
         else
         {
             yield return(results);
         }
     }
 }
예제 #19
0
            private QuerySettings _settings;             // Settings collected from the query

            internal PartitionerQueryOperatorResults(Partitioner <TElement> partitioner, QuerySettings settings)
            {
                _partitioner = partitioner;
                _settings    = settings;
            }
 private void Start()
 {
     policy      = new FrontSpacePolicy();
     partitioner = new Partitioner();
     partitioner.Init();
 }
        /// <summary>
        ///     Selects an item (such as Max or Min).
        /// </summary>
        /// <param name="fromInclusive">Starting index of the loop.</param>
        /// <param name="toExclusive">Ending index of the loop</param>
        /// <param name="select">The function to select items over a subset.</param>
        /// <param name="reduce">The function to select the item of selection from the subsets.</param>
        /// <returns>The selected value.</returns>
        public static T Aggregate <T>(int fromInclusive, int toExclusive, Func <int, T> select, Func <T[], T> reduce)
        {
            if (select == null)
            {
                throw new ArgumentNullException(nameof(select));
            }

            if (reduce == null)
            {
                throw new ArgumentNullException(nameof(reduce));
            }

            // Special case: no action
            if (fromInclusive >= toExclusive)
            {
                return(reduce(new T[0]));
            }

            // Special case: single action, inline
            if (fromInclusive == toExclusive - 1)
            {
                return(reduce(new[] { select(fromInclusive) }));
            }

            // Special case: straight execution without parallelism
            if (Control.MaxDegreeOfParallelism < 2)
            {
                var mapped = new T[toExclusive - fromInclusive];
                for (var k = 0; k < mapped.Length; k++)
                {
                    mapped[k] = select(k + fromInclusive);
                }

                return(reduce(mapped));
            }

            // Common case
            var intermediateResults = new List <T>();
            var syncLock            = new object();

            Parallel.ForEach(
                Partitioner.Create(fromInclusive, toExclusive),
                CreateParallelOptions(),
                () => new List <T>(),
                (range, loop, localData) =>
            {
                var mapped = new T[range.Item2 - range.Item1];
                for (var k = 0; k < mapped.Length; k++)
                {
                    mapped[k] = select(k + range.Item1);
                }

                localData.Add(reduce(mapped));
                return(localData);
            },
                localResult =>
            {
                lock (syncLock)
                {
                    intermediateResults.Add(reduce(localResult.ToArray()));
                }
            });
            return(reduce(intermediateResults.ToArray()));
        }
예제 #22
0
        public async Task Generate()
        {
            try
            {
                if (string.IsNullOrEmpty(ProjectFilePath))
                {
                    Log.Exception("ProjectFilePath is empty: " + Project.ToString());
                    return;
                }

                ProjectDestinationFolder = GetProjectDestinationPath(Project, SolutionGenerator.SolutionDestinationFolder);
                if (ProjectDestinationFolder == null)
                {
                    Log.Exception("Errors evaluating project: " + Project.Id);
                    return;
                }

                Log.Write(ProjectDestinationFolder, ConsoleColor.DarkCyan);

                ProjectSourcePath = Paths.MakeRelativeToFolder(ProjectFilePath, SolutionGenerator.SolutionSourceFolder);

                if (File.Exists(Path.Combine(ProjectDestinationFolder, Constants.DeclaredSymbolsFileName + ".txt")))
                {
                    // apparently someone already generated a project with this assembly name - their assembly wins
                    Log.Exception(string.Format(
                                      "A project with assembly name {0} was already generated, skipping current project: {1}",
                                      this.AssemblyName,
                                      this.ProjectFilePath), isSevere: false);
                    return;
                }

                if (Configuration.CreateFoldersOnDisk)
                {
                    Directory.CreateDirectory(ProjectDestinationFolder);
                }

                var documents = Project.Documents.Where(IncludeDocument).ToList();

                var generationTasks = Partitioner.Create(documents)
                                      .GetPartitions(Environment.ProcessorCount)
                                      .Select(partition =>
                                              Task.Run(async() =>
                {
                    using (partition)
                    {
                        while (partition.MoveNext())
                        {
                            await GenerateDocument(partition.Current);
                        }
                    }
                }));

                await Task.WhenAll(generationTasks);

                foreach (var document in documents)
                {
                    OtherFiles.Add(Paths.GetRelativeFilePathInProject(document));
                }

                if (Configuration.WriteProjectAuxiliaryFilesToDisk)
                {
                    GenerateProjectFile();
                    GenerateDeclarations();
                    GenerateBaseMembers();
                    GenerateImplementedInterfaceMembers();
                    GenerateProjectInfo();
                    GenerateReferencesDataFiles(
                        this.SolutionGenerator.SolutionDestinationFolder,
                        ReferencesByTargetAssemblyAndSymbolId);
                    GenerateSymbolIDToListOfDeclarationLocationsMap(
                        ProjectDestinationFolder,
                        SymbolIDToListOfLocationsMap);
                    GenerateReferencedAssemblyList();
                    GenerateUsedReferencedAssemblyList();
                    GenerateProjectExplorer();
                    GenerateNamespaceExplorer();
                    GenerateIndex();
                }

                var compilation = Project.GetCompilationAsync().Result;
                var diagnostics = compilation.GetDiagnostics().Select(d => d.ToString()).ToArray();
                if (diagnostics.Length > 0)
                {
                    var diagnosticsTxt = Path.Combine(this.ProjectDestinationFolder, "diagnostics.txt");
                    File.WriteAllLines(diagnosticsTxt, diagnostics);
                }
            }
            catch (Exception ex)
            {
                Log.Exception(ex, "Project generation failed for: " + ProjectSourcePath);
            }
        }
예제 #23
0
        /// <summary>
        /// 进行Npp条带去除
        /// </summary>
        /// <param name="srcImgRaster"></param>
        /// <param name="i"></param>
        /// <param name="srcBandData"></param>
        /// <param name="solarZenithData"></param>
        /// <param name="srcBlockImgSize"></param>
        /// <param name="angleSize"></param>
        protected override void DoRadiation(AbstractWarpDataset srcImgRaster, int i, ushort[] srcBandData,
                                            float[] solarZenithData, Size srcBlockImgSize, Size angleSize)
        {
            //定标功能
            Parallel.ForEach(Partitioner.Create(0, srcBandData.Length), range =>
            {
                float temp = 0;
                for (int ii = range.Item1; ii < range.Item2; ii++)
                {
                    if (srcBandData[ii] != 0)
                    {
                        temp = srcBandData[ii] * _factors[i * 2] + _factors[i * 2 + 1];
                        if (temp < 2)
                        {
                            srcBandData[ii] = temp < 0 ? (ushort)0 : (ushort)(temp * 1000 + 0.5);
                        }
                        else
                        {
                            srcBandData[ii] = (ushort)(temp * 10 + 0.5);
                        }
                    }
                }
            });

            //监测0值的上下值,求平均
            int height = srcBlockImgSize.Height;
            int width  = srcBlockImgSize.Width;
            var timer  = System.Diagnostics.Stopwatch.StartNew();

            if (false)
            {
                Parallel.ForEach(Partitioner.Create(0, srcBlockImgSize.Width), range =>
                {
                    ushort[] temp           = new ushort[height];
                    List <ushort> fillValue = new List <ushort>();
                    for (int ii = range.Item1; ii < range.Item2; ii++)
                    {
                        int noValuePixelCount = 0;
                        for (int j = 0; j < height; j++)
                        {
                            temp[j] = srcBandData[j * width + ii];
                            if (temp[j] == 0)
                            {
                                noValuePixelCount++;
                            }
                        }

                        if (noValuePixelCount == 0)
                        {
                            continue;
                        }
                        for (int k = 0; k < 4; k++)
                        {
                            for (int t = 0; t < height; t++)
                            {
                                if (temp[t] != 0)
                                {
                                    continue;
                                }
                                if (t == 0)
                                {
                                    if (temp[t + 1] != 0)
                                    {
                                        temp[t] = temp[t + 1];
                                    }
                                }
                                else if (t == height - 1)
                                {
                                    if (temp[t - 1] != 0)
                                    {
                                        temp[t] = temp[t - 1];
                                    }
                                }
                                else
                                {
                                    if (temp[t + 1] != 0)
                                    {
                                        temp[t] = temp[t + 1];
                                    }
                                    else if (temp[t - 1] != 0)
                                    {
                                        temp[t] = temp[t - 1];
                                    }
                                }
                            }
                        }

                        //结束修改
                        for (int j = 0; j < height; j++)
                        {
                            srcBandData[j * width + ii] = temp[j];
                        }
                    }

                    temp = null;
                });
            }
            else
            {
                for (int t = 0; t < 4; t++)
                {
                    int    validCount = 0;
                    double validSum   = 0;
                    for (int ii = 1; ii < height - 1; ii++)
                    {
                        for (int jj = 1; jj < width - 1; jj++)
                        {
                            if (srcBandData[ii * width + jj] == 0)
                            {
                                validCount = 0;
                                validSum   = 0;
                                for (int q = -1; q <= 1; q++)
                                {
                                    for (int w = -1; w <= 1; w++)
                                    {
                                        if (q != 0 && w != 0 && srcBandData[(ii + q) * width + jj + w] != 0)
                                        {
                                            validCount++;
                                            validSum += srcBandData[(ii + q) * width + jj + w];
                                        }
                                    }
                                }

                                if (validCount != 0)
                                {
                                    srcBandData[ii * width + jj] = (ushort)(validSum / validCount + 0.5);
                                }
                            }
                        }
                    }
                }

                {
                    int    ii         = 0;
                    int    jj         = 0;
                    int    validCount = 0;
                    double validSum   = 0;
                    //第一行
                    for (jj = 1; jj < width - 1; jj++)
                    {
                        if (srcBandData[ii * width + jj] == 0)
                        {
                            validCount = 0;
                            validSum   = 0;
                            for (int q = 0; q <= 1; q++)
                            {
                                for (int w = -1; w <= 1; w++)
                                {
                                    if (q != 0 && w != 0 && srcBandData[(ii + q) * width + jj + w] != 0)
                                    {
                                        validCount++;
                                        validSum += srcBandData[(ii + q) * width + jj + w];
                                    }
                                }
                            }

                            if (validCount != 0)
                            {
                                srcBandData[ii * width + jj] = (ushort)(validSum / validCount + 0.5);
                            }
                        }
                    }

                    ii = height - 1;
                    //最后一行
                    for (jj = 1; jj < width - 1; jj++)
                    {
                        if (srcBandData[ii * width + jj] == 0)
                        {
                            validCount = 0;
                            validSum   = 0;
                            for (int q = -1; q <= 0; q++)
                            {
                                for (int w = -1; w <= 1; w++)
                                {
                                    if (q != 0 && w != 0 && srcBandData[(ii + q) * width + jj + w] != 0)
                                    {
                                        validCount++;
                                        validSum += srcBandData[(ii + q) * width + jj + w];
                                    }
                                }
                            }

                            if (validCount != 0)
                            {
                                srcBandData[ii * width + jj] = (ushort)(validSum / validCount + 0.5);
                            }
                        }
                    }

                    jj = 0;
                    //第一列
                    for (ii = 1; ii < height - 1; ii++)
                    {
                        if (srcBandData[ii * width + jj] == 0)
                        {
                            validCount = 0;
                            validSum   = 0;
                            for (int q = -1; q <= 1; q++)
                            {
                                for (int w = 0; w <= 1; w++)
                                {
                                    if (q != 0 && w != 0 && srcBandData[(ii + q) * width + jj + w] != 0)
                                    {
                                        validCount++;
                                        validSum += srcBandData[(ii + q) * width + jj + w];
                                    }
                                }
                            }

                            if (validCount != 0)
                            {
                                srcBandData[ii * width + jj] = (ushort)(validSum / validCount + 0.5);
                            }
                        }
                    }

                    //最后一列
                    jj = width - 1;
                    for (ii = 1; ii < height - 1; ii++)
                    {
                        if (srcBandData[ii * width + jj] == 0)
                        {
                            validCount = 0;
                            validSum   = 0;
                            for (int q = -1; q <= 1; q++)
                            {
                                for (int w = -1; w <= 0; w++)
                                {
                                    if (q != 0 && w != 0 && srcBandData[(ii + q) * width + jj + w] != 0)
                                    {
                                        validCount++;
                                        validSum += srcBandData[(ii + q) * width + jj + w];
                                    }
                                }
                            }

                            if (validCount != 0)
                            {
                                srcBandData[ii * width + jj] = (ushort)(validSum / validCount + 0.5);
                            }
                        }
                    }
                }
            }

            //Console.WriteLine("花费时间" + timer.ElapsedMilliseconds);
        }
예제 #24
0
        public QuartzEndpointDefinition(QuartzConfiguration configuration)
        {
            _configuration = configuration;

            Partition = new Partitioner(_configuration.ConcurrentMessageLimit, new Murmur3UnsafeHashGenerator());
        }
예제 #25
0
        /// <summary>
        /// Loads all scan data from a Thermo .raw file.
        /// </summary>
        public static ThermoRawFileReaderData LoadAllStaticData(string filePath, IFilteringParams filterParams = null, int maxThreads = -1)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException();
            }

            Loaders.LoadElements();

            // I don't know why this line needs to be here, but it does...
            var temp = RawFileReaderAdapter.FileFactory(filePath);

            var threadManager   = RawFileReaderFactory.CreateThreadManager(filePath);
            var rawFileAccessor = threadManager.CreateThreadAccessor();

            if (!rawFileAccessor.IsOpen)
            {
                throw new MzLibException("Unable to access RAW file!");
            }

            if (rawFileAccessor.IsError)
            {
                throw new MzLibException("Error opening RAW file!");
            }

            if (rawFileAccessor.InAcquisition)
            {
                throw new MzLibException("RAW file still being acquired!");
            }

            rawFileAccessor.SelectInstrument(Device.MS, 1);
            var msDataScans = new MsDataScan[rawFileAccessor.RunHeaderEx.LastSpectrum];

            Parallel.ForEach(Partitioner.Create(0, msDataScans.Length), new ParallelOptions {
                MaxDegreeOfParallelism = maxThreads
            }, (fff, loopState) =>
            {
                IRawDataPlus myThreadDataReader = threadManager.CreateThreadAccessor();
                myThreadDataReader.SelectInstrument(Device.MS, 1);

                for (int s = fff.Item1; s < fff.Item2; s++)
                {
                    try
                    {
                        var scan       = GetOneBasedScan(myThreadDataReader, filterParams, s + 1);
                        msDataScans[s] = scan;
                    }
                    catch (Exception ex)
                    {
                        throw new MzLibException("Error reading scan " + (s + 1) + ": " + ex.Message);
                    }
                }
            });

            rawFileAccessor.Dispose();

            string sendCheckSum;

            using (FileStream stream = File.OpenRead(filePath))
            {
                using (SHA1Managed sha = new SHA1Managed())
                {
                    byte[] checksum = sha.ComputeHash(stream);
                    sendCheckSum = BitConverter.ToString(checksum)
                                   .Replace("-", string.Empty);
                }
            }

            SourceFile sourceFile = new SourceFile(
                @"Thermo nativeID format",
                @"Thermo RAW format",
                sendCheckSum,
                @"SHA-1",
                filePath,
                Path.GetFileNameWithoutExtension(filePath));

            return(new ThermoRawFileReaderData(msDataScans, sourceFile));
        }
        /// <inheritdoc />
        public override unsafe void DoStepOpenCL(OpenCLDispatcher dispatcher, OpenCLDevice device)
        {
            var timerTotal = Stopwatch.StartNew();

            OpenCLKernelSet kernelSet = dispatcher.Compile(device, "CellBasedSim.cl");

            currentStep++;

            // Increase random seed
            randomSeed++;

            int cellsLength      = Current.Cells.Length;
            int junctionsLength  = Current.Junctions.Length;
            int generatorsLength = Current.Generators.Length;
            int carsLength       = Current.Cars.Length;

            // Reset waiting count on every junction
            Parallel.ForEach(Partitioner.Create(0, Current.Junctions.Length), range => {
                for (int i = range.Item1; i < range.Item2; i++)
                {
                    Current.Junctions[i].WaitingCount = 0;
                }
            });

            fixed(Cell *cellsPtr = Current.Cells)
            fixed(CellToCar * cellsToCarPtr = Current.CellsToCar)
            fixed(Junction * junctionsPtr   = Current.Junctions)
            fixed(Generator * generatorsPtr = Current.Generators)
            fixed(Car * carsPtr             = Current.Cars)
            fixed(float *randomPtr          = random)
            {
                var timer = Stopwatch.StartNew();

                // Process all cars
                kernelSet["DoStepCar"]
                .BindBuffer(cellsPtr, sizeof(Cell) * cellsLength, true)
                .BindBuffer(cellsToCarPtr, sizeof(CellToCar) * cellsLength, false)
                .BindValue(cellsLength)

                .BindBuffer(junctionsPtr, sizeof(Junction) * junctionsLength, false)
                .BindValue(junctionsLength)

                .BindBuffer(carsPtr, sizeof(Car) * carsLength, false)
                .BindValue(carsLength)

                .BindBuffer(randomPtr, sizeof(float) * randomLength, true)
                .BindValue(randomLength)
                .BindValue(randomSeed)

                .Run(carsLength)
                .Finish();

                LastTimeCars = timer.Elapsed;
                timer.Restart();

                // Process all generators
                if ((flags & SimulationFlags.NoSpawn) == 0)
                {
                    kernelSet["SpawnCars"]
                    .BindBuffer(cellsPtr, sizeof(Cell) * cellsLength, true)
                    .BindBuffer(cellsToCarPtr, sizeof(CellToCar) * cellsLength, false)
                    .BindValue(cellsLength)

                    .BindBuffer(generatorsPtr, sizeof(Generator) * generatorsLength, false)
                    .BindValue(generatorsLength)

                    .BindBuffer(carsPtr, sizeof(Car) * carsLength, false)
                    .BindValue(carsLength)

                    .BindBuffer(randomPtr, sizeof(float) * randomLength, true)
                    .BindValue(randomLength)
                    .BindValue(randomSeed)

                    .Run(generatorsLength)
                    .Finish();
                }


                LastTimeGenerators = timer.Elapsed;
            }

            LastTimeTotal = timerTotal.Elapsed;
        }
예제 #27
0
        public TEntity[] CreateEntities <TEntity>(DataTable data, QueryBuilder <TEntity> builder) where TEntity : Entity, new()
        {
            var fieldCount       = builder.PropertySetter.Length;
            var arrayFieldCount  = 0;
            var classFieldCount  = 0;
            var structFieldCount = 0;

            if (data == null || data.Rows.Count == 0)
            {
                return(new TEntity[0]);
            }

            var entity = new TEntity();

            for (var i = 0; i < builder.Properties.Length; i++)
            {
                if (builder.Properties[i].PropertyType.IsArray)
                {
                    var arr = builder.Properties[i].GetValue(new TEntity()) as Array;

                    arrayFieldCount += arr.Length - 1;
                }
                else if (builder.Properties[i].PropertyType.IsCustomClass())
                {
                    classFieldCount += builder.Properties[i].PropertyType.GetReadWriteProperties().Length - 1;
                }
                else if (builder.Properties[i].PropertyType.IsCustomStruct())
                {
                    structFieldCount += builder.Properties[i].PropertyType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Length - 1;
                }
            }

            if (data.Columns.Count != (fieldCount + arrayFieldCount + classFieldCount + structFieldCount))
            {
                Trace.TraceError(string.Format("Table '{0}' (Column/Property count mismatch)", Pluralize <TEntity>()));
                Trace.TraceError(string.Format("Columns '{0}'", data.Columns.Count));
                Trace.TraceError(string.Format("Properties '{0}'", fieldCount + arrayFieldCount + classFieldCount + structFieldCount));
                Trace.WriteLine("Press a key to continue loading.");

                Console.ReadKey(true);

                return(new TEntity[0]);
            }

            for (var i = 0; i < fieldCount; i++)
            {
                if (builder.Properties[i].PropertyType == typeof(bool) || builder.Properties[i].PropertyType.IsArray || builder.Properties[i].PropertyType.IsCustomClass() || builder.Properties[i].PropertyType.IsCustomStruct())
                {
                    continue;
                }

                // Return an empty list if any column/property type mismatches
                if (!data.Columns[i].DataType.IsEquivalentTo(builder.Properties[i].PropertyType.IsEnum ?
                                                             builder.Properties[i].PropertyType.GetEnumUnderlyingType() : builder.Properties[i].PropertyType))
                {
                    Trace.TraceError(string.Format("Table '{0}' (Column/Property type mismatch)", Pluralize <TEntity>()));
                    Trace.TraceError(string.Format("Column '{0}' ({1})", data.Columns[i].ColumnName, data.Columns[i].DataType));
                    Trace.TraceError(string.Format("Property '{0}' ({1})", builder.Properties[i].Name, builder.Properties[i].PropertyType.IsEnum ?
                                                   builder.Properties[i].PropertyType.GetEnumUnderlyingType() : builder.Properties[i].PropertyType));

                    Trace.WriteLine("Press a key to continue loading.");

                    Console.ReadKey(true);

                    return(new TEntity[0]);
                }
            }

            var entities         = new TEntity[data.Rows.Count];
            var datapPartitioner = Partitioner.Create(0, data.Rows.Count);

            // Create one test object for foreign key assignment check
            var foreignKeys = typeof(TEntity).GetProperties().Where(p => p.GetMethod.IsVirtual).ToArray();

            // Key: GroupStartIndex, Value: GroupCount
            var groups              = new ConcurrentDictionary <int, int>();
            var lastGroupName       = "";
            var lastGroupStartIndex = 0;

            // Get Groups
            for (var i = 0; i < fieldCount; i++)
            {
                var group = builder.Properties[i].GetCustomAttribute <GroupAttribute>();

                if (group != null)
                {
                    if (group.Name == lastGroupName)
                    {
                        groups[lastGroupStartIndex] += 1;
                    }
                    else
                    {
                        lastGroupName       = group.Name;
                        lastGroupStartIndex = i;

                        groups.TryAdd(lastGroupStartIndex, 1);
                    }
                }
            }

            if (entity.AutoAssignForeignKeys && foreignKeys.Length > 0)
            {
                // TODO: Optimize foreign key assignment (slow atm...)
                Parallel.ForEach(datapPartitioner, (dataRange, loopState) =>
                {
                    for (var i = dataRange.Item1; i < dataRange.Item2; i++)
                    {
                        entities[i] = new TEntity();

                        for (var j = 0; j < fieldCount; j++)
                        {
                            if (!builder.Properties[j].PropertyType.IsArray)
                            {
                                if (builder.Properties[j].PropertyType.IsCustomClass())
                                {
                                    var instanceFields = builder.Properties[j].PropertyType.GetReadWriteProperties();
                                    var instance       = Activator.CreateInstance(builder.Properties[j].PropertyType);

                                    for (var f = 0; f < instanceFields.Length; f++)
                                    {
                                        instanceFields[f].SetValue(instance, Convert.IsDBNull(data.Rows[i][j + f]) ? "" : data.Rows[i][j + f].ChangeTypeGet(builder.Properties[j].PropertyType));
                                    }

                                    builder.PropertySetter[j].SetValue(entities[i], instance);
                                }
                                else if (builder.Properties[j].PropertyType.IsCustomStruct())
                                {
                                    var instanceFields = builder.Properties[j].PropertyType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).ToArray();
                                    var instance       = Activator.CreateInstance(builder.Properties[j].PropertyType);

                                    for (var f = 0; f < instanceFields.Length; f++)
                                    {
                                        instanceFields[f].SetValue(instance, Convert.IsDBNull(data.Rows[i][j + f]) ? "" : data.Rows[i][j + f].ChangeTypeGet(builder.Properties[j + f].PropertyType));
                                    }

                                    builder.PropertySetter[j].SetValue(entities[i], instance);
                                }
                                else
                                {
                                    builder.PropertySetter[j].SetValue(entities[i], Convert.IsDBNull(data.Rows[i][j]) ? "" : data.Rows[i][j].ChangeTypeGet(builder.Properties[j].PropertyType));
                                }
                            }
                            else
                            {
                                var groupCount = 0;

                                if (groups.TryGetValue(j, out groupCount))
                                {
                                    for (var c = 0; c < groupCount; c++, j++)
                                    {
                                        var arr = builder.Properties[j].GetValue(new TEntity()) as Array;

                                        for (var k = 0; k < arr.Length; k++)
                                        {
                                            arr.SetValue(data.Rows[i][j + (k * groupCount)], k);
                                        }

                                        builder.PropertySetter[j].SetValue(entities[i], arr);
                                    }
                                }
                                else
                                {
                                    var arr = builder.Properties[j].GetValue(new TEntity()) as Array;

                                    for (var k = 0; k < arr.Length; k++)
                                    {
                                        arr.SetValue(data.Rows[i][j + k], k);
                                    }

                                    builder.PropertySetter[j].SetValue(entities[i], arr);
                                }
                            }
                        }

                        // TODO Fix group assignment in foreign keys.
                        if (groups.Count == 0)
                        {
                            parentDb.AssignForeignKeyData(entities[i], foreignKeys, groups);
                        }

                        entities[i].InitializeNonTableProperties();
                    }
                });
            }
            else
            {
                Parallel.ForEach(datapPartitioner, (dataRange, loopState) =>
                {
                    for (var i = dataRange.Item1; i < dataRange.Item2; i++)
                    {
                        entities[i] = new TEntity();

                        for (var j = 0; j < fieldCount; j++)
                        {
                            if (!builder.Properties[j].PropertyType.IsArray)
                            {
                                if (builder.Properties[j].PropertyType.IsCustomClass())
                                {
                                    var instanceFields = builder.Properties[j].PropertyType.GetReadWriteProperties();
                                    var instance       = Activator.CreateInstance(builder.Properties[j].PropertyType);

                                    for (var f = 0; f < instanceFields.Length; f++)
                                    {
                                        instanceFields[f].SetValue(instance, Convert.IsDBNull(data.Rows[i][j + f]) ? "" : data.Rows[i][j + f]);
                                    }

                                    builder.PropertySetter[j].SetValue(entities[i], instance);
                                }
                                else if (builder.Properties[j].PropertyType.IsCustomStruct())
                                {
                                    var instanceFields = builder.Properties[j].PropertyType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).ToArray();
                                    var instance       = Activator.CreateInstance(builder.Properties[j].PropertyType);

                                    for (var f = 0; f < instanceFields.Length; f++)
                                    {
                                        instanceFields[f].SetValue(instance, Convert.IsDBNull(data.Rows[i][j + f]) ? "" : data.Rows[i][j + f].ChangeTypeGet(builder.Properties[j + f].PropertyType));
                                    }

                                    builder.PropertySetter[j].SetValue(entities[i], instance);
                                }
                                else
                                {
                                    builder.PropertySetter[j].SetValue(entities[i], Convert.IsDBNull(data.Rows[i][j]) ? "" : data.Rows[i][j].ChangeTypeGet(builder.Properties[j].PropertyType));
                                }
                            }
                            else
                            {
                                var groupCount = 0;

                                if (groups.TryGetValue(j, out groupCount))
                                {
                                    for (var c = 0; c < groupCount; c++, j++)
                                    {
                                        var arr = builder.Properties[j].GetValue(entities[i]) as Array;

                                        for (var k = 0; k < arr.Length; k++)
                                        {
                                            arr.SetValue(data.Rows[i][j + (k * groupCount)], k);
                                        }

                                        builder.PropertySetter[j].SetValue(entities[i], arr);
                                    }
                                }
                                else
                                {
                                    var arr = builder.Properties[j].GetValue(entities[i]) as Array;

                                    for (var k = 0; k < arr.Length; k++)
                                    {
                                        arr.SetValue(data.Rows[i][j + k], k);
                                    }

                                    builder.PropertySetter[j].SetValue(entities[i], arr);
                                }
                            }
                        }

                        entities[i].InitializeNonTableProperties();
                    }
                });
            }

            return(entities);
        }
예제 #28
0
            private void SeparateRenderables(RenderContext context, bool invalidateSceneGraph, bool invalidatePerFrameRenderables)
            {
                Clear(invalidateSceneGraph, invalidatePerFrameRenderables);
                if (invalidateSceneGraph)
                {
                    viewportRenderables.AddRange(Viewport.Renderables);
                    renderer.UpdateSceneGraph(RenderContext, viewportRenderables, perFrameFlattenedScene);
    #if DEBUG
                    Debug.WriteLine("Flatten Scene Graph");
    #endif
                }
                int sceneCount = perFrameFlattenedScene.Count;
                if (invalidatePerFrameRenderables)
                {
    #if DEBUG
                    Debug.WriteLine("Get PerFrameRenderables");
    #endif
                    for (int i = 0; i < sceneCount;)
                    {
                        var renderable = perFrameFlattenedScene[i];
                        renderable.Value.Update(context);
                        var type = renderable.Value.RenderType;
                        if (!renderable.Value.IsRenderable)
                        {
                            //Skip scene graph depth larger than current node
                            int depth = renderable.Key;
                            ++i;
                            for (; i < sceneCount; ++i)
                            {
                                if (perFrameFlattenedScene[i].Key <= depth)
                                {
                                    break;
                                }
                                i += perFrameFlattenedScene[i].Value.ItemsInternal.Count;
                            }
                            continue;
                        }
                        if (renderable.Value.RenderCore.NeedUpdate) // Run update function at the beginning of actual rendering.
                        {
                            needUpdateCores.Add(renderable.Value.RenderCore);
                        }
                        ++i;
                        switch (type)
                        {
                        case RenderType.Opaque:
                            opaqueNodes.Add(renderable.Value);
                            break;

                        case RenderType.Light:
                            lightNodes.Add(renderable.Value);
                            break;

                        case RenderType.Transparent:
                            transparentNodes.Add(renderable.Value);
                            break;

                        case RenderType.Particle:
                            particleNodes.Add(renderable.Value);
                            break;

                        case RenderType.PreProc:
                            preProcNodes.Add(renderable.Value);
                            break;

                        case RenderType.PostProc:
                            postProcNodes.Add(renderable.Value);
                            break;

                        case RenderType.ScreenSpaced:
                            screenSpacedNodes.Add(renderable.Value);
                            break;
                        }
                    }
                    if (RenderConfiguration.EnableRenderOrder)
                    {
                        for (int i = 0; i < preProcNodes.Count; ++i)
                        {
                            preProcNodes[i].UpdateRenderOrderKey();
                        }
                        preProcNodes.Sort();
                        for (int i = 0; i < opaqueNodes.Count; ++i)
                        {
                            opaqueNodes[i].UpdateRenderOrderKey();
                        }
                        opaqueNodes.Sort();
                        for (int i = 0; i < postProcNodes.Count; ++i)
                        {
                            postProcNodes[i].UpdateRenderOrderKey();
                        }
                        postProcNodes.Sort();
                        for (int i = 0; i < particleNodes.Count; ++i)
                        {
                            particleNodes[i].UpdateRenderOrderKey();
                        }
                        particleNodes.Sort();
                    }
                    opaquePartitioner      = opaqueNodes.Count > 0 ? Partitioner.Create(0, opaqueNodes.Count, FrustumPartitionSize) : null;
                    transparentPartitioner = transparentNodes.Count > 0 ? Partitioner.Create(0, transparentNodes.Count, FrustumPartitionSize) : null;
                    SetupFrustumTestFunctions();
                }
                else
                {
                    for (int i = 0; i < sceneCount;)
                    {
                        var renderable = perFrameFlattenedScene[i];
                        renderable.Value.Update(context);
                        if (!renderable.Value.IsRenderable)
                        {
                            //Skip scene graph depth larger than current node
                            int depth = renderable.Key;
                            ++i;
                            for (; i < sceneCount; ++i)
                            {
                                if (perFrameFlattenedScene[i].Key <= depth)
                                {
                                    break;
                                }
                                i += perFrameFlattenedScene[i].Value.ItemsInternal.Count;
                            }
                            continue;
                        }
                        if (renderable.Value.RenderCore.NeedUpdate) // Run update function at the beginning of actual rendering.
                        {
                            needUpdateCores.Add(renderable.Value.RenderCore);
                        }
                        ++i;
                    }
                }
            }
예제 #29
0
        private int OnExecute()
        {
            InputFile = Path.GetFullPath(InputFile);

            if (OutputFile != null)
            {
                OutputFile = Path.GetFullPath(OutputFile);
                OutputFile = FixPathSlashes(OutputFile);
            }

            if (FileFilter != null)
            {
                FileFilter = FixPathSlashes(FileFilter);
            }

            if (ExtFilter != null)
            {
                ExtFilterList = ExtFilter.Split(',');
            }

            var paths = new List <string>();

            if (Directory.Exists(InputFile))
            {
                if (OutputFile != null && File.Exists(OutputFile))
                {
                    Console.Error.WriteLine("Output path is an existing file, but input is a folder.");

                    return(1);
                }

                IsInputFolder = true;

                var dirs = Directory
                           .EnumerateFiles(InputFile, "*.*", RecursiveSearch ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)
                           .Where(s => s.EndsWith("_c") || s.EndsWith(".vcs"));

                if (!dirs.Any())
                {
                    Console.Error.WriteLine(
                        "Unable to find any \"_c\" compiled files in \"{0}\" folder.{1}",
                        InputFile,
                        RecursiveSearch ? " Did you mean to include --recursive parameter?" : string.Empty);

                    return(1);
                }

                paths.AddRange(dirs);
            }
            else if (File.Exists(InputFile))
            {
                if (RecursiveSearch)
                {
                    Console.Error.WriteLine("File passed in with --recursive option. Either pass in a folder or remove --recursive.");

                    return(1);
                }

                paths.Add(InputFile);
            }
            else
            {
                Console.Error.WriteLine("Input \"{0}\" is not a file or a folder.", InputFile);

                return(1);
            }

            CurrentFile = 0;
            TotalFiles  = paths.Count;

            if (MaxParallelismThreads > 1)
            {
                Console.WriteLine("Will use {0} threads concurrently.", MaxParallelismThreads);

                var partitioner = Partitioner.Create(paths, EnumerablePartitionerOptions.NoBuffering);
                Parallel.ForEach(partitioner, new ParallelOptions {
                    MaxDegreeOfParallelism = MaxParallelismThreads
                }, (path, state) =>
                {
                    ProcessFile(path);
                });
            }
            else
            {
                foreach (var path in paths)
                {
                    ProcessFile(path);
                }
            }

            if (CollectStats)
            {
                Console.WriteLine();
                Console.WriteLine("Processed resource stats:");

                foreach (var stat in stats.OrderByDescending(x => x.Value.Count).ThenBy(x => x.Key))
                {
                    var info = string.IsNullOrEmpty(stat.Value.Info) ? string.Empty : $" ({stat.Value.Info})";

                    Console.WriteLine($"{stat.Value.Count,5} resources of version {stat.Value.Version} and type {stat.Value.Type}{info}");

                    foreach (var file in stat.Value.FilePaths)
                    {
                        Console.WriteLine($"\t\t{file}");
                    }
                }

                Console.WriteLine();
                Console.WriteLine("Unique special dependancies:");

                foreach (var stat in uniqueSpecialDependancies)
                {
                    Console.WriteLine("{0} in {1}", stat.Key, stat.Value);
                }
            }

            return(0);
        }
예제 #30
0
    void Update()
    {
        Split();
        Grow();

        int    iterations = _convergence;
        double totVel;

        do
        {
            Search.Populate(Particles);

            if (Mesh != null)
            {
                var particlesCount = Particles.Count;
                var points         = new List <Point3d>(particlesCount);
                var pullPoints     = new Point3d[particlesCount];

                for (int i = 0; i < particlesCount; i++)
                {
                    points.Add(Particles[i].Position);
                }

                Parallel.ForEach(Partitioner.Create(0, particlesCount), range =>
                {
                    var subPoints = points.GetRange(range.Item1, range.Item2 - range.Item1);
                    var subPulled = Mesh.PullPointsToMesh(subPoints);

                    int count = 0;
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        pullPoints[i] = subPulled[count++];
                    }
                });

                // var pullPoints = Mesh.PullPointsToMesh(points);

                Parallel.ForEach(Partitioner.Create(0, particlesCount), range =>
                {
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        Particles[i].Forces(pullPoints[i]);
                    }
                });
            }
            else
            {
                Parallel.ForEach(Partitioner.Create(0, Particles.Count), range =>
                {
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        Particles[i].Forces();
                    }
                });
            }

            Parallel.ForEach(Partitioner.Create(0, Springs.Count), range =>
            {
                for (int i = range.Item1; i < range.Item2; i++)
                {
                    Springs[i].Forces(10);
                }
            });

            Parallel.ForEach(Partitioner.Create(0, Particles.Count), range =>
            {
                for (int i = range.Item1; i < range.Item2; i++)
                {
                    Particles[i].Move();
                }
            });

            Parallel.ForEach(Partitioner.Create(0, Springs.Count), range =>
            {
                for (int i = range.Item1; i < range.Item2; i++)
                {
                    Springs[i].Update();
                }
            });

            totVel = 0;
            foreach (var particle in Particles)
            {
                totVel += particle.Velocity.SquareLength;
            }
        } while (totVel > 0.001 && iterations-- > 0);
    }
            protected virtual void OnSubmitGeometries(DeviceContextProxy deviceContext)
            {
                if (Geometries == null)
                {
                    VertexBuffer[0].UploadDataToBuffer(deviceContext, EmptyArray, 0);
                    IndexBuffer?.UploadDataToBuffer(deviceContext, EmptyIntArray, 0);
                    vertexBufferBindings = new VertexBufferBinding[0];
                    return;
                }
#if OutputBuildTime
                var time = System.Diagnostics.Stopwatch.GetTimestamp();
#endif
                var totalVertex  = 0;
                var totalIndices = 0;
                var vertRange    = new int[Geometries.Length];
                var idxRange     = new int[Geometries.Length];
                for (var i = 0; i < Geometries.Length; ++i)
                {
                    vertRange[i] = totalVertex;
                    totalVertex += Geometries[i].Geometry.Positions.Count;
                    if (Geometries[i].Geometry.Indices != null)
                    {
                        idxRange[i]   = totalIndices;
                        totalIndices += Geometries[i].Geometry.Indices.Count;
                    }
                }

                var tempVerts   = new VertStruct[totalVertex];
                var tempIndices = new int[totalIndices];
                if (Geometries.Length > 50 && totalVertex > 5000)
                {
                    var partitionParams = Partitioner.Create(0, Geometries.Length);
                    Parallel.ForEach(partitionParams, (range) =>
                    {
                        for (var i = range.Item1; i < range.Item2; ++i)
                        {
                            var geo       = Geometries[i];
                            var transform = geo.ModelTransform;
                            var vertStart = vertRange[i];
                            OnFillVertArray(tempVerts, vertStart, ref geo, ref transform);

                            if (IndexBuffer != null && geo.Geometry.Indices != null)
                            {
                                //Fill Indices, make sure to correct the offset
                                var count   = geo.Geometry.Indices.Count;
                                var tempIdx = idxRange[i];
                                for (var j = 0; j < count; ++j, ++tempIdx)
                                {
                                    tempIndices[tempIdx] = geo.Geometry.Indices[j] + vertStart;
                                }
                            }
                        }
                    });
                }
                else
                {
                    var vertOffset  = 0;
                    var indexOffset = 0;
                    for (var i = 0; i < Geometries.Length; ++i)
                    {
                        var geo       = Geometries[i];
                        var transform = geo.ModelTransform;
                        OnFillVertArray(tempVerts, vertOffset, ref geo, ref transform);

                        if (IndexBuffer != null && geo.Geometry.Indices != null)
                        {
                            //Fill Indices, make sure to correct the offset
                            var count   = geo.Geometry.Indices.Count;
                            var tempIdx = indexOffset;
                            for (var j = 0; j < count; ++j, ++tempIdx)
                            {
                                tempIndices[tempIdx] = geo.Geometry.Indices[j] + vertOffset;
                            }
                            indexOffset += geo.Geometry.Indices.Count;
                        }
                        vertOffset += geo.Geometry.Positions.Count;
                    }
                }
#if OutputBuildTime
                time = System.Diagnostics.Stopwatch.GetTimestamp() - time;
                Console.WriteLine($"Build Batch Time: {(float)time / System.Diagnostics.Stopwatch.Frequency * 1000} ms");
#endif
                VertexBuffer[0].UploadDataToBuffer(deviceContext, tempVerts, tempVerts.Length);
                IndexBuffer?.UploadDataToBuffer(deviceContext, tempIndices, tempIndices.Length);
                vertexBufferBindings = new[] { new VertexBufferBinding(VertexBuffer[0].Buffer, VertexBuffer[0].StructureSize, VertexBuffer[0].Offset) };
            }
예제 #32
0
        public unsafe double ParallelizedUnsafeSimdUnrolled()
        {
            double delta = 0;
            var sync = new object();

            Partitioner<Tuple<int, int>> partitioner = Partitioner.Create(0, _values.Length);
#if SEQUENTIAL
            var range = Tuple.Create(0, _values.Length);
#else
            Parallel.ForEach(
                partitioner,
                range =>
                {
#endif
                    double localDelta = 0;
                    double avg        = this.Mean;
                    int n             = range.Item2;

                    fixed (double* pArray = _values)
                    {
                        int i = range.Item1;
                        //double* arr = &pArray[i];
                        double* arr = pArray + i;     // is the same as above

                        if (Vector.IsHardwareAccelerated && (n - i) >= Vector<double>.Count)
                        {
                            var avgVec   = new Vector<double>(avg);
                            var deltaVec = new Vector<double>(0);

                            for (; i < n - 8 * Vector<double>.Count; i += 8 * Vector<double>.Count)
                            {
                                Core(arr, 0 * Vector<double>.Count, avgVec, ref deltaVec);
                                Core(arr, 1 * Vector<double>.Count, avgVec, ref deltaVec);
                                Core(arr, 2 * Vector<double>.Count, avgVec, ref deltaVec);
                                Core(arr, 3 * Vector<double>.Count, avgVec, ref deltaVec);
                                Core(arr, 4 * Vector<double>.Count, avgVec, ref deltaVec);
                                Core(arr, 5 * Vector<double>.Count, avgVec, ref deltaVec);
                                Core(arr, 6 * Vector<double>.Count, avgVec, ref deltaVec);
                                Core(arr, 7 * Vector<double>.Count, avgVec, ref deltaVec);

                                arr += 8 * Vector<double>.Count;
                            }

                            if (i < n - 4 * Vector<double>.Count)
                            {
                                Core(arr, 0 * Vector<double>.Count, avgVec, ref deltaVec);
                                Core(arr, 1 * Vector<double>.Count, avgVec, ref deltaVec);
                                Core(arr, 2 * Vector<double>.Count, avgVec, ref deltaVec);
                                Core(arr, 3 * Vector<double>.Count, avgVec, ref deltaVec);

                                arr += 4 * Vector<double>.Count;
                                i   += 4 * Vector<double>.Count;
                            }

                            if (i < n - 2 * Vector<double>.Count)
                            {
                                Core(arr, 0 * Vector<double>.Count, avgVec, ref deltaVec);
                                Core(arr, 1 * Vector<double>.Count, avgVec, ref deltaVec);

                                arr += 2 * Vector<double>.Count;
                                i   += 2 * Vector<double>.Count;
                            }

                            if (i < n - Vector<double>.Count)
                            {
                                Core(arr, 0 * Vector<double>.Count, avgVec, ref deltaVec);

                                i += Vector<double>.Count;
                            }

                            for (int j = 0; j < Vector<double>.Count; ++j)
                                localDelta += deltaVec[j];
                        }

                        for (; i < n; ++i)
                            localDelta += Math.Abs(pArray[i] - avg);
                    }

                    lock (sync) delta += localDelta;
#if !SEQUENTIAL
                }
            );
#endif
            return delta / _values.Length;
            //-----------------------------------------------------------------
            void Core(double* arr, int offset, Vector<double> avgVec, ref Vector<double> deltaVec)
            {
                Vector<double> vec = VectorHelper.GetVectorUnaligned(arr + offset);
                deltaVec += Vector.Abs(vec - avgVec);
            }
        }