Beispiel #1
0
        /// <summary>
        /// Plugin Thread
        /// </summary>

        public void PluginMain()
        {
            //Get the application port for the server
            if (!isRunning) //Application starting the first time
            {
                clientList = new List <Socket>();
                int appPort = default(int);
                Types.InputBoxValue result = new Types.InputBoxValue {
                    dialogResult = DialogResult.OK, result = ""
                };
                if (Integrate.CheckPermission(Permissions.Display, pluginToken))
                {
                    result = ServerSettings.ShowInputBox("Android Bridge", "Please enter a port for the android listener to run on", pluginToken);
                }
                if (result.dialogResult != DialogResult.OK)
                {
                    Console.WriteLine("Port not set or display permission is denied");
                    return;
                }
                ui = new AndroidUI(this);
                Invoke(() => ui.Show());
                appPort      = int.Parse(result.result);
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Create the socket server
                serverSocket.Bind(new IPEndPoint(IPAddress.Any, appPort));                                  //Bind the server to any interface and the selected port number
                serverSocket.Listen(50000);                                                                 //begin listen max. 50000 pending connections
                serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);                          //begin accepting clients
                isRunning = true;                                                                           //Set the application to running state
            }
            else //Application running in the background
            {
                ui = new AndroidUI(this);
                Invoke(() => ui.Show());
            }
        }
        private void AreaDetection()
        {
            double shortSum = 0, longSum = 0, shortAve, longAve;

            for (int j = i; j > (i - shortNum + 1); j--)
            {
                double slope     = (data[j, 1] - data[j - 1, 1]) / (data[j, 0] - data[j - 1, 0]);
                double intercept = data[j, 1] - slope * data[j, 0];
                var    result1   = Integrate.OnClosedInterval(x => slope * x + intercept, data[j - 1, 0], (data[j, 0]));

                shortSum += Math.Abs(result1);
            }
            for (int j = i; j > (i - longNum + 1); j--)
            {
                double slope     = (data[j, 1] - data[j - 1, 1]) / (data[j, 0] - data[j - 1, 0]);
                double intercept = data[j, 1] - slope * data[j, 0];
                var    result2   = Integrate.OnClosedInterval(x => slope * x + intercept, data[j - 1, 0], (data[j, 0]));

                longSum += Math.Abs(result2);
            }
            shortAve = shortSum / shortNum;
            longAve  = longSum / longNum;

            if (Math.Abs((shortAve - longAve) / longAve) > ArgDetect)
            {
                Point point = new Point();
                point = new Point(data[i, 0], data[i, 1]);
                dataSource2.AppendAsync(base.Dispatcher, point);
                flag = 2;
            }
        }
        public void TestIntegrateFacade()
        {
            Assert.AreEqual(
                TargetAreaA,
                Integrate.OnClosedInterval(TargetFunctionA, StartA, StopA),
                1e-5,
                "Interval");

            Assert.AreEqual(
                TargetAreaA,
                Integrate.OnClosedInterval(TargetFunctionA, StartA, StopA, 1e-10),
                1e-10,
                "Interval, Target 1e-10");

            Assert.AreEqual(
                Integrate.OnRectangle(TargetFunctionB, StartA, StopA, StartB, StopB),
                TargetAreaB,
                1e-12,
                "Rectangle");

            Assert.AreEqual(
                Integrate.OnRectangle(TargetFunctionB, StartA, StopA, StartB, StopB, 22),
                TargetAreaB,
                1e-10,
                "Rectangle, Gauss-Legendre Order 22");
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            double samplingRate = 1;
            int    index        = 1;

            while (true)
            {
                switch (index)
                {
                case 1:
                case 2:
                case 3:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;

                case 4:
                case 5:
                case 6:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;

                default:
                    Console.ForegroundColor = ConsoleColor.Green;
                    break;
                }
                double dx = Integrate.IntegrateFunction(0, 2, samplingRate, new Sigmoid());
                Console.WriteLine("├ #" + index++ + " ┼ Sigmoid integral: " + dx + " on sampling rate: " + samplingRate);
                samplingRate /= 10;
            }
        }
        /// <summary>
        /// Executes the example.
        /// </summary>
        /// <seealso cref="http://reference.wolfram.com/mathematica/ref/Integrate.html"/>
        /// <seealso cref="http://en.wikipedia.org/wiki/Trapezoidal_rule">Trapezoidal rule</seealso>
        public override void ExecuteExample()
        {
            // 1. Integrate x*x on interval [0, 10]
            Console.WriteLine(@"1. Integrate x*x on interval [0, 10]");
            var result = Integrate.OnClosedInterval(x => x * x, 0, 10);

            Console.WriteLine(result);
            Console.WriteLine();

            // 2. Integrate 1/(x^3 + 1) on interval [0, 1]
            Console.WriteLine(@"2. Integrate 1/(x^3 + 1) on interval [0, 1]");
            result = Integrate.OnClosedInterval(x => 1 / (Math.Pow(x, 3) + 1), 0, 1);
            Console.WriteLine(result);
            Console.WriteLine();

            // 3. Integrate f(x) = exp(-x/5) (2 + sin(2 * x)) on [0, 10]
            Console.WriteLine(@"3. Integrate f(x) = exp(-x/5) (2 + sin(2 * x)) on [0, 10]");
            result = Integrate.OnClosedInterval(x => Math.Exp(-x / 5) * (2 + Math.Sin(2 * x)), 0, 100);
            Console.WriteLine(result);
            Console.WriteLine();

            // 4. Integrate target function with absolute error = 1E-4
            Console.WriteLine(@"4. Integrate target function with absolute error = 1E-4 on [0, 10]");
            Console.WriteLine(@"public static double TargetFunctionA(double x) {
  return Math.Exp(-x / 5) * (2 + Math.Sin(2 * x));
}");
            result = Integrate.OnClosedInterval(TargetFunctionA, 0, 100, 1e-4);
            Console.WriteLine(result);
            Console.WriteLine();
        }
        /// <summary>
        /// Determine the value of the caplet using the Black-Caplet-formula
        /// </summary>
        /// <returns></returns>
        public double Value(YieldCurve yieldCurve, double delta, Func <double, double> volatilityFunc)
        {
            // valuation date
            var valuationDate = yieldCurve.SettleDate;

            var T = Utilities.ConvertToDayCountFraction(valuationDate, FixingDate);

            Func <double, double> func = t => volatilityFunc(T - t) * volatilityFunc(T - t);

            var sigma = Math.Sqrt(1 / T * Integrate.OnClosedInterval(func, 0, T));

            var tenor = Utilities.ConvertToDayCountFraction(FixingDate, ExpiryDate);
            var bond  = yieldCurve.GetDiscountFactors(new [] { FixingDate, ExpiryDate });

            var kappa = CapRate / (Tenor * Principal) + delta;

            var spotForwardRate = 1 / tenor * (bond[0] / bond[1] - 1);

            var logLK  = Math.Log((spotForwardRate + delta) / (kappa));
            var gamma  = T * sigma * sigma;
            var dPlus  = (logLK + 0.5 * gamma) / Math.Sqrt(gamma);
            var dMinus = (logLK - 0.5 * gamma) / Math.Sqrt(gamma);

            return(bond[1] * Principal * Tenor * (spotForwardRate * Normal.CDF(0, 1, dPlus) - kappa * Normal.CDF(0, 1, dMinus)));
        }
Beispiel #7
0
    float TestReslut()
    {
        float e_pow   = (Mathf.Pow(a, 2) - Mathf.Pow(b, 2)) / Mathf.Pow(a, 2);
        float resulte = a * (float)Integrate.OnClosedInterval(x => Mathf.Sqrt(1 - e_pow * Mathf.Pow(Mathf.Cos((float)x), 2)), down * Mathf.Deg2Rad, up * Mathf.Deg2Rad);

        return(Mathf.Abs(resulte));
    }
        private void test_Click(object sender, RoutedEventArgs e)
        {
            //var fenetre = new fenetreOpenGL();
            // fenetre.Show();
            _openGlPanel    = new Integrate();
            wfhSample.Child = _openGlPanel;

            wfhSample.Focus();
        }
Beispiel #9
0
        public async Task AreaListOption(string areaname, string option, string choice)
        {
            //サーバーID等の変数の宣言
            string serverfolder = $@"R:\Project\RUMM.warehouse\{Context.Guild.Id}";

            string datafolder          = $@"{serverfolder}\Data";
            string datafolder_area     = $@"{datafolder}\Area";
            string datafolder_areaname = $@"{datafolder_area}\{areaname}";
            string area_text           = $@"{datafolder_areaname}\{areaname}.txt";

            string trimedfolder     = $@"{serverfolder}\Trimed";
            string trimedfolder_map = $@"{trimedfolder}\TrimedMap";

            string completedfolder        = $@"{serverfolder}\Completed";
            string areafolder             = $@"{completedfolder}\AreaMap\{areaname}";
            string area_completedmap_list = $@"{areafolder}\{areaname}[list].png";

            switch (option)
            {
            case "list":
                switch (choice)
                {
                case "text":
                    if (File.Exists(area_text))
                    {
                        await Context.Channel.SendFileAsync(area_text);

                        await Context.Channel.SendSuccessAsync("完了", $"{areaname}の座標リストだよ!");
                    }
                    else
                    {
                        await Context.Channel.SendErrorAsync("エラー", $"そんな名前のエリアはないよ...? \r\n `r.area add {areaname}`でエリアを追加してみよ!");
                    }
                    break;

                case "map":
                    if (File.Exists(area_text))
                    {
                        Integrate.Original_Area_WithCoord(area_text, trimedfolder_map, area_completedmap_list);

                        await Context.Channel.SendFileAsync(area_completedmap_list);

                        await Context.Channel.SendSuccessAsync("完了", $"これが{areaname}の座標付き地図だよ!");
                    }
                    else
                    {
                        await Context.Channel.SendErrorAsync("エラー", $"そんな名前のエリアはないよ...? \r\n `r.area add {areaname}`でエリアを追加してみよう!");
                    }
                    break;
                }
                break;

            case "copy":
                break;
            }
        }
Beispiel #10
0
        public static double simpsonRuleEs(Expr expr, string varName, double a, double b, int n)
        {
            var f = expr.Compile(varName);

            double srValue = SimpsonRule.IntegrateComposite(f, a, b, n);

            double trueValue = Integrate.OnClosedInterval(f, a, b);

            return(abs(trueValue - srValue));
        }
Beispiel #11
0
        public static double trapezoidalRuleEt(Expr expr, string varName, double a, double b, int n)
        {
            var f = expr.Compile(varName);

            double trValue = NewtonCotesTrapeziumRule.IntegrateComposite(f, a, b, n);

            double trueValue = Integrate.OnClosedInterval(f, a, b);

            return(abs(trueValue - trValue));
        }
Beispiel #12
0
        public async Task Download(int scale)
        {
            //サーバーID等の変数の宣言
            string serverfolder = $@"R:\Project\RUMM.warehouse\{Context.Guild.Id}";

            string trimedfolder     = $@"{serverfolder}\Trimed";
            string trimedfolder_map = $@"{trimedfolder}\TrimedMap";

            string completedfolder            = $@"{serverfolder}\Completed";
            string completedfolder_map        = $@"{completedfolder}\CompletedMap";
            string completedfolder_map_backup = $@"{completedfolder}\CompletedMap[Backup]";

            string compmap_path          = $@"{completedfolder_map}\completedmap.png";
            string compmap_path_withdate = $@"{completedfolder_map}\completedmap[{DateTime.Now.ToString("yyyyMMdd")}].png";
            string compmap_backup_path   = $@"{completedfolder_map_backup}\{DateTime.Now.ToString("yyyyMMdd")}.png";

            //特定のサーバーからこのコマンドが実行されないようにする
            if (Context.Guild.Id == 725704901652381718)
            {
                await Context.Channel.SendErrorAsync("エラー", $"このコマンドは`{Context.Guild.Name}`では使えないよ!");

                return;
            }

            //指定できる最大サイズを超えた指定をされた場合、拒否する
            if (scale > 384)
            {
                await Context.Channel.SendErrorAsync("エラー", "指定できるサイズは`384`以下だよ!もう実行試してみてね!");

                return;
            }

            //指定されたサイズで地図を統合 / 同時に、バックアップ用の統合地図を最大サイズで作る
            Integrate.Original(trimedfolder_map, compmap_path_withdate, scale);
            Integrate.Original(trimedfolder_map, compmap_backup_path, 384);

            //Discordで送信できる最大サイズである[8MB]を超えた場合、送信を拒否する
            FileInfo file = new FileInfo(compmap_path_withdate);

            if (file.Length < 8000000)
            {
                await Context.Channel.SendFileAsync(compmap_path_withdate);

                await Context.Channel.SendSuccessAsync("完了", "これが君たちの世界の地図だよ!");
            }
            else
            {
                await Context.Channel.SendErrorAsync("エラー", $"地図が8MBを超えていて送れないんだ...、今の地図の大きさは`{file.Length / 1048576}MB`だよ!" +
                                                     $"\r\n別のサイズで試してみてね!(※統合はできているよ!)");
            }

            File.Move(compmap_path_withdate, compmap_path, true);
        }
        public void TestPortal()
        {
            Assert.That(
                Integrate.OnClosedInterval(TargetFunctionA, StartA, StopA),
                NumericIs.AlmostEqualTo(TargetAreaA, 1e-5),
                "Basic");

            Assert.That(
                Integrate.OnClosedInterval(TargetFunctionA, StartA, StopA, 1e-10),
                NumericIs.AlmostEqualTo(TargetAreaA, 1e-10),
                "Basic Target 1e-10");
        }
Beispiel #14
0
        public void TestIntegratePortal()
        {
            Assert.AreEqual(
                TargetAreaA,
                Integrate.OnClosedInterval(TargetFunctionA, StartA, StopA),
                1e-5,
                "Basic");

            Assert.AreEqual(
                TargetAreaA,
                Integrate.OnClosedInterval(TargetFunctionA, StartA, StopA, 1e-10),
                1e-10,
                "Basic Target 1e-10");
        }
Beispiel #15
0
        public double Functional_J(Vector calc_u)
        {
            double h      = MyMath.Basic.GetStep(GRID_SIZE, 0d, L);
            Vector calc_y = new Vector(GRID_SIZE);
            Vector err    = new Vector(GRID_SIZE);

            for (int i = 0; i < GRID_SIZE; i++)
            {
                err[i] = (calc_u[i] - y(h * i)) * (calc_u[i] - y(h * i));
            }


            return(Integrate.RiemannSum(err.ToArray, h));
        }
Beispiel #16
0
 void IntegrateAll(string paths, Integrate integrate)
 {
     if (games.Count == 0)
     {
         Console.WriteLine("Warning: no games set for integration!");
     }
     foreach (Game g in games)
     {
         integrator.VerifyAgainst = g;
         integrator.Verbose       = verbose;
         string[] files = paths.Split(new char[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
         foreach (string file in files)
         {
             integrate(file);
         }
     }
 }
Beispiel #17
0
        Point3D ICompute.ElasticCenter()
        {
            double xcoord = Integrate.OnClosedInterval(
                x => x * dL(x) / L,
                -W / 2,
                W / 2,
                Prec
                );
            double zcoord = Integrate.OnClosedInterval(
                x => F(x) * dL(x) / L,
                -W / 2,
                W / 2,
                Prec
                );

            return(new Point3D(xcoord, 0, zcoord));
        }
        private Matrix LocVolMatrixFromImpliedVol(CallPriceMarketData Hdataset, IFunction impVol, out Vector locVolMat, out Vector locVolStr)
        {
            int    nmat    = calibrationSettings.LocalVolatilityMaturities;
            int    nstrike = calibrationSettings.LocalVolatilityStrikes;
            double lastMat = Hdataset.Maturity[Range.End];
            double lastStr = Hdataset.Strike[Range.End];

            locVolMat = Vector.Linspace(Hdataset.Maturity[0], lastMat, nmat);
            locVolStr = Vector.Linspace(Hdataset.Strike[0], lastStr, nstrike);
            Matrix locVolMatrix = new Matrix(nmat, nstrike);

            Integrate integrate = new Integrate(this);
            double    sigma, dSigmadk, num, y, den, avgGrowthRate;
            Vector    x = new Vector(2);

            for (int i = 0; i < nmat; i++)
            {
                avgGrowthRate = integrate.AdaptLobatto(0.0, locVolMat[i]);

                int j = 0;
                x[0]               = locVolMat[i];
                x[1]               = locVolStr[j];
                sigma              = impVol.Evaluate(x);
                dSigmadk           = impVol.Partial(x, 1);
                num                = Math.Pow(sigma, 2) + 2.0 * sigma * x[0] * impVol.Partial(x, 0);
                den                = 1.0;
                locVolMatrix[i, j] = Math.Sqrt(num / den);

                // The rest of the cycle.
                for (j = 1; j < nstrike; j++)
                {
                    x[1]     = locVolStr[j];
                    sigma    = impVol.Evaluate(x);
                    dSigmadk = impVol.Partial(x, 1);
                    num      = Math.Pow(sigma, 2) + 2.0 * sigma * x[0] *
                               (impVol.Partial(x, 0) + avgGrowthRate * x[1] * dSigmadk);
                    y   = Math.Log(locVolStr[j] / Hdataset.S0) + avgGrowthRate;
                    den = System.Math.Pow(1.0 - x[1] * y * dSigmadk / sigma, 2) + x[1] * sigma * x[0] *
                          (dSigmadk - 0.25 * x[1] * sigma * x[0] * dSigmadk * dSigmadk + x[1] * impVol.Partial2(x, 1));
                    locVolMatrix[i, j] = Math.Sqrt(num / den);
                }
            }
            return(locVolMatrix);
        }
Beispiel #19
0
        static async Task Main(string[] args)
        {
            //Первое задание
            object first  = "высокий приоритет";
            object second = "низкий приоритет";

            Integrate integrate = new Integrate();

            integrate.Finish += integrate.Result;

            Thread threadFirst = new Thread(integrate.Integration);

            threadFirst.Priority = ThreadPriority.Highest;

            Thread threadSecond = new Thread(integrate.Integration);

            threadSecond.Priority = ThreadPriority.Lowest;

            threadFirst.Start(first);
            threadSecond.Start(second);

            Console.ReadKey();

            //Второе задание
            using (MemoryStream stream = new MemoryStream())
            {
                StreamService       service = new StreamService();
                Func <Worker, bool> retFunc = Filter;

                Task writeToStream = service.WriteToStream(stream);
                await Task.Delay(100);

                Task copyFromStream = service.CopyFromStream(stream, "Test.txt");

                await Task.WhenAll(new Task[] { writeToStream, copyFromStream });

                Console.WriteLine("=============================================");

                Task <int> stat = Task.Run(() => service.GetStatisticsAsync("Test.txt", retFunc));

                Console.WriteLine($"\nКоличество объектов, удовлетворяющих условию: {stat.Result}");
            }
        }
Beispiel #20
0
        public List <PointLoad> DiscretizeForce(Func <double, double> force, Vault structure, UnitVector3D projection)
        {
            var        res   = new List <PointLoad>();
            Boundaries bound = Boundaries[Axis];

            for (int i = 0; i < structure.Points.MidSegment.Count; i++)
            {
                double coord_prev = structure.Points.Segment[i].ToVector3D().DotProduct(Axis);
                double coord_next = structure.Points.Segment[i + 1].ToVector3D().DotProduct(Axis);

                if (coord_prev > coord_next)
                {
                    var temp = coord_next;
                    coord_next = coord_prev;
                    coord_prev = temp;
                }

                if (coord_next >= bound.Min && coord_prev <= bound.Max)
                {
                    var point = structure.Points.MidSegment[i];

                    double min = Max(coord_prev, bound.Min);
                    double max = Min(coord_next, bound.Max);
                    double force_integral;

                    if (Abs(min - max) > Prec)
                    {
                        force_integral = Integrate.OnClosedInterval(force, min, max);
                    }
                    else
                    {
                        max            = point.ToVector3D().DotProduct(Axis);
                        force_integral = 2 * Integrate.OnClosedInterval(force, min, max);
                    }

                    if (Abs(force_integral) > Prec)
                    {
                        res.Add(new VaultPointLoad(point, force_integral * projection));
                    }
                }
            }
            return(res);
        }
Beispiel #21
0
        public void TestIntegralOfGaussian(double a, double b, double expected)
        {
            Assert.AreEqual(
                expected,
                Integrate.DoubleExponential((x) => Math.Exp(-x * x / 2), a, b),
                1e-10,
                "DET Integral of e^(-x^2 /2) from {0} to {1}", a, b);

            Assert.AreEqual(
                expected,
                Integrate.GaussKronrod((x) => Math.Exp(-x * x / 2), a, b),
                1e-10,
                "GK Integral of e^(-x^2 /2) from {0} to {1}", a, b);

            Assert.AreEqual(
                expected,
                Integrate.GaussLegendre((x) => Math.Exp(-x * x / 2), a, b, order: 128),
                1e-10,
                "GL Integral of e^(-x^2 /2) from {0} to {1}", a, b);
        }
Beispiel #22
0
        public void TestIntegralOfSinc(double a, double b, double expected, double factor)
        {
            Assert.AreEqual(
                expected,
                factor * Integrate.DoubleExponential((x) => 1 / (1 + x * x), a, b),
                1e-10,
                "DET Integral of sin(pi*x)/(pi*x) from {0} to {1}", a, b);

            Assert.AreEqual(
                expected,
                factor * Integrate.GaussKronrod((x) => 1 / (1 + x * x), a, b),
                1e-10,
                "GK Integral of sin(pi*x)/(pi*x) from {0} to {1}", a, b);

            Assert.AreEqual(
                expected,
                factor * Integrate.GaussLegendre((x) => 1 / (1 + x * x), a, b, order: 128),
                1e-10,
                "GL Integral of sin(pi*x)/(pi*x) from {0} to {1}", a, b);
        }
Beispiel #23
0
        public virtual Length GetArcLength()
        {
            double length = GetFinalPoint().X.GetBasicVal();

            if (Settings.Quantities.Α.IsRight() || length == 0)
            {
                return(new Length(2.0 * GetHighestPoint().Y.GetBasicVal() - Settings.Quantities.H.GetBasicVal(), UnitLength.Basic));
            }

            return(new Length(
                       Integrate.OnClosedInterval(
                           x => Math.Sqrt(
                               1 + Math.Pow(
                                   Math.Tan(Settings.Quantities.Α.GetBasicVal()) -
                                   Settings.Quantities.G.GetBasicVal() /
                                   Math.Pow(GetInitialPoint().Vx.GetBasicVal(), 2.0) * x, 2.0)
                               ), 0, length
                           ), UnitLength.Basic
                       ));
        }
        /// <summary>
        /// Compute correlation matrix
        /// </summary>
        /// <param name="t"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        private Matrix <double> CorrelationMatrix(double t, double dt)
        {
            var C = Matrix <double> .Build.Dense(NumRates, NumRates);

            for (var i = 0; i < NumRates; i++)
            {
                for (var j = 0; j <= i; j++)
                {
                    var i1 = i;
                    var j1 = j;

                    Func <double, double> func = x => Correlation[i1, j1] * Volatility[i1](T[i1] - x) * Volatility[j1](T[j1] - x);

                    var corr = Integrate.OnClosedInterval(func, t, t + dt);

                    C[i, j] = corr;
                    C[j, i] = corr;
                }
            }
            return(C);
        }
Beispiel #25
0
 private void button1_Click(object sender, EventArgs e)
 {
     try
     {
         double xp = Double.Parse(textBox7.Text);
         double xk = Double.Parse(textBox5.Text);
         int    n  = Int32.Parse(textBox6.Text);
         if (n % 2 == 0 && xp >= xk)
         {
             textBox1.Text = "" + MetodaProstokatow(h, xp, xk, n);
             textBox3.Text = "" + MetodaTrapezow(h, xp, xk, n);
             textBox4.Text = "" + Integrate.OnClosedInterval(h, xp, xk);
             textBox2.Text = "" + MathNet.Numerics.Integration.Algorithms.SimpsonRule.IntegrateComposite(h, xp, xk, n);
         }
         else
         {
             MessageBox.Show("Zły przedział, lub granica górna jest mniejsza od dolnej");
         }
     }
     catch (System.FormatException) { }
 }
Beispiel #26
0
        double ICompute.IntZSq()
        {
            Func <double, double> func;

            switch (Restraint)
            {
            case Restraint.Fixed:
                double Oz = Points.ElasticCenter.Z;
                func = u => Math.Pow(F(u) - Oz, 2) * dL(u);
                break;

            case Restraint.Pinned:
                func = u => Math.Pow(F(u), 2) * dL(u);
                break;

            default:
                var msg = "Restraint is unknown";
                throw new InvalidOperationException(msg);
            }
            return(Integrate.OnClosedInterval(func, -W / 2, W / 2, Prec));
        }
Beispiel #27
0
        /// <summary>
        /// Jointly calculate a call and a put price.
        /// </summary>
        /// <returns></returns>
        internal Vector HestonCallPutPrice()
        {
            double F         = this.s0 * Math.Exp((this.rate - this.dividend) * this.T);
            double firstTerm = 0.5 * (F - this.K);
            double a         = 1E-12;
            double b         = 1000.0;

            // The second term of this expressions approximates the integral in the interval [0,a].
            var integrate = new Integrate(this);

            integrate.Tolerance         = 10e-8;
            integrate.MaxRecursionLevel = 4;// 4;



            double part1    = PerformIntegral(a, b, IntegrandFunc);
            double integral = part1 + a * IntegrandFunc(a / 2.0);
            Vector callPut  = new Vector(2);

            callPut[0] = Math.Exp(-this.rate * this.T) * (firstTerm + integral / Math.PI);
            callPut[1] = Math.Exp(-this.rate * this.T) * (-firstTerm + integral / Math.PI);
            return(callPut);
        }
        private IExpressionType doPredefinedFunc(Function f)
        {
            Computator     comp = new Computator();
            Simplification s    = new Simplification();

            switch (f.getName())
            {
            case "plot":
                MathList mathList = (MathList)f.getOperands()[0];
                Variable var      = (Variable)f.getOperands()[1];
                Interval interval = (Interval)f.getOperands()[2];

                PlotModel plot = new PlotModel(mathList, var, interval);
                plot.drawGraphics();
                return(f);

            case "integrate":
                Integrate       i       = new Integrate((Variable)f.getOperands()[1]);
                IExpressionType operand = f.getOperands()[0].doOperation(comp);
                if (operand.getType() == Types.VarDefinition)
                {
                    return(i.integrate((IMathExpression)operand.getOperands()[1]));
                }
                IExpressionType integrated = i.integrate((IMathExpression)operand);
                return(integrated.doOperation(comp));
            }

            List <IExpressionType> list = new List <IExpressionType>();

            foreach (var op in f.getOperands())
            {
                list.Add(op.doOperation(comp));
            }

            return(s.simplify(new Function(f.getType(), list, f.getName())));
        }
        private EstimationResult QuantLibEstimate(CurveMarketData discoutingCurve, CallPriceMarketData Hdataset)
        {
            EquityCalibrationData HCalData = new EquityCalibrationData(Hdataset, discoutingCurve);

            bool hasArbitrage = HCalData.HasArbitrageOpportunity(10e-2);
            if (hasArbitrage)
                Console.WriteLine("Market data contains arbitrage opportunity");

            this.r = new DVPLDOM.PFunction(discoutingCurve.Durations,discoutingCurve.Values);
            this.q = HCalData.dyFunc as PFunction;

            //this.r.Parse(null);
            //this.q.Parse(null);

            Hdataset.Volatility = new Matrix(Hdataset.CallPrice.R, Hdataset.CallPrice.C);
            for (int i = 0; i < Hdataset.Volatility.R; i++)
            {
                double m=Hdataset.Maturity[i];
                for (int j = 0; j < Hdataset.Volatility.C; j++)
                {
                    if (Hdataset.CallPrice[i, j] > 0)
                    {
                        var bs = new Fairmat.Finance.BlackScholes(r.Evaluate(m), Hdataset.S0, Hdataset.Strike[j], 0, m, q.Evaluate(m));
                        //Hdataset.Volatility[i, j] = Hdataset.Volatility[i, j] * Hdataset.Volatility[i, j] * Hdataset.Maturity[i];

                        //Hdataset.Volatility[i, j] = bs.ImpliedCallVolatility(Hdataset.CallPrice[i, j]);
                    }
                }
            }

            Console.WriteLine(Hdataset.Volatility);

            IFunction impVol = FitImplVolModel(Hdataset);

            Document doc = new Document();
            ProjectROV prj = new ProjectROV(doc);
            doc.Part.Add(prj);
            prj.Symbols.Add(impVol);
            // doc.WriteToXMLFile("impVol.fair");

            int nmat = calibrationSettings.LocalVolatilityMaturities;
            int nstrike = calibrationSettings.LocalVolatilityStrikes;
            double lastMat = Hdataset.Maturity[SymbolicIntervalExtremes.End];
            double lastStr = Hdataset.Strike[SymbolicIntervalExtremes.End];
            Vector locVolMat = Vector.Linspace(Hdataset.Maturity[0], lastMat, nmat);
            Vector locVolStr = Vector.Linspace(Hdataset.Strike[0], lastStr, nstrike);
            Matrix locVolMatrix = new Matrix(nmat, nstrike);
            double t, dt, forwardValue, y, dy, strike, strikep, strikem, w, wp, wm, dwdy;
            double d2wdy2, den1, den2, den3, strikept, strikemt, wpt, wmt, dwdt;
            Integrate integrate = new Integrate(this);

            for (int i = 0; i < nmat; i++)
            {
                t = locVolMat[i];
                forwardValue = Hdataset.S0 * Math.Exp(integrate.AdaptLobatto(0.0, t));
                for (int j = 0; j < nstrike; j++)
                {
                    strike = locVolStr[j];
                    y = Math.Log(strike / forwardValue);
                    dy = ((Math.Abs(y) > 0.001) ? y * 0.0001 : 0.000001);

                    // strike derivative
                    strikep = strike * Math.Exp(dy);
                    strikem = strike / Math.Exp(dy);
                    w = impVol.Evaluate(t, strike);
                    wp = impVol.Evaluate(t, strikep);
                    wm = impVol.Evaluate(t, strikem);
                    dwdy = (wp - wm) / (2.0 * dy);
                    d2wdy2 = (wp - 2.0 * w + wm) / (dy * dy);

                    // time derivative
                    if (t == 0.0)
                    {
                        dt = 0.0001;
                        strikept = strike * Math.Exp(integrate.AdaptLobatto(0.0, t + dt));
                        wpt = impVol.Evaluate(t + dt, strikept);
                        // if (wpt < w)
                        //    Console.WriteLine("Decreasing variance at strike {0} between time {1} and time {2}", strike, t, t + dt);
                        dwdt = (wpt - w) / dt;
                    }
                    else
                    {
                        dt = Math.Min(0.0001, t / 2.0);
                        strikept = strike * Math.Exp(integrate.AdaptLobatto(t, t + dt));
                        strikemt = strike * Math.Exp(-integrate.AdaptLobatto(t - dt, t));
                        wpt = impVol.Evaluate(t + dt, strikept);
                        wmt = impVol.Evaluate(t + dt, strikemt);

                        //if (wpt < w)
                        //    Console.WriteLine("Decreasing variance at strike {0} between time {1} and time {2}", strike, t, t + dt);
                        //if (w < wmt)
                        //    Console.WriteLine("Decreasing variance at strike {0} between time {1} and time {2}", strike, t-dt, t);
                        dwdt = (wpt - wmt) / (2.0 * dt);
                    }
                    if (dwdy == 0.0 && d2wdy2 == 0.0)
                        locVolMatrix[i, j] = Math.Sqrt(dwdt);
                    else
                    {
                        den1 = 1.0 - y / w * dwdy;
                        den2 = 0.25 * (-0.25 - 1.0 / w + y * y / w / w) * dwdy * dwdy;
                        den3 = 0.5 * d2wdy2;
                        locVolMatrix[i, j] = dwdt / (den1 + den2 + den3);
                        //if (locVolMatrix[i,j] < 0.0)
                        //    Console.WriteLine("Negative local vol^2 at strike {0} and time {1}; " +
                        //        "Black vol surface is not smooth enought.", strike, t);
                    }
                }
            }

            // Create dupire outputs.
            Console.WriteLine(locVolMat);
            PFunction2D.PFunction2D localVol = new PFunction2D.PFunction2D(locVolMat, locVolStr, locVolMatrix);
            localVol.Parse(null);
            string[] names = new string[] { "S0" };
            Vector param = new Vector(1);
            param[0] = Hdataset.S0;
            EstimationResult result = new EstimationResult(names, param);
            //result.Objects = new object[3];
            result.Objects = new object[4];
            result.Objects[0] = this.r;
            result.Objects[1] = this.q;
            result.Objects[2] = localVol;
            result.Objects[3] = impVol;
            //Console.WriteLine("r = " + HCalData.Rate.ToString());
            //Console.WriteLine("q = " + HCalData.DividendYield.ToString());
            return result;
        }
Beispiel #30
0
        private Matrix LocVolMatrixFromCallPrices(CallPriceMarketData Hdataset, CallPriceSurface CallPrice, out Vector locVolMat, out Vector locVolStr)
        {
            Integrate integrate = new Integrate(this);

            int nmat = calibrationSettings.LocalVolatilityMaturities;
            int nstrike = calibrationSettings.LocalVolatilityStrikes;

            double firstMat = CallPrice.MinMaturity;
            double lastMat = CallPrice.MaxMaturity;

            double firstStr =  CallPrice.MinStrike;
            double lastStr = CallPrice.MaxStrike;
            double delta = (lastStr - firstStr) / nstrike;
            locVolMat = Vector.Linspace(firstMat, lastMat, nmat);
            locVolStr = Vector.Linspace(firstStr + delta, lastStr - delta, nstrike);
            Matrix locVolMatrix = new Matrix(nmat, nstrike);

            // this next matrix is created only for debugging pourpose
            Matrix squaredLocVolMatrix = new Matrix(nmat, nstrike);
            double num, den, call, dCdt, dCdk, d2Cdk2;
            Vector x = new Vector(2);
            double h0 = 0.02*Hdataset.S0;//increment for numerical derivatives (stock)
            double ht = 0.02;// 0.25 * (lastMat - firstMat) / nmat;//increment for numerical derivatives (maturities)
            double hs = h0;
            double d2Threshold=10e-5;
            for (int i = 0; i < nmat; i++)
            {
                double growthRate = integrate.AdaptLobatto(0.0, locVolMat[i]);
                x[0] = locVolMat[i];
                for (int j = 0; j < nstrike; j++)
                {
                    x[1] = locVolStr[j];

                    var support=CallPrice.SupportY(x[0]);
                    //if (x[1] > support[1] && j > 1)
                    if(x[1]<support[0]||x[1]>support[1])
                    {
                        //skip...fill later
                        //squaredLocVolMatrix[i, j] = squaredLocVolMatrix[i, j - 1];
                        //locVolMatrix[i, j] = locVolMatrix[i, j-1];
                    }
                    else
                    {
                        bool fail = false;
                        call = CallPrice.Evaluate(x);
                        dCdt = CallPrice.Partial(x, 0, ht);
                        //do
                       // {

                            dCdk = CallPrice.Partial(x, 1, hs);
                            d2Cdk2 = CallPrice.Partial2(x, 1, hs);
                            //if (Math.Abs(d2Cdk2) > d2Threshold || hs > 0.1 * Hdataset.S0)
                            if (Math.Abs(d2Cdk2) < d2Threshold)
                            {
                                fail = true;
                                //break;
                            }
                        //    hs *= 2;
                        //} while (true);

                        if (!fail)
                        {
                            double qq = this.q.Evaluate(x[0]);
                            num = dCdt + growthRate * x[1] * dCdk + qq * call;
                            den = x[1] * x[1] * d2Cdk2;
                            squaredLocVolMatrix[i, j] = 2.0 * num / den;
                            locVolMatrix[i, j] = Math.Sqrt(Math.Abs(2.0 * num / den));
                        }
                    }
                }
            }

            //Fill missing vol
            for (int i = 0; i < nmat; i++)
            {
                double lastVol=0;
                for (int j = 0; j < nstrike; j++)
                {
                    if (locVolMatrix[i, j] != 0)
                        lastVol = locVolMatrix[i, j];
                    else
                        locVolMatrix[i, j] = lastVol;
                }
                lastVol = 0;
                for (int j = nstrike-1; j >=0; j--)
                {
                    if (locVolMatrix[i, j] != 0)
                        lastVol = locVolMatrix[i, j];
                    else
                        locVolMatrix[i, j] = lastVol;
                }
                //

            }

            return locVolMatrix;
        }
Beispiel #31
0
        /// <summary>
        /// Jointly calculate a call and a put price.
        /// </summary>
        /// <returns></returns>
        internal Vector HestonCallPutPrice()
        {
            double F = this.s0 * Math.Exp((this.rate - this.dividend) * this.T);
            double firstTerm = 0.5 * (F - this.K);
            double a = 1E-12;
            double b = 1000.0;

            // The second term of this expressions approximates the integral in the interval [0,a].
            var integrate = new Integrate(this);
            integrate.Tolerance = 10e-8;
            integrate.MaxRecursionLevel = 4;// 4;

            double part1 = PerformIntegral(a, b, IntegrandFunc);
            double integral = part1 + a * IntegrandFunc(a / 2.0);
            Vector callPut= new Vector(2);
            callPut[0] = Math.Exp(-this.rate * this.T) * (firstTerm + integral / Math.PI);
            callPut[1] = Math.Exp(-this.rate * this.T) * (-firstTerm + integral / Math.PI);
            return callPut;
        }
Beispiel #32
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        if (cameraTransform == null)
        {
            cameraTransform = GameObject.Find("Main Camera").transform;
        }

        EntityManager.GetAllUniqueSharedComponentData(uniqueTypes);

        ComponentDataArray <SPHCollider> colliders = SPHColliderGroup.GetComponentDataArray <SPHCollider>();
        int colliderCount = colliders.Length;

        for (int typeIndex = 1; typeIndex < uniqueTypes.Count; typeIndex++)
        {
            // Get the current chunk setting
            SPHParticle settings = uniqueTypes[typeIndex];
            SPHCharacterGroup.SetFilter(settings);

            // Cache the data
            ComponentDataArray <Position>    positions  = SPHCharacterGroup.GetComponentDataArray <Position>();
            ComponentDataArray <SPHVelocity> velocities = SPHCharacterGroup.GetComponentDataArray <SPHVelocity>();

            int cacheIndex    = typeIndex - 1;
            int particleCount = positions.Length;

            NativeMultiHashMap <int, int> hashMap = new NativeMultiHashMap <int, int>(particleCount, Allocator.TempJob);

            NativeArray <Position>    particlesPosition = new NativeArray <Position>(particleCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
            NativeArray <SPHVelocity> particlesVelocity = new NativeArray <SPHVelocity>(particleCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
            NativeArray <float3>      particlesForces   = new NativeArray <float3>(particleCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
            NativeArray <float>       particlesPressure = new NativeArray <float>(particleCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
            NativeArray <float>       particlesDensity  = new NativeArray <float>(particleCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
            NativeArray <int>         particleIndices   = new NativeArray <int>(particleCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);

            NativeArray <int>         cellOffsetTableNative = new NativeArray <int>(cellOffsetTable, Allocator.TempJob);
            NativeArray <SPHCollider> copyColliders         = new NativeArray <SPHCollider>(colliderCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);



            // Add new or dispose previous particle chunks
            PreviousParticle nextParticles = new PreviousParticle
            {
                hashMap           = hashMap,
                particlesPosition = particlesPosition,
                particlesVelocity = particlesVelocity,
                particlesForces   = particlesForces,
                particlesPressure = particlesPressure,
                particlesDensity  = particlesDensity,
                particleIndices   = particleIndices,
                cellOffsetTable   = cellOffsetTableNative,
                copyColliders     = copyColliders
            };

            if (cacheIndex > previousParticles.Count - 1)
            {
                previousParticles.Add(nextParticles);
            }
            else
            {
                previousParticles[cacheIndex].hashMap.Dispose();
                previousParticles[cacheIndex].particlesPosition.Dispose();
                previousParticles[cacheIndex].particlesVelocity.Dispose();
                previousParticles[cacheIndex].particlesForces.Dispose();
                previousParticles[cacheIndex].particlesPressure.Dispose();
                previousParticles[cacheIndex].particlesDensity.Dispose();
                previousParticles[cacheIndex].particleIndices.Dispose();
                previousParticles[cacheIndex].cellOffsetTable.Dispose();
                previousParticles[cacheIndex].copyColliders.Dispose();
            }
            previousParticles[cacheIndex] = nextParticles;



            // Copy the component data to native arrays
            CopyComponentData <Position> particlesPositionJob = new CopyComponentData <Position> {
                Source = positions, Results = particlesPosition
            };
            JobHandle particlesPositionJobHandle = particlesPositionJob.Schedule(particleCount, 64, inputDeps);

            CopyComponentData <SPHVelocity> particlesVelocityJob = new CopyComponentData <SPHVelocity> {
                Source = velocities, Results = particlesVelocity
            };
            JobHandle particlesVelocityJobHandle = particlesVelocityJob.Schedule(particleCount, 64, inputDeps);

            CopyComponentData <SPHCollider> copyCollidersJob = new CopyComponentData <SPHCollider> {
                Source = colliders, Results = copyColliders
            };
            JobHandle copyCollidersJobHandle = copyCollidersJob.Schedule(colliderCount, 64, inputDeps);

            MemsetNativeArray <float> particlesPressureJob = new MemsetNativeArray <float> {
                Source = particlesPressure, Value = 0.0f
            };
            JobHandle particlesPressureJobHandle = particlesPressureJob.Schedule(particleCount, 64, inputDeps);

            MemsetNativeArray <float> particlesDensityJob = new MemsetNativeArray <float> {
                Source = particlesDensity, Value = 0.0f
            };
            JobHandle particlesDensityJobHandle = particlesDensityJob.Schedule(particleCount, 64, inputDeps);

            MemsetNativeArray <int> particleIndicesJob = new MemsetNativeArray <int> {
                Source = particleIndices, Value = 0
            };
            JobHandle particleIndicesJobHandle = particleIndicesJob.Schedule(particleCount, 64, inputDeps);

            MemsetNativeArray <float3> particlesForcesJob = new MemsetNativeArray <float3> {
                Source = particlesForces, Value = new float3(0, 0, 0)
            };
            JobHandle particlesForcesJobHandle = particlesForcesJob.Schedule(particleCount, 64, inputDeps);



            // Put positions into a hashMap
            HashPositions hashPositionsJob = new HashPositions
            {
                positions  = particlesPosition,
                hashMap    = hashMap.ToConcurrent(),
                cellRadius = settings.radius
            };
            JobHandle hashPositionsJobHandle = hashPositionsJob.Schedule(particleCount, 64, particlesPositionJobHandle);

            JobHandle mergedPositionIndicesJobHandle = JobHandle.CombineDependencies(hashPositionsJobHandle, particleIndicesJobHandle);

            MergeParticles mergeParticlesJob = new MergeParticles
            {
                particleIndices = particleIndices
            };
            JobHandle mergeParticlesJobHandle = mergeParticlesJob.Schedule(hashMap, 64, mergedPositionIndicesJobHandle);

            JobHandle mergedMergedParticlesDensityPressure = JobHandle.CombineDependencies(mergeParticlesJobHandle, particlesPressureJobHandle, particlesDensityJobHandle);

            // Compute density pressure
            ComputeDensityPressure computeDensityPressureJob = new ComputeDensityPressure
            {
                particlesPosition = particlesPosition,
                densities         = particlesDensity,
                pressures         = particlesPressure,
                hashMap           = hashMap,
                cellOffsetTable   = cellOffsetTableNative,
                settings          = settings
            };
            JobHandle computeDensityPressureJobHandle = computeDensityPressureJob.Schedule(particleCount, 64, mergedMergedParticlesDensityPressure);

            JobHandle mergeComputeDensityPressureVelocityForces = JobHandle.CombineDependencies(computeDensityPressureJobHandle, particlesForcesJobHandle, particlesVelocityJobHandle);

            // Compute forces
            ComputeForces computeForcesJob = new ComputeForces
            {
                particlesPosition = particlesPosition,
                particlesVelocity = particlesVelocity,
                particlesForces   = particlesForces,
                particlesPressure = particlesPressure,
                particlesDensity  = particlesDensity,
                cellOffsetTable   = cellOffsetTableNative,
                hashMap           = hashMap,
                settings          = settings
            };
            JobHandle computeForcesJobHandle = computeForcesJob.Schedule(particleCount, 64, mergeComputeDensityPressureVelocityForces);

            // Integrate
            Integrate integrateJob = new Integrate
            {
                particlesPosition = particlesPosition,
                particlesVelocity = particlesVelocity,
                particlesDensity  = particlesDensity,
                particlesForces   = particlesForces
            };
            JobHandle integrateJobHandle = integrateJob.Schedule(particleCount, 64, computeForcesJobHandle);

            JobHandle mergedIntegrateCollider = JobHandle.CombineDependencies(integrateJobHandle, copyCollidersJobHandle);

            // Compute Colliders
            ComputeColliders computeCollidersJob = new ComputeColliders
            {
                particlesPosition = particlesPosition,
                particlesVelocity = particlesVelocity,
                copyColliders     = copyColliders,
                settings          = settings
            };
            JobHandle computeCollidersJobHandle = computeCollidersJob.Schedule(particleCount, 64, mergedIntegrateCollider);

            // Apply positions
            ApplyPositions applyPositionsJob = new ApplyPositions
            {
                particlesPosition = particlesPosition,
                particlesVelocity = particlesVelocity,
                positions         = positions,
                velocities        = velocities
            };
            JobHandle applyPositionsJobHandle = applyPositionsJob.Schedule(particleCount, 64, computeCollidersJobHandle);

            inputDeps = applyPositionsJobHandle;
        }

        // Done
        uniqueTypes.Clear();
        return(inputDeps);
    }
Beispiel #33
0
 public virtual double XToLength(double x)
 {
     return(Integrate.OnClosedInterval(dL, -W / 2, x));
 }
Beispiel #34
0
        private Matrix LocVolMatrixFromImpliedVol(CallPriceMarketData Hdataset, IFunction impVol, out Vector locVolMat, out Vector locVolStr)
        {
            int nmat = calibrationSettings.LocalVolatilityMaturities;
            int nstrike = calibrationSettings.LocalVolatilityStrikes;
            double lastMat = Hdataset.Maturity[Range.End];
            double lastStr = Hdataset.Strike[Range.End];
            locVolMat = Vector.Linspace(Hdataset.Maturity[0], lastMat, nmat);
            locVolStr = Vector.Linspace(Hdataset.Strike[0], lastStr, nstrike);
            Matrix locVolMatrix = new Matrix(nmat, nstrike);

            Integrate integrate = new Integrate(this);
            double sigma, dSigmadk, num, y, den, avgGrowthRate;
            Vector x = new Vector(2);
            for (int i = 0; i < nmat; i++)
            {
                avgGrowthRate = integrate.AdaptLobatto(0.0, locVolMat[i]);

                int j = 0;
                x[0] = locVolMat[i];
                x[1] = locVolStr[j];
                sigma = impVol.Evaluate(x);
                dSigmadk = impVol.Partial(x, 1);
                num = Math.Pow(sigma, 2) + 2.0 * sigma * x[0] * impVol.Partial(x, 0);
                den = 1.0;
                locVolMatrix[i, j] = Math.Sqrt(num / den);

                // The rest of the cycle.
                for (j = 1; j < nstrike; j++)
                {
                    x[1] = locVolStr[j];
                    sigma = impVol.Evaluate(x);
                    dSigmadk = impVol.Partial(x, 1);
                    num = Math.Pow(sigma, 2) + 2.0 * sigma * x[0] *
                        (impVol.Partial(x, 0) + avgGrowthRate * x[1] * dSigmadk);
                    y = Math.Log(locVolStr[j] / Hdataset.S0) + avgGrowthRate;
                    den = System.Math.Pow(1.0 - x[1] * y * dSigmadk / sigma, 2) + x[1] * sigma * x[0] *
                        (dSigmadk - 0.25 * x[1] * sigma * x[0] * dSigmadk * dSigmadk + x[1] * impVol.Partial2(x, 1));
                    locVolMatrix[i, j] = Math.Sqrt(num / den);
                }
            }
            return locVolMatrix;
        }