public static void CalculateTasks(SimulationGraph graph, List <IPricer> pricers, List <NArray> derivatives = null)
        {
            var simulationCount = graph.Context.Settings.SimulationCount;
            var timePointCount  = graph.Context.Settings.SimulationTimePoints.Length;

            if (derivatives == null)
            {
                derivatives = new List <NArray>();
            }

            var tasks = new List <Task>();

            foreach (var partition in Partitioner(pricers.Count))
            {
                var resultsStorage = new CalculationResult(simulationCount, timePointCount, derivatives.Count);
                tasks.Add(Task.Run(() =>
                {
                    for (int i = 0; i < timePointCount; ++i)
                    {
                        foreach (var index in partition)
                        {
                            NArray.Evaluate(() =>
                            {
                                NArray pv;
                                pricers[index].Price(i, out pv);
                                return(pv);
                            },
                                            derivatives, Aggregator.ElementwiseAdd, resultsStorage.GetStorageForTimePoint(i));
                        }
                    }
                }));
            }

            Task.WaitAll(tasks.ToArray());
        }
        public void TestPerformance()
        {
            LinearGaussianModel  model;
            IEnumerable <NArray> allDiscountFactorT0;

            TimePoint[]     timePoints;
            SimulationGraph graph;
            List <IPricer>  pricers;

            SimulateModel(out model, out allDiscountFactorT0, out timePoints, out graph, out pricers);

            var resultStorage = Enumerable.Range(0, 1 + allDiscountFactorT0.Count()).
                                Select(i => new NArray(StorageLocation.Host, 5000, 1)).ToArray();

            Console.WriteLine(); Console.WriteLine("Deferred execution all derivatives, storage provided");
            VectorAccelerator.Tests.TestHelpers.Timeit(() =>
            {
                NArray.Evaluate(() =>
                {
                    var df = model[10, timePoints[10].DateTime.AddMonths(3)];
                    return(df);
                },
                                allDiscountFactorT0.ToArray(), Aggregator.ElementwiseAdd, resultStorage);
            }, 10, 10);
        }
Example #3
0
        public void WorkedExample()
        {
            NArray x0, x1;

            using (var stream = new RandomNumberStream(StorageLocation.Host, RandomNumberGeneratorType.MRG32K3A))
            {
                var normal = new Normal(stream, 0, 1);
                x0 = NArray.CreateRandom(5000, normal);
                x1 = NArray.CreateRandom(5000, normal);
            }

            var result = NArray.Evaluate(() =>
            {
                return(x0 * x1 + x0 * NMath.Exp(2 * x1));
            }, x0, x1);

            var derivativeWRTx0 = result[1];
            var derivativeWRTx1 = result[2];

            Assert.IsTrue(TestHelpers.AgreesAbsolute(derivativeWRTx0, x1 + NMath.Exp(2 * x1)));
            Assert.IsTrue(TestHelpers.AgreesAbsolute(derivativeWRTx1, x0 + 2 * x0 * NMath.Exp(2 * x1)));

            // can also call in such a way that the expression list is appended to a StringBuilder:
            var logger       = new StringBuilder();
            var loggedResult = NArray.Evaluate(() =>
            {
                return(x0 * x1 + x0 * NMath.Exp(2 * x1));
            }, logger, x0, x1);

            Console.WriteLine(logger.ToString());
        }
        private void DoWorkDeferred(NArray a, Normal normalDistribution, bool threaded = false)
        {
            // A version where assignment happens, but we defer execution.
            var result = NArray.CreateLike(a);

            result.Assign(a);

            var result2 = NArray.CreateLike(a);

            //var options = new DeferredExecution.VectorExecutionOptions() { MultipleThreads = threaded };

            for (int j = 0; j < 100; ++j)
            {
                NArray.Evaluate(() =>
                {
                    return(NMath.Log(NMath.Exp(result)));
                }, new List <NArray>(), Aggregator.ElementwiseAdd, new List <NArray> {
                    result2
                });

                //using (NArray.DeferredExecution(options))
                //{
                //    var temp = NMath.Exp(result);
                //    result.Assign(NMath.Log(temp));
                //}
            }
        }
Example #5
0
        public void BlackScholes()
        {
            NArray s;

            using (var stream = new RandomNumberStream(StorageLocation.Host, RandomNumberGeneratorType.MRG32K3A))
            {
                var normal = new Normal(stream, 0, 1);
                s = 100 * NMath.Exp(NArray.CreateRandom(5, normal) * 0.2);
            }

            double k          = 90;
            var    volatility = 0.2;
            var    t          = 5;
            var    df         = Math.Exp(-0.005 * t);

            var result = NArray.Evaluate(() =>
            {
                var f = s / df;
                return(df * Finance.BlackScholes(CallPut.Call, f, k, volatility, t));
            }, s);

            var sds   = s + 1e-6;
            var check = (df * Finance.BlackScholes(CallPut.Call, sds / df, k, volatility, t)
                         - df * Finance.BlackScholes(CallPut.Call, s / df, k, volatility, t)) * 1e6;

            Assert.IsTrue(TestHelpers.AgreesAbsolute(result[1], check));
        }
Example #6
0
        public void CUDA()
        {
            var location = StorageLocation.Host;
            var normal   = new Normal(new RandomNumberStream(location), 0, 1);
            var input    = NArray.CreateRandom(1000, normal);
            var result   = NArray.CreateLike(input);

            NArray.Evaluate(() =>
            {
                return(NMath.Exp(input * 0.2 + 6));
            });
        }
        /// <summary>
        /// A very customisable aggregation routine
        /// </summary>
        /// <param name="deals"></param>
        /// <param name="vectorLength"></param>
        /// <returns></returns>
        private NArray AggregateValuations(IList <Deal> deals, int vectorLength)
        {
            object lockObject       = new object();
            var    rangePartitioner = Partitioner.Create(0, deals.Count);

            var sum = new NArray(StorageLocation.Host, vectorLength);

            var options = new ParallelOptions();// { MaxDegreeOfParallelism = 2 };

            Parallel.ForEach(
                // input intervals
                rangePartitioner,

                options,

                // local initial partial result
                () => new NArray(StorageLocation.Host, vectorLength),

                // loop body for each interval
                (range, loopState, initialValue) =>
            {
                var partialSum = initialValue;
                for (int i = range.Item1; i < range.Item2; i++)
                {
                    partialSum.Add(
                        NArray.Evaluate(() =>
                    {
                        return(deals[i].Price(0));
                    }));
                }
                return(partialSum);
            },

                // final step of each local context
                (localPartialSum) =>
            {
                // using a lock to enforce serial access to shared result
                lock (lockObject)
                {
                    sum.Add(localPartialSum);
                }
            });

            return(sum);
        }
        public static void Calculate(SimulationGraph graph, List <IPricer> pricers, bool multiThread = true, List <NArray> derivatives = null)
        {
            var simulationCount = graph.Context.Settings.SimulationCount;
            var timePointCount  = graph.Context.Settings.SimulationTimePoints.Length;

            if (derivatives == null)
            {
                derivatives = new List <NArray>();
            }

            var threadCount = multiThread ? System.Environment.ProcessorCount : 1;
            var threads     = new Thread[threadCount];

            for (int i = 0; i < threads.Length; ++i)
            {
                var thread = new Thread(new ThreadStart(() =>
                {
                    var resultsStorage = new CalculationResult(simulationCount, timePointCount, derivatives.Count);
                    for (int j = 0; j < 1; ++j)
                    {
                        for (int index = i; index < pricers.Count; index += threadCount)
                        {
                            NArray.Evaluate(() =>
                            {
                                NArray pv;
                                pricers[index].Price(j, out pv);
                                return(pv);
                            },
                                            derivatives, Aggregator.ElementwiseAdd, resultsStorage.GetStorageForTimePoint(j));
                        }
                    }
                }));
                threads[i] = thread;
            }
            //threads[0].Start(); threads[0].Join();
            Array.ForEach(threads, t => { t.Start(); t.Join(); });
        }
Example #9
0
        public void BlackScholesPerformance()
        {
            double k          = 90;
            var    volatility = 0.2;
            var    t          = 5;

            var s            = new List <NArray>();
            int batchCount   = 1000;
            int vectorLength = 5000;

            using (var stream = new RandomNumberStream(StorageLocation.Host, RandomNumberGeneratorType.MRG32K3A))
            {
                var normal = new Normal(stream, 0, 1);
                for (int i = 0; i < batchCount; ++i)
                {
                    s.Add(100 * NMath.Exp(NArray.CreateRandom(vectorLength, normal) * 0.2));
                }
            }

            var result = NArray.CreateLike(s.First());

            double elapsedTime = TestHelpers.TimeitSeconds(() =>
            {
                for (int i = 0; i < batchCount; ++i)
                {
                    NArray.Evaluate(() =>
                    {
                        return(Finance.BlackScholes(CallPut.Call, s[i], k, volatility, t));
                    }, new List <NArray>(), Aggregator.ElementwiseAdd, new List <NArray> {
                        result
                    });
                }
            });

            Console.WriteLine(string.Format("Time per option price (single core): {0} ns", elapsedTime * 1e9 / (batchCount * vectorLength)));
            Console.WriteLine(string.Format("Valuations per second (single core): {0:F0} million", batchCount * vectorLength / (elapsedTime * 1e6)));
        }
Example #10
0
        public void DivisionTest()
        {
            NArray a, b;

            using (var stream = new RandomNumberStream(StorageLocation.Host))
            {
                a = NArray.CreateRandom(1000, new Normal(stream, 0, 1));
                b = NArray.CreateRandom(1000, new Normal(stream, 0, 1));
            }

            // First test
            var expected1     = 5.0 / a;
            var expectedDiff1 = -5.0 / (a * a);

            var obtained1 = NArray.Evaluate(() =>
            {
                return(5.0 / a);
            }, a);


            Assert.IsTrue(TestHelpers.AgreesAbsolute(obtained1[0], expected1));
            Assert.IsTrue(TestHelpers.AgreesAbsolute(obtained1[1], expectedDiff1));

            // Second test
            var expected2       = a / b;
            var expectedDiff2_1 = 1 / b;
            var expectedDiff2_2 = -a / (b * b);

            var obtained2 = NArray.Evaluate(() =>
            {
                return(a / b);
            }, a, b);

            Assert.IsTrue(TestHelpers.AgreesAbsolute(obtained2[0], expected2));
            Assert.IsTrue(TestHelpers.AgreesAbsolute(obtained2[1], expectedDiff2_1));
            Assert.IsTrue(TestHelpers.AgreesAbsolute(obtained2[2], expectedDiff2_2));
        }
        public void TestEndToEnd()
        {
            LinearGaussianModel  model;
            IEnumerable <NArray> allZeroRatesT0;

            TimePoint[]     timePoints;
            SimulationGraph graph;
            List <IPricer>  pricers;

            SimulateModel(out model, out allZeroRatesT0, out timePoints, out graph, out pricers);

            var simulationCount = graph.Context.Settings.SimulationCount;
            var timePointCount  = graph.Context.Settings.SimulationTimePoints.Length;

            var resultStorage =
                Enumerable.Range(0, timePointCount).Select(i =>
                                                           Enumerable.Range(0, 1 + allZeroRatesT0.Count()).
                                                           Select(j => new NArray(StorageLocation.Host, simulationCount, 1)).ToArray()).
                ToArray();

            var resultStorageSingle = Enumerable.Range(0, timePointCount).Select(i =>
                                                                                 new List <NArray> {
                new NArray(StorageLocation.Host,
                           simulationCount, 1)
            })
                                      .ToArray();

            Console.WriteLine(string.Format("Using {0} scenarios", simulationCount));

            foreach (var pricer in pricers)
            {
                pricer.PrePrice();
            }

            Console.WriteLine(string.Format("Running calculation: deferred execution, {0} flows, no derivatives, single thread", pricers.Count));
            double averageTime;

            TestHelpers.Timeit(() =>
            {
                for (int i = 0; i < timePointCount; ++i)
                {
                    foreach (var pricer in pricers)
                    {
                        NArray.Evaluate(() =>
                        {
                            NArray pv;
                            pricer.Price(i, out pv);
                            return(pv);
                        },
                                        new List <NArray>(), Aggregator.ElementwiseAdd, resultStorageSingle[i]);
                    }
                }
            }, out averageTime, 1, 1);

            var pricingOperationCount = 0;

            for (int i = 0; i < timePointCount; ++i)
            {
                pricingOperationCount += pricers.Count(p => p.ExposureEndDate < timePoints[i].DateTime);
            }

            double timeForSinglePrice = averageTime * 1e6 / (pricingOperationCount * simulationCount);

            Console.WriteLine(string.Format("Average time for single flow: {0:F1} ns", timeForSinglePrice));

            var percentiles = new double[] { 1, 10, 50, 90, 99 };
            var measures    = new List <IList <double> >();

            for (int i = 0; i < timePoints.Length; ++i)
            {
                var values = NMath.Percentiles(resultStorageSingle[i].First(), percentiles)
                             .Concat(new double[] { resultStorageSingle[i].First().DebugDataView
                                                    .Select(v => Math.Max(0, v)).Average() })
                             .ToList();
                measures.Add(values);
            }

            var times                = timePoints.Select(p => p.YearsFromBaseDate).ToArray();
            var profile10            = measures.Select(p => p[1]).ToArray();
            var profile90            = measures.Select(p => p[3]).ToArray();
            var meanPositive         = measures.Select(p => p[5]).ToArray();
            var maxMeanPositive      = meanPositive.Max();
            var maxMeanPositiveIndex = Array.IndexOf(meanPositive, maxMeanPositive);

            Console.WriteLine("Simulated profile:");
            Console.WriteLine(String.Format("{0,-5}   {1,-10}", "Date", "Mean positive", "90%"));
            for (int i = 0; i < times.Length && times[i] <= 10.25; ++i)
            {
                Console.WriteLine(String.Format("{0,-5:F2}  {1,-10:F2}  {2,-10:F2}", times[i], meanPositive[i], profile90[i]));
            }
            //Plot.PlotHelper.QuickPlot(times, profile90, new Tuple<double,double>(0, 11));

            Console.WriteLine(string.Format("Running calculation: deferred execution, {0} flows, {1} derivatives, single thread", pricers.Count, allZeroRatesT0.Count()));
            TestHelpers.Timeit(() =>
            {
                for (int i = 0; i < timePointCount; ++i)
                {
                    foreach (var pricer in pricers)
                    {
                        NArray.Evaluate(() =>
                        {
                            NArray pv;
                            pricer.Price(i, out pv);
                            return(pv);
                        },
                                        allZeroRatesT0.ToArray(), Aggregator.ElementwiseAdd, resultStorage[i]);
                    }
                }
            }, 1, 1);

            // we check that
            var           maxMeanPositiveSims = resultStorage[maxMeanPositiveIndex].First();
            List <double> gradients           = new List <double>();

            for (int i = 0; i < allZeroRatesT0.Count(); ++i)
            {
                var maxMeanPositiveDerivs = resultStorage[maxMeanPositiveIndex][i + 1];
                gradients.Add(maxMeanPositiveSims.DebugDataView
                              .Zip(maxMeanPositiveDerivs.DebugDataView,
                                   (s, d) => (s > 0) ? d : 0)
                              .Average()
                              );
            }

            Assert.IsTrue(TestHelpers.AgreesAbsolute(gradients[16], 8748.38858299));

            Console.WriteLine(string.Format(
                                  "Calculated gradient of maximum positive exposure ({0:F2} EUR)" + Environment.NewLine
                                  + "with respect to change of the zero rate with maturity {1:F2} years: {2:F3}",
                                  maxMeanPositive, 2556 / 365.25, gradients[16]));
        }
        /// <summary>
        /// Test building blocks of interest rate swap exposure calculation.
        /// </summary>
        public void TestBasics(LinearGaussianModel model, IEnumerable <NArray> allZeroRatesT0,
                               TimePoint[] timePoints, SimulationGraph graph)
        {
            bool testModel = true;

            if (testModel)
            {
                var check1 = model[1, timePoints[1].DateTime.AddDays(182)].First();
                Assert.IsTrue(TestHelpers.AgreesAbsolute(check1, 1.0015314301020275));

                var check2 = model[1, timePoints[1].DateTime.AddDays(91)].First();
                Assert.IsTrue(TestHelpers.AgreesAbsolute(check2, 1.0007451895710209));

                var check3 = model.ForwardRate(1,
                                               timePoints[1].DateTime.AddDays(91), timePoints[1].DateTime.AddDays(182)).First();
                Assert.IsTrue(TestHelpers.AgreesAbsolute(check3, -0.0031509366920208916));
            }

            bool testProfile = true;

            if (testProfile)
            {
                var testVariates0 = graph.RegisterFactor <NormalVariates>("IR_DiscountFactor_EUR_Factor0");
                var testVariates1 = graph.RegisterFactor <NormalVariates>("IR_DiscountFactor_EUR_Factor1");
                var testVariates2 = graph.RegisterFactor <NormalVariates>("IR_DiscountFactor_EUR_Factor2");

                var check = Descriptive.Correlation(testVariates1.Value, testVariates2.Value);

                // check 3M rolling tenor
                var percentiles = new double[] { 1, 10, 50, 90, 99 };
                var measures    = new List <IList <double> >();
                for (int i = 0; i < timePoints.Length; ++i)
                {
                    var tenorMonths = 3;
                    var tenorYears  = tenorMonths / 12.0;
                    var df          = model[i, timePoints[i].DateTime.AddMonths(3)];
                    var zeroRate    = -NMath.Log(df) / tenorYears;
                    var values      = NMath.Percentiles(zeroRate, percentiles).ToList();
                    measures.Add(values);
                }

                var times     = timePoints.Select(p => p.YearsFromBaseDate).ToArray();
                var profile10 = measures.Select(p => p[1]).ToArray();
                var profile90 = measures.Select(p => p[3]).ToArray();
            }

            bool testForwardRate = true;

            if (testForwardRate)
            {
                // check 3M rolling tenor
                var percentiles = new double[] { 1, 10, 50, 90, 99 };
                var measures    = new List <IList <double> >();
                for (int i = 0; i < timePoints.Length; ++i)
                {
                    var tenorMonths = 3;
                    var tenorYears  = tenorMonths / 12.0;
                    var forwardRate = model.ForwardRate(i, timePoints[i].DateTime.AddMonths(3), timePoints[i].DateTime.AddMonths(6));
                    var values      = NMath.Percentiles(forwardRate, percentiles).ToList();
                    measures.Add(values);
                }

                var times     = timePoints.Select(p => p.YearsFromBaseDate).ToArray();
                var profile10 = measures.Select(p => p[1]).ToArray();
                var profile90 = measures.Select(p => p[3]).ToArray();
            }

            bool testAAD = true;

            if (testAAD)
            {
                // just get the result
                var result0 = NArray.Evaluate(() =>
                {
                    var df = model[10, timePoints[10].DateTime.AddMonths(3)];
                    return(df);
                });

                // get the result and single derivative
                var result1 = NArray.Evaluate(() =>
                {
                    var df = model[10, timePoints[10].DateTime.AddMonths(3)];
                    return(df);
                }, model.ZeroRatesT0[6].Value);

                var log = new StringBuilder();

                // get the result and all derivatives (and log output)
                var result2 = NArray.Evaluate(() =>
                {
                    var df = model[10, timePoints[10].DateTime.AddMonths(3)];
                    return(df);
                }, log, allZeroRatesT0.ToArray());

                // now forward rate and all derivatives
                var result3 = NArray.Evaluate(() =>
                {
                    var df = model.ForwardRate(10, timePoints[10].DateTime.AddMonths(3), timePoints[10].DateTime.AddMonths(6));
                    return(df);
                }, allZeroRatesT0.ToArray());

                var unbumped0 = model[10, timePoints[10].DateTime.AddMonths(3)];

                var expected0 = unbumped0.DebugDataView.ToArray();
                var unbumped3 = model.ForwardRate(10, timePoints[10].DateTime.AddMonths(3), timePoints[10].DateTime.AddMonths(6));
                var expected3 = unbumped3.DebugDataView.ToArray();

                var obtained0 = result1[0].DebugDataView.ToArray();
                var obtained1 = result1[0].DebugDataView.ToArray();
                var obtained2 = result2[0].DebugDataView.ToArray();
                var obtained3 = result3[0].DebugDataView.ToArray();

                Assert.IsTrue(TestHelpers.AgreesAbsolute(expected0, obtained0));
                Assert.IsTrue(TestHelpers.AgreesAbsolute(expected0, obtained1));
                Assert.IsTrue(TestHelpers.AgreesAbsolute(expected0, obtained2));
                Assert.IsTrue(TestHelpers.AgreesAbsolute(expected3, obtained3));

                var logCheck = log.ToString();

                var obtained_deriv1 = result1[1].DebugDataView.ToArray();
                var obtained_deriv2 = result2[7].DebugDataView.ToArray();
                var obtained_deriv3 = result3[7].DebugDataView.ToArray();

                model.ZeroRatesT0.Data[6] = new DataPoint(model.ZeroRatesT0.Data[6].Time, model.ZeroRatesT0.Data[6].Value + 1e-6);

                var bumped0 = model[10, timePoints[10].DateTime.AddMonths(3)];
                var bumped3 = model.ForwardRate(10, timePoints[10].DateTime.AddMonths(3), timePoints[10].DateTime.AddMonths(6));

                var expected_deriv1 = ((bumped0 - unbumped0) / 1e-6)
                                      .DebugDataView.ToArray();

                var expected_deriv3 = ((bumped3 - unbumped3) / 1e-6)
                                      .DebugDataView.ToArray();

                Assert.IsTrue(TestHelpers.AgreesAbsolute(expected_deriv1, obtained_deriv1, 1e-5));
                Assert.IsTrue(TestHelpers.AgreesAbsolute(expected_deriv1, obtained_deriv2, 1e-5));
                Assert.IsTrue(TestHelpers.AgreesAbsolute(expected_deriv3, obtained_deriv3, 1e-5));
            }

            bool checkTimings = true;

            if (checkTimings)
            {
                // check timings
                Console.WriteLine("Immediate execution");
                VectorAccelerator.Tests.TestHelpers.Timeit(() =>
                {
                    var df = model[10, timePoints[10].DateTime.AddMonths(3)];
                }, 10, 10);

                Console.WriteLine(); Console.WriteLine("Deferred execution no derivatives");
                VectorAccelerator.Tests.TestHelpers.Timeit(() =>
                {
                    NArray.Evaluate(() =>
                    {
                        var df = model[10, timePoints[10].DateTime.AddMonths(3)];
                        return(df);
                    });
                }, 10, 10);

                Console.WriteLine(); Console.WriteLine("Deferred execution all derivatives");
                VectorAccelerator.Tests.TestHelpers.Timeit(() =>
                {
                    NArray.Evaluate(() =>
                    {
                        var df = model[10, timePoints[10].DateTime.AddMonths(3)];
                        return(df);
                    }, allZeroRatesT0.ToArray());
                }, 10, 10);
            }
        }
Example #13
0
        public void SimpleSpeedTest()
        {
            var factory = new NArrayFactory(StorageLocation.Host);

            IntelMathKernelLibrary.SetAccuracyMode(VMLAccuracy.LowAccuracy);

            int length = 1024 * 5;

            var a  = factory.CreateFromEnumerable(Enumerable.Range(0, length).Select(i => (double)i / length));
            var a2 = (a.Storage as VectorAccelerator.NArrayStorage.ManagedStorage <double>).Array;
            var b  = factory.CreateFromEnumerable(Enumerable.Range(3, length).Select(i => (double)i / length));
            var b2 = (b.Storage as VectorAccelerator.NArrayStorage.ManagedStorage <double>).Array;

            double[] result  = null;
            NArray   resultN = null;

            Console.WriteLine("Allocation");
            Timeit(
                () =>
            {
                result = new double[length];
            });
            Console.WriteLine(Environment.NewLine);

            result = new double[length];
            Console.WriteLine("Managed optimal");
            Timeit(
                () =>
            {
                for (int i = 0; i < result.Length; ++i)
                //Parallel.For(0, result.Length, (i) =>
                {
                    result[i] = 3 * Math.Log(Math.Exp(a2[i]) * Math.Exp(b2[i]));
                }
                //);
            });
            Console.WriteLine(Environment.NewLine);

            var vectorOptions = new VectorAccelerator.DeferredExecution.VectorExecutionOptions();

            vectorOptions.MultipleThreads = true;
            resultN = NArray.CreateLike(a);
            Console.WriteLine("Deferred threaded");
            Timeit(
                () =>
            {
                NArray.Evaluate(vectorOptions, () =>
                {
                    return(3 * NMath.Log(NMath.Exp(a) * NMath.Exp(b)));
                });
            });
            Console.WriteLine(CheckitString(result, (resultN.Storage as ManagedStorage <double>).Array));
            Console.WriteLine(Environment.NewLine);

            resultN = NArray.CreateLike(a);
            vectorOptions.MultipleThreads = false;
            Console.WriteLine("Deferred not threaded");
            Timeit(
                () =>
            {
                NArray.Evaluate(vectorOptions, () =>
                {
                    return(3 * NMath.Log(NMath.Exp(a) * NMath.Exp(b)));
                });
            });
            Console.WriteLine(CheckitString(result, (resultN.Storage as ManagedStorage <double>).Array));
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine("Immediate");
            Timeit(
                () =>
            {
                resultN.Assign(3 * NMath.Log(NMath.Exp(a) * NMath.Exp(b)));
            });
            Console.WriteLine(CheckitString(result, (resultN.Storage as ManagedStorage <double>).Array));
            Console.WriteLine(Environment.NewLine);

            Console.WriteLine("Hit any key");
            Console.ReadKey();
        }
        public void VectorFundamentalsTest()
        {
            var location = StorageLocation.Host;

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

                var a      = new NArray(StorageLocation.Host, 5000);
                var b      = new NArray(StorageLocation.Host, 5000);
                var c      = new NArray(StorageLocation.Host, 5000);
                var d      = new NArray(StorageLocation.Host, 5000);
                var result = NArray.CreateLike(a);
                a.FillRandom(normalDistribution);
                b.FillRandom(normalDistribution);
                c.FillRandom(normalDistribution);
                d.FillRandom(normalDistribution);
                var aArray      = GetArray(a);
                var bArray      = GetArray(b);
                var cArray      = GetArray(c);
                var dArray      = GetArray(d);
                var resultArray = GetArray(result);

                Console.WriteLine(); Console.WriteLine("In place vector Exp MKL");
                TestHelpers.Timeit(() =>
                {
                    IntelMathKernelLibrary.Exp(aArray, 0, resultArray, 0, result.Length);
                }, 20, 50);

                Console.WriteLine(); Console.WriteLine("In place vector Exp C sharp");
                TestHelpers.Timeit(() =>
                {
                    for (int i = 0; i < 5000; ++i)
                    {
                        resultArray[i] = Math.Exp(aArray[i]);
                    }
                }, 20, 50);

                Console.WriteLine(); Console.WriteLine("In place vector aX + Y MKL");
                TestHelpers.Timeit(() =>
                {
                    IntelMathKernelLibrary.ConstantAddMultiply(aArray, 0, 3, 0, resultArray, 0, 5000);
                    //IntelMathKernelLibrary.Multiply(bArray, 0, resultArray, 0, resultArray, 0, result.Length);
                    IntelMathKernelLibrary.Add(bArray, 0, resultArray, 0, resultArray, 0, result.Length);
                    //IntelMathKernelLibrary.Exp(resultArray, 0, resultArray, 0, result.Length);
                    // 3 reads and 2 writes
                }, 20, 50);

                Console.WriteLine(); Console.WriteLine("In place vector aX + Y C sharp");
                TestHelpers.Timeit(() =>
                {
                    for (int i = 0; i < 5000; ++i)
                    {
                        resultArray[i] = 3 * aArray[i] + bArray[i]; // 2 reads and a write
                        //resultArray[i] = Math.Exp(3 * aArray[i] + bArray[i]); // 2 reads and a write
                    }
                }, 20, 50);

                Console.WriteLine(); Console.WriteLine("Immediate mode; creating storage");
                TestHelpers.Timeit(() =>
                {
                    //var result2 = NMath.Exp(3 * a + b);
                    var result2 = 3 * a + b;
                }, 20, 50);

                var result3 = NArray.CreateLike(a);

                Console.WriteLine(); Console.WriteLine("Deferred mode; storage passed in");
                TestHelpers.Timeit(() =>
                {
                    NArray.Evaluate(() =>
                    {
                        //return NMath.Exp(3 * a + b);
                        return(3 * a + b);
                    }
                                    , new List <NArray>(), Aggregator.ElementwiseAdd, new List <NArray> {
                        result3
                    });
                }, 20, 50);

                return;

                Console.WriteLine(); Console.WriteLine("Deferred mode; storage passed in");
                TestHelpers.Timeit(() =>
                {
                    NArray.Evaluate(() =>
                    {
                        return(3 * a + b);
                    }
                                    , new List <NArray>(), Aggregator.ElementwiseAdd, new List <NArray> {
                        result
                    });
                }, 20, 50);
            }
        }
Example #15
0
        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));
            }
        }
        /// <summary>
        /// Test of efficiency for a large number of simple vector operations.
        /// In particular, tests enhanced recycling of locals.
        /// </summary>
        public void SimpleTest()
        {
            // create 500 random vectors
            var vectorLength = 5000;
            var vectors      = new NArray[500];

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

                for (int i = 0; i < vectors.Length; ++i)
                {
                    vectors[i] = NArray.CreateRandom(vectorLength, normalDistribution);
                }
            }
            var watch  = new System.Diagnostics.Stopwatch(); watch.Start();
            var result = NArray.CreateLike(vectors.First());

            for (int i = 0; i < vectors.Length; ++i)
            {
                for (int j = 0; j < vectors.Length; ++j)
                {
                    result.Add(vectors[i] * vectors[j] * 123);
                    //result = result + vectors[i] * vectors[j] * 123;
                }
            }
            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);

            var arrays = vectors.Select(v => (v.Storage as ManagedStorage <double>).Array).ToArray();

            watch.Restart();
            var arrayResult = new double[vectors.First().Length];

            for (int i = 0; i < vectors.Length; ++i)
            {
                for (int j = 0; j < vectors.Length; ++j)
                {
                    for (int k = 0; k < arrayResult.Length; ++k)
                    {
                        arrayResult[k] += arrays[i][k] * arrays[j][k] * 123;
                    }
                }
            }
            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);

            watch.Restart();
            result = NArray.CreateLike(vectors.First());
            for (int i = 0; i < vectors.Length; ++i)
            {
                var batch = NArray.Evaluate(() =>
                {
                    NArray res = NArray.CreateScalar(0);
                    for (int j = 0; j < vectors.Length; ++j)
                    {
                        res = res + vectors[i] * vectors[j] * 123;
                    }
                    return(res);
                });
                result += batch;
            }
            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);
        }
Example #17
0
        public void Example1()
        {
            var location = StorageLocation.Host;

            var watch = new System.Diagnostics.Stopwatch(); watch.Start();

            using (var randomStream = new RandomNumberStream(location, RandomNumberGeneratorType.MRG32K3A, 111))
            {
                var normal = new Normal(randomStream, 0, 1);
                var test   = NArray.CreateRandom(1000, normal);
                for (int i = 0; i < 363 * 100; ++i)
                {
                    test.FillRandom(normal);
                }
            }
            watch.Stop();
            var elapsed = watch.ElapsedMilliseconds * 5000 / (100 * 1000);

            NArray a, b;

            using (var randomStream = new RandomNumberStream(location, RandomNumberGeneratorType.MRG32K3A, 111))
            {
                var normal = new Normal(randomStream, 0, 1);
                a = NArray.CreateRandom(5000, normal);
                b = NArray.CreateRandom(5000, normal);
            }

            var expressions = new StringBuilder();
            var result      = NArray.Evaluate(() =>
            {
                return(a * b + a * NMath.Exp(b));
            }, expressions);

            var expressionsDiff = new StringBuilder();
            var resultDiff      = NArray.Evaluate(() =>
            {
                return(a * b + a * NMath.Exp(2 * b));
            }, expressionsDiff, a, b);

            var output = expressionsDiff.ToString();

            var expressionsDiff2 = new StringBuilder();

            var s = NMath.Exp(a) + 5;

            var resultDiff2 = NArray.Evaluate(() =>
            {
                return(Finance.BlackScholes(CallPut.Call, s, 5, 1, 1));
                //return NMath.Exp(NMath.Sqrt(a));
            }, expressionsDiff2, s);

            var check    = (Finance.BlackScholes(CallPut.Call, s + 1e-6, 5, 1, 1) - Finance.BlackScholes(CallPut.Call, s, 5, 1, 1)) / 1e-6;
            var expected = check.DebugDataView.Take(10).ToArray();
            var obtained = resultDiff2[1].DebugDataView.Take(10).ToArray();

            var output2 = expressionsDiff2.ToString();

            Console.Write(output2);

            VectorAccelerator.Tests.TestHelpers.Timeit(() =>
            {
                var resultTiming = NArray.Evaluate(() =>
                {
                    return(Finance.BlackScholes(CallPut.Call, s, 5, 1, 1));
                }, expressionsDiff2);
            });
        }