public static IList<NArray> Evaluate(Func<NArray> function, IList<NArray> independentVariables, StringBuilder expressionsOut = null,
            Aggregator aggregator = Aggregator.ElementwiseAdd, IList<NArray> existingStorage = null, VectorExecutionOptions vectorOptions = null)
        {
            if (existingStorage != null && existingStorage.Count != independentVariables.Count + 1)
                throw new ArgumentException(string.Format("storage provided does not match requirement for 1 result and {0} derivatives",
                    independentVariables.Count));

            var timer = new ExecutionTimer();
            timer.Start();
            NArray[] outputs = new NArray[independentVariables.Count + 1];

            var context = new DeferredExecutionContext(new VectorExecutionOptions(), independentVariables);
            NArray dependentVariable;
            try
            {
                // execute function as deferred operations and obtain reference to the dependentVariable
                dependentVariable = function();
            }
            finally
            {
                context.Finish();
            }
            timer.MarkFunctionComplete();
            for (int i = 0; i < outputs.Length; ++i)
            {
                // if new storage is required, we create scalars in the first instance
                outputs[i] = (existingStorage == null) ? NArray.CreateScalar(0) : existingStorage[i];
            }
            context._executor.Evaluate(context._options, outputs, dependentVariable, independentVariables,
                timer, expressionsOut, aggregator);

            //Console.WriteLine(timer.Report());
            return outputs;
        }
 private DeferredExecutionContext(VectorExecutionOptions options, IList<NArray> independentVarables)
 {
     _executor = new DeferringExecutor(independentVarables);
     _previousExecutor = ExecutionContext.Executor;
     _options = options;
     ExecutionContext.Executor = _executor;
 }
Пример #3
0
 private DeferredExecutionContext(VectorExecutionOptions options, IList <NArray> independentVarables)
 {
     _executor                 = new DeferringExecutor(independentVarables);
     _previousExecutor         = ExecutionContext.Executor;
     _options                  = options;
     ExecutionContext.Executor = _executor;
 }
        public static void Execute(DeferringExecutor executor,
                                   LinearAlgebraProvider provider, VectorExecutionOptions vectorOptions)
        {
            //Console.WriteLine(executor.DebugString());
            int chunksLength   = 1000;
            var arrayPoolStack = ExecutionContext.ArrayPool.GetStack(chunksLength);

            while (arrayPoolStack.Count < 10)
            {
                arrayPoolStack.Push(new double[chunksLength]);
            }

            int length = executor.VectorsLength;

            int chunkCount = length / chunksLength;

            if (length % chunksLength != 0)
            {
                chunkCount++;
            }

            //AssignNArrayStorage(executor.LocalVariables.OfType<NArray<double>>(), chunkCount, chunksLength);
            // and integers too?

            var options = new ParallelOptions();

            if (!vectorOptions.MultipleThreads)
            {
                options.MaxDegreeOfParallelism = 1;
            }

            //for (int i = 0; i < chunkCount; i++)
            var operations = Simplify(executor, provider);

            Parallel.For(0, chunkCount, options, (i) =>
            {
                int startIndex = i * chunksLength;
                List <double[]> temporaryArrays = new List <double[]>();
                int vectorLength = Math.Min(chunksLength, length - startIndex);
                foreach (var operation in operations)
                {
                    if (operation is NArrayOperation <double> )
                    {
                        ExecuteSingleVectorOperation <double>(operation as NArrayOperation <double>,
                                                              arrayPoolStack, temporaryArrays,
                                                              vectorLength,
                                                              i, startIndex);
                    }
                }
                foreach (var array in temporaryArrays)
                {
                    arrayPoolStack.Push(array);
                }
            });
            //};
        }
        public void OptionPricingTest()
        {
            var location = StorageLocation.Host;

            var a = new NArray(location, Enumerable.Range(0, 10).Select(i => (double)i).ToArray());
            var b = new NArray(location, Enumerable.Range(0, 10).Select(i => (double)i * 2).ToArray());
            var c = 5 - b;
            var check = c.First();
            IntelMathKernelLibrary.SetAccuracyMode(VMLAccuracy.LowAccuracy);
            IntelMathKernelLibrary.SetSequential();
            using (var randomStream = new RandomNumberStream(location, RandomNumberGeneratorType.MRG32K3A, 111))
            {
                var normalDistribution = new Normal(randomStream, 0, 1);

                var vectorOptions = new VectorExecutionOptions() { MultipleThreads = true };

                var watch = new Stopwatch();

                watch.Start();
                var optionPrices = Value(normalDistribution);
                Console.WriteLine(String.Format("Start-up: {0}ms", watch.ElapsedMilliseconds));

                randomStream.Reset();

                watch.Restart();
                optionPrices = Value(normalDistribution);
                Console.WriteLine(String.Format("Threaded, deferred 1: {0}ms", watch.ElapsedMilliseconds));

                randomStream.Reset();

                watch.Restart();
                var optionPricesDeferred = Value(normalDistribution);
                Console.WriteLine(String.Format("Threaded, deferred 2: {0}ms", watch.ElapsedMilliseconds)); watch.Restart();

                Console.WriteLine(TestHelpers.AgreesAbsoluteString(optionPrices, optionPricesDeferred));
            }
        }
        public void TestBlackScholes()
        {
            var location = StorageLocation.Host;

            using (var randomStream = new RandomNumberStream(location, RandomNumberGeneratorType.MRG32K3A, 111))
            {
                var normalDistribution = new Normal(randomStream, 0, 1);

                double deltaT = 1;
                double r = 0.1;
                double vol = 0.3;

                var options = new ParallelOptions();
                options.MaxDegreeOfParallelism = 1;

                var variates = NArray.CreateRandom(5000, normalDistribution);
                NArray optionPrices = NArray.CreateLike(variates);
                var watch = new Stopwatch(); watch.Start();

                Parallel.For(0, 1000, options, (i) =>
                {
                    optionPrices = NArray.CreateLike(variates);
                    var logStockPrice = Math.Log(100)
                        + variates * Math.Sqrt(deltaT) * vol + (r - 0.5 * vol * vol) * deltaT;
                    var stockPrices = NMath.Exp(logStockPrice);

                    optionPrices.Assign(Finance.BlackScholes(-1, stockPrices, 90, 0.2, 1));
                });
                Console.WriteLine("Baseline sequential");
                Console.WriteLine(watch.ElapsedMilliseconds); watch.Restart();

                Parallel.For(0, 1000, (i) =>
                {
                    optionPrices = NArray.CreateLike(variates);
                    var logStockPrice = Math.Log(100)
                        + variates * Math.Sqrt(deltaT) * vol + (r - 0.5 * vol * vol) * deltaT;
                    var stockPrices = NMath.Exp(logStockPrice);

                    optionPrices.Assign(Finance.BlackScholes(-1, stockPrices, 90, 0.2, 1));
                });
                Console.WriteLine("Baseline threaded");
                Console.WriteLine(watch.ElapsedMilliseconds);

                NArray optionPrices2 = NArray.CreateLike(variates);

                watch.Restart();
                var vectorOptions = new DeferredExecution.VectorExecutionOptions() { MultipleThreads = true };
                Parallel.For(0, 1000, options, (i) =>
                {
                    optionPrices2 = NArray.CreateLike(variates);
                    NArray.Evaluate(optionPrices2, () =>
                    {
                        var logStockPrice = Math.Log(100)
                            + variates * Math.Sqrt(deltaT) * vol + (r - 0.5 * vol * vol) * deltaT;
                        var stockPrices = NMath.Exp(logStockPrice);

                        return Finance.BlackScholes(-1, stockPrices, 90, 0.2, 1);
                    });
                });
                Console.WriteLine("Deferred sequential");
                Console.WriteLine(watch.ElapsedMilliseconds);
                Console.WriteLine(CheckitString((optionPrices.Storage as ManagedStorage<double>).Array, (optionPrices2.Storage as ManagedStorage<double>).Array));
                watch.Restart();

                Parallel.For(0, 1000, (i) =>
                {
                    //optionPrices2 = NArray.CreateLike(variates);
                    optionPrices2 = NArray.Evaluate(() =>
                    {
                        var logStockPrice = Math.Log(100)
                            + variates * Math.Sqrt(deltaT) * vol + (r - 0.5 * vol * vol) * deltaT;
                        var stockPrices = NMath.Exp(logStockPrice);

                        return Finance.BlackScholes(-1, stockPrices, 90, 0.2, 1);
                    });
                });
                Console.WriteLine("Deferred threaded");
                Console.WriteLine(watch.ElapsedMilliseconds); watch.Restart();
                Console.WriteLine(CheckitString((optionPrices.Storage as ManagedStorage<double>).Array, (optionPrices2.Storage as ManagedStorage<double>).Array));
            }
        }
Пример #7
0
        public static IList <NArray> Evaluate(Func <NArray> function, IList <NArray> independentVariables, StringBuilder expressionsOut = null,
                                              Aggregator aggregator = Aggregator.ElementwiseAdd, IList <NArray> existingStorage = null, VectorExecutionOptions vectorOptions = null)
        {
            if (existingStorage != null && existingStorage.Count != independentVariables.Count + 1)
            {
                throw new ArgumentException(string.Format("storage provided does not match requirement for 1 result and {0} derivatives",
                                                          independentVariables.Count));
            }

            var timer = new ExecutionTimer();

            timer.Start();
            NArray[] outputs = new NArray[independentVariables.Count + 1];

            var    context = new DeferredExecutionContext(new VectorExecutionOptions(), independentVariables);
            NArray dependentVariable;

            try
            {
                // execute function as deferred operations and obtain reference to the dependentVariable
                dependentVariable = function();
            }
            finally
            {
                context.Finish();
            }
            timer.MarkFunctionComplete();
            for (int i = 0; i < outputs.Length; ++i)
            {
                // if new storage is required, we create scalars in the first instance
                outputs[i] = (existingStorage == null) ? NArray.CreateScalar(0) : existingStorage[i];
            }
            context._executor.Evaluate(context._options, outputs, dependentVariable, independentVariables,
                                       timer, expressionsOut, aggregator);

            //Console.WriteLine(timer.Report());
            return(outputs);
        }