public AffineDivCurveUtils(DividendQuote[] dividends, DiscountCurve discountCurve, ITimeMeasure time) { Contract.Requires(EnumerableUtils.IsSorted(dividends.Select(div => div.Date))); if (dividends.Length > 0) { double[] divDates = dividends.Map(div => time[div.Date]); double[] spotYieldGrowths = dividends.Scan(1.0, (prev, div) => prev * (1.0 - div.Yield)); var spotYieldGrowth = new StepFunction(divDates, spotYieldGrowths, 1.0); assetGrowth = t => spotYieldGrowth.Eval(t) / discountCurve.Zc(t); double[] discountedCashs = dividends.Map(div => div.Cash / assetGrowth(time[div.Date])); double[] cashBpvs = discountedCashs.Scan(0.0, (prev, c) => prev + c); cashDivBpv = new StepFunction(divDates, cashBpvs, 0.0); cashBpvIntegral = cashDivBpv.Integral(0.0); double[] squareTimeWeightedCashs = discountedCashs.ZipWith(divDates, (c, t) => c * t * t); squareTimeWeightedCash = new StepFunction(divDates, squareTimeWeightedCashs, 0.0); } else { assetGrowth = t => 1.0 / discountCurve.Zc(t); cashDivBpv = new StepFunction(new[] { 0.0 }, new[] { 0.0 }, double.NaN); cashBpvIntegral = RrFunctions.Zero; squareTimeWeightedCash = new StepFunction(new[] { 0.0 }, new[] { 0.0 }, double.NaN); } }
public void Test() { var market = Market(); const double lambda = 0.01; var sigma = new StepFunction(new[] { 0.0, 1.0, 2.0 }, new[] { 0.007, 0.004, 0.0065 }, 0.0); var hw1 = new Hw1Model(TimeMeasure.Act365(market.RefDate), Currency.Eur, lambda, sigma); var mcConfig = new MonteCarloConfig(20000, RandomGenerators.GaussianSobol(SobolDirection.JoeKuoD5)); var mcPricer = McPricer.WithDetails(mcConfig); var fixedLeg = FixedLeg(market.RefDate); var mcPriceResult = (PriceResult)mcPricer.Price(fixedLeg, hw1, market); var mcCoupons = mcPriceResult.Details.Map(p => p.Item3.Value); var refCoupons = mcPriceResult.Details.Map(pi => market.DiscountCurve(pi.Item2.Financing).Zc(pi.Item2.Date)); var errAbs = Math.Abs(mcCoupons.Sum() - refCoupons.Sum()); Assert.LessOrEqual(errAbs, 7.0e-5); var errRel = Math.Abs(mcCoupons.Sum() / refCoupons.Sum() - 1.0); Assert.LessOrEqual(errRel, 8.0e-6); }
public static Perceptron CreatePerceptron( double learningRate, double initialWeightLimit, int inputsCount, StepFunction stepFunction, bool useAdaline) { if (learningRate <= 0) { throw new ArgumentException($"{nameof(learningRate)} cannot be 0! Nor negative. F****t"); } if (useAdaline) { stepFunction = StepFunction.Bipolar; } double[] initialWeights = new double[inputsCount]; for (int i = 0; i < initialWeights.Length; i++) { initialWeights[i] = initialWeightLimit * (Rng.NextDouble() * 2 - 1); } double bias = initialWeightLimit * (Rng.NextDouble() * 2 - 1); Perceptron perceptron = new Perceptron(initialWeights, learningRate, bias, stepFunction, useAdaline); return(perceptron); }
public void TestEval() { var abs = new[] { 0.0, 0.5, 0.99, 2.5 }; var vals = new[] { 5.0, 5.4, 3.1, 1.0 }; const double leftVal = 0.0; var stepFunc = new StepFunction(abs, vals, leftVal); foreach (var i in Enumerable.Range(0, abs.Length)) { Assert.AreEqual(stepFunc.Eval(abs[i]), vals[i]); if (i < abs.Length - 1) { var midPoint = 0.5 * (abs[i] + abs[i + 1]); Assert.AreEqual(stepFunc.Eval(midPoint), vals[i]); var nextPointMinus = abs[i] + (1.0 - 5.0 * DoubleUtils.MachineEpsilon) * (abs[i + 1] - abs[i]); Assert.AreEqual(stepFunc.Eval(nextPointMinus), vals[i]); } } Assert.AreEqual(stepFunc.Eval(abs[0] - 0.00000000001), leftVal); Assert.AreEqual(stepFunc.Eval(double.NegativeInfinity), leftVal); Assert.AreEqual(stepFunc.Eval(abs[abs.Length - 1] + 0.00000000001), vals[abs.Length - 1]); Assert.AreEqual(stepFunc.Eval(double.PositiveInfinity), vals[abs.Length - 1]); }
private static RationalFraction BasedExtrapol(StepFunction <RationalFraction> stepSplines, double firstPillar) { var extrapol = stepSplines.Eval(double.NegativeInfinity); var basedNum = extrapol.Num.TaylorDev(firstPillar - stepSplines.Pillars.First()); var basedDenom = extrapol.Denom.TaylorDev(firstPillar - stepSplines.Pillars.First()); return(basedNum / basedDenom); }
public static void InitEnv(StepFunction step, Env env, string[]?cmdArgs = null) { env.Set(new Symbol("*ARGV*", NilV), new List((cmdArgs ?? new string[0]).Skip(1).Select(arg => new Str(arg) as MalType).ToLList(), ListType.List, NilV)); env.Set(new Symbol("eval", NilV), new Fn(args => args switch { (var Mal, null) => Eval(Mal, env), _ => throw new Exception($"'eval' function requires one argument, but got {args.JoinMalTypes(", ")}") }, NilV));
private static RationalFraction BasedSpline(StepFunction <RationalFraction> stepSplines, double basePoint) { int stepIndex; var spline = stepSplines.Eval(basePoint, out stepIndex); var splineBasePoint = stepSplines.Pillars[Math.Max(0, stepIndex)]; var basedNum = spline.Num.TaylorDev(basePoint - splineBasePoint); var basedDenom = spline.Denom.TaylorDev(basePoint - splineBasePoint); return(basedNum / basedDenom); }
public void TestIntegral(double[] pillars, double[] vals, double leftVal, double[] refIntegralVals) { var stepFunc = new StepFunction(pillars, vals, leftVal); var integral = stepFunc.Integral(pillars[0]); Assert.IsTrue(integral is SplineInterpoler); for (int i = 0; i < pillars.Length - 1; i++) { var integralVal = integral.Eval(pillars[i]); Assert.IsTrue(DoubleUtils.MachineEquality(integralVal, refIntegralVals[i])); } }
public Perceptron( double[] weights, double learningRate, double bias, StepFunction stepFunction, bool isAdaline ) { _weights = weights; _learningRate = learningRate; _bias = bias; _stepFunction = stepFunction; _isAdaline = isAdaline; }
public void TestIntegralExp() { var exp = RrFunctions.Exp(0.1); var step = new StepFunction(new[] { 0.0, 5.0 }, new[] { 0.015, 0.010 }, 0.0); var f = exp * step; var integral = f.Integral(0.0); var testVal = integral.Eval(10.0); var expintegral = exp.Integral(0.0); var refVal = 0.015 * (expintegral.Eval(5.0) - expintegral.Eval(0.0)) + 0.01 * (expintegral.Eval(10.0) - expintegral.Eval(5.0)); Assert.IsTrue(DoubleUtils.Equality(testVal, refVal, 1.5 * DoubleUtils.MachineEpsilon)); }
private static RrFunction BinaryOp(SplineInterpoler left, SplineInterpoler right, FracBinaryOp binaryOp) { double[] mergedPillars = ArrayUtils.MergeSortedArray(left.pillars, right.pillars); var binOpElems = mergedPillars.Select(p => { RationalFraction leftElem = BasedSpline(left.stepSplines, p); RationalFraction rightElem = BasedSpline(right.stepSplines, p); return(binaryOp(leftElem, rightElem)); }).ToArray(); RationalFraction leftExtrapol = BasedExtrapol(left.stepSplines, mergedPillars.First()); RationalFraction rightExtrapol = BasedExtrapol(right.stepSplines, mergedPillars.First()); RationalFraction binOpExtrapol = binaryOp(leftExtrapol, rightExtrapol); var stepSplines = new StepFunction <RationalFraction>(mergedPillars, binOpElems, binOpExtrapol); return(new SplineInterpoler(stepSplines)); }
public void TestMult() { var pillars1 = new[] { 0.0, 1.0, 2.0 }; var vals1 = new[] { 0.007, 0.004, 0.0065 }; const double left1 = 2.0; var step1 = new StepFunction(pillars1, vals1, left1); var pillars2 = new[] { -0.8, 0.2, 1.0, 1.5, 2.0, 3.55 }; var vals2 = new[] { 0.005, 0.003, -0.1, 0.0, -0.08, 10.0 }; const double left2 = -1.89; var step2 = new StepFunction(pillars2, vals2, left2); var prod = step1 * step2; Assert.IsTrue(prod is StepFunction); var allPillars = pillars1.Union(pillars2).OrderBy(p => p).ToArray(); for (int i = 0; i < allPillars.Length; i++) { double x = allPillars[i]; var val1 = step1.Eval(x); var val2 = step2.Eval(x); var prodVal = prod.Eval(x); Assert.IsTrue(DoubleUtils.MachineEquality(prodVal, val1 * val2)); } Assert.IsTrue(DoubleUtils.MachineEquality(prod.Eval(double.NegativeInfinity), step1.Eval(double.NegativeInfinity) * step2.Eval(double.NegativeInfinity))); var rand = new Random(123); double a = allPillars.Max() - allPillars.Min(); double b = allPillars.Min(); for (int i = 0; i < 1000; i++) { var x = rand.NextDouble() * a * 3.0 + b - 0.1 * a; var val1 = step1.Eval(x); var val2 = step2.Eval(x); var prodVal = prod.Eval(x); Assert.IsTrue(DoubleUtils.MachineEquality(prodVal, val1 * val2)); } }
public void MainTest() { var func = new StepFunction(4, 3, 3); StepFunction[] array = { new StepFunction(10, 0, 2), new StepFunction(4, 1, 2), new StepFunction(3, 2, 2) }; const int n = 4; const int m = 2; Assert.NotNull(func.A); Assert.NotNull(func.B); Assert.NotNull(func.X); Assert.NotEmpty(array); Assert.NotNull(array[0]); Assert.NotNull(array[1]); Assert.NotNull(array[2]); Assert.Throws <IndexOutOfRangeException>(() => Assert.Null(array[3])); Assert.Equal(108, func.FuncRes()); Assert.Equal("0*x^(-1)", func.GetNlook(n)); Assert.Equal(0, func.GetNresult(n)); var look = " "; double result = 0; double derivativeRes = 0; foreach (var el in array) { result += el.FuncRes(); look += el.GetNlook(m); look += "+ "; derivativeRes += el.GetNresult(m); } look = look.Substring(0, look.Length - 2); Assert.Equal(30, result); Assert.Equal(" 0*x^(-2)+ 0*x^(-1)+ 6*x^(0)", look); Assert.Equal(6, derivativeRes); }
/// <summary> /// Creates a new distribution summary which corresponds to a mixture distribution: /// with probability p1 we get the original (this) /// with probability (1-p1) we get the other distribution /// </summary> /// <param name="other">other distribution</param> /// <param name="p1">weight assigned to this distribution</param> /// <returns></returns> public DistributionApproximation MixWith(DistributionApproximation other, double p1, int histBins) { double p2 = 1.0 - p1; StepFunction sf1 = CDF; StepFunction sf2 = other.CDF; StepFunction mixed = sf1 * p1 + sf2 * p2; var retval = new DistributionApproximation(); // compute quantiles by getting them from the mixed cdf var quants = Matrix <double> .Build.Dense(histBins + 1, 2); for (int i = 0; i <= histBins; ++i) { quants[i, 0] = i / (double)histBins; quants[i, 1] = mixed.MonotonicIncreasingInverse(quants[i, 0]); } retval.Quantiles = quants; return(retval); }
public void Zc(double lambda, Duration zcStart, Duration zcDuration, int quadratureNbPoints, double precision) { var sigma = new StepFunction(new[] { 0.0, 1.0, 2.0 }, new[] { 0.007, 0.004, 0.0065 }, 0.0); var refDate = DateTime.Parse("07/06/2009"); var hw1 = new Hw1Model(TimeMeasure.Act365(refDate), Currency.Eur, lambda, sigma); var hw1Zc = new Hw1ModelZcRepresentation(hw1); var zcDate = refDate + zcStart; var zc = hw1Zc.Zc(zcDate, zcDate + zcDuration, 1.0); var drift = hw1.DriftTerm(); var stdDev = Math.Sqrt(drift.Eval(hw1.Time[zcDate])); double[] x, w; GaussHermite.GetQuadrature(quadratureNbPoints, out x, out w); double zcQuad = x.Select((t, i) => w[i] * zc.Eval(new[] { stdDev *t })).Sum(); var error = Math.Abs(zcQuad - 1.0); Assert.LessOrEqual(error, precision); }
private static int CountTrees(OptimizedWorld world, StepFunction stepFunction) { var currentX = 0; var currentY = 0; var worldHeight = world.GridHeight; var trees = 0; while (currentY < worldHeight) { if (world.Get(currentX, currentY).GroundType == GroundType.Tree) { trees++; } currentX += stepFunction.stepsRight; currentY += stepFunction.stepsDown; } return(trees); }
public static void Error( double learningRate, double weightsLimit, StepFunction stepFunction, int inputsCount) { CsvPrinter.DumpParams( new KeyValuePair <string, object>("weightsLimit", weightsLimit), new KeyValuePair <string, object>("learningRate", learningRate), new KeyValuePair <string, object>("stepFunction", stepFunction), new KeyValuePair <string, object>("inputsCount", inputsCount) ); CsvPrinter.DumpHeaderLine("n", "error"); try { var p = PerceptronTrainer.CreatePerceptron(learningRate, weightsLimit, inputsCount, stepFunction, false); var epochs = PerceptronTrainer.TrainPerceptron_And(p, dumpData: true); } catch (PerceptronLearnException) { } }
public static void WeightsRange( double start, double end, double step, int repetitions, double learningRate, StepFunction stepFunction, int inputsCount, bool useAdaline = false, double adalineThreshold = 1, bool verbose = false ) { if (start > end || step > Math.Abs(end - start) || step == 0) { throw new ArgumentException(); } CsvPrinter.DumpParams( new KeyValuePair <string, object>("start", start), new KeyValuePair <string, object>("end", end), new KeyValuePair <string, object>("step", step), new KeyValuePair <string, object>("repetitions", repetitions), new KeyValuePair <string, object>("learningRate", learningRate), new KeyValuePair <string, object>("stepFunction", stepFunction), new KeyValuePair <string, object>("inputsCount", inputsCount), new KeyValuePair <string, object>("useAdalvine", useAdaline), new KeyValuePair <string, object>("adalineThreshold", adalineThreshold), new KeyValuePair <string, object>("verbose", verbose) ); CsvPrinter.DumpHeaderLine("n", "initial weights limit", "min epochs", "max epochs", "avg epochs"); int experimentIndex = 0; for (double weightsLimit = start; weightsLimit <= end; weightsLimit += step) { experimentIndex++; var minEpochs = int.MaxValue; var epochsSum = 0; var maxEpochs = 0; var run = 0; Perceptron p = null; if (verbose) { ConsoleHelper.WriteYellowLine($"Experiment - {experimentIndex}"); } for (int j = 0; j < repetitions; j++) { run++; p = PerceptronTrainer.CreatePerceptron(learningRate, weightsLimit, inputsCount, stepFunction, useAdaline); var epochs = PerceptronTrainer.TrainPerceptron_And(p, adalineThreshold, verbose); if (epochs < minEpochs) { minEpochs = epochs; } if (epochs > maxEpochs) { maxEpochs = epochs; } epochsSum += epochs; } var avarageEpochs = epochsSum / run; CsvPrinter.DumpLine(experimentIndex, weightsLimit, minEpochs, maxEpochs, avarageEpochs); } }
private SplineInterpoler(StepFunction <RationalFraction> stepSplines) { this.stepSplines = stepSplines; pillars = stepSplines.Pillars; }