public double[] bucketedCS01FromCreditCurve(
            CDS cds,
            double cdsCoupon,
            CDS[] bucketCDSs,
            YieldTermStructure yieldCurve,
            PiecewiseconstantHazardRate creditCurve)
        {
            int             n       = bucketCDSs.Length;
            Vector <double> vLambda = Vector <double> .Build.Random(n);

            for (int i = 0; i < n; i++)
            {
                vLambda[i] = _pricer.pvCreditSensitivity(cds, yieldCurve, creditCurve, cdsCoupon, i);
            }

            Matrix <double> jacT = Matrix <double> .Build.Random(n, n);

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    jacT[i, j] = _pricer.parSpreadCreditSensitivity(bucketCDSs[j], yieldCurve, creditCurve, i);
                }
            }

            LU <double>     LUResult = jacT.LU();
            Vector <double> vS       = LUResult.Solve(vLambda);

            return(vS.ToArray());
        }
Exemplo n.º 2
0
        /// <inheritdoc />
        public IEnumerable <double> LowerUpperFactorizeAndSolve(IEnumerable <double> colleyRatings)
        {
            LU <double>     lowerUpper    = _sparseMatrix.LU();
            Vector          ratingsVector = new DenseVector(colleyRatings.ToArray());
            Vector <double> solvedVector  = lowerUpper.Solve(ratingsVector);

            return(solvedVector.AsArray());
        }
Exemplo n.º 3
0
        public Vector3D MinError()
        {
            var lu = new LU(Derivative(), 4);

            lu.Decompose();
            var x = new double[4];

            lu.Solve(new double[] { 0.0, 0.0, 0.0, 1.0 }, ref x);
            return(new Vector3D(x[0], x[1], x[2]));
        }
Exemplo n.º 4
0
        public double[] getHedgeRatios(double[] cdsSensitivities, LU <double> luRes)
        {
            int             n       = cdsSensitivities.Length;
            Vector <double> vLambda = Vector <double> .Build.Random(n);

            for (int i = 0; i < n; i++)
            {
                vLambda[i] = cdsSensitivities[i];
            }

            double[] w = luRes.Solve(vLambda).ToArray();
            return(w);
        }
Exemplo n.º 5
0
    void Test03()
    {
        var A = new double[] {
            -1, 1, 1,
            1, -1, 1,
            1, 1, -1
        };
        var lu = new LU(A, 3);

        var b    = new double[] { -3, 1, 1 };
        var refX = new double[] { 1, -1, -1 };
        var x    = new double[3];

        lu.Solve(b, ref x);
        AssertX(b, refX);
    }
        public void ShouldRegress()
        {
            var X = new Matrix(new double[, ]
            {
                { 13.0, 12.0, 0.0 },
                { 15.0, 19.0, 0.0 },
                { 12.0, 23.0, 0.0 },
                { 13.0, 30.0, 1.0 },
                { 13.0, 22.0, 1.0 },
                { 16.0, 11.0, 0.0 },
                { 15.0, 13.0, 1.0 },
                { 16.0, 28.0, 1.0 },
                { 15.0, 10.0, 1.0 },
                { 16.0, 11.0, 1.0 }
            });

            var Y = new Vector(new double[]
            {
                34.12,
                40.94,
                33.58,
                38.95,
                35.42,
                32.12,
                28.57,
                40.47,
                32.06,
                30.55
            });

            Debug.WriteLine($"Data:\n{X.ConcatColumns(Y):F2}");

            var Xdesign = new Vector(X.Rows).Fill(1).ConcatColumns(X);

            Debug.WriteLine($"Design:\n{Xdesign:F2}");

            var coef = LU.Solve(Xdesign, Y);

            var r2 = X.ConcatColumns(Y).RSquared(coef);

            Debug.Print($"R2={r2}");

            var y = MatrixMath.Predict(new double[] { 14, 12, 0 }, coef);

            Debug.Print($"Prediction is {y}");
        }
Exemplo n.º 7
0
    void Test01()
    {
        var A = new double[] {
            1, 2, 3, 4,
            2, 3, 4, 1,
            3, 4, 1, 2,
            4, 1, 2, 3,
        };
        var lu = new LU(A, 4);

        var b = new double[] { 16, 14, 16, 14 };
        var x = new double[4];

        lu.Solve(b, ref x);
        var refX = new double[] { 1, 2, 1, 2 };

        AssertX(x, refX);
    }
Exemplo n.º 8
0
    void Test02()
    {
        var A = new double[] {
            0, 1, 2,
            2, 0, 1,
            1, 2, 0
        };
        var lu    = new LU(A, 3);
        var refLu = new double[] {
            2f, 0f, 1f,
            1f / 2, 2f, -1f / 2,
            0f, 1f / 2, 9f / 4
        };

        AssertLU(lu, refLu);

        var b    = new double[] { 8, 5, 5 };
        var x    = new double[3];
        var refX = new double[] { 1, 2, 3 };

        lu.Solve(b, ref x);
        AssertX(x, refX);
    }
        public double[][] bucketedCS01FromCreditCurve(
            CDS[] cds,
            double[] cdsCoupon,
            CDS[] bucketCDSs,
            YieldTermStructure yieldCurve,
            PiecewiseconstantHazardRate creditCurve)
        {
            int m = cds.Length;
            LUDecompositionCommons decomp = new LUDecompositionCommons();
            int n = bucketCDSs.Length;


            Matrix <double> jacT = Matrix <double> .Build.Random(n, n);

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    jacT[i, j] = _pricer.parSpreadCreditSensitivity(bucketCDSs[j], yieldCurve, creditCurve, i);
                }
            }
            Vector <double> vLambda = Vector <double> .Build.Random(n);

            double[][]  res      = new double[m][];
            LU <double> LUResult = jacT.LU();

            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    vLambda[j] = _pricer.pvCreditSensitivity(cds[i], yieldCurve, creditCurve, cdsCoupon[i], j);
                }
                res[i] = LUResult.Solve(vLambda).ToArray();
            }
            return(res);
        }
Exemplo n.º 10
0
        private void Solve()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            double[] h            = new double[Codend.dof];
            double   PrevTowSpeed = Codend.towSpeed;
            int      PrevCatch    = Codend.GetMeshesBlocked();

            SparseLU LU;
            var      LUorder     = ColumnOrdering.MinimumDegreeAtPlusA;
            double   LUtolerance = 1.0;

            bool hasConverged    = false;                       // convergence flag
            bool correctSolution = false;                       // correctness of solution flag
            bool hasDiverged     = false;                       // restart flag
            bool usePrecalc      = CheckPrecalc();
            int  restartsCount   = 0;
            int  iter            = 0;

            double hNorm     = 1;
            double addStiff  = SolverSettings.DiagStiffness;
            double addStiff0 = SolverSettings.DiagStiffness;
            double tolStiff  = SolverSettings.StiffnessTol;

            //=============================
            // Start calculation
            //=============================

            for (int stage = 1; stage <= 2; stage++)
            {
                //===========================
                // Restarts loop
                //===========================

                while (!correctSolution)
                {
                    // Set initial shape depending on whether it is precalculated from previous stage or not
                    Codend.ClearState();

                    SetStageInitialShape(stage);

                    Codend.UpdateTotalForces(IncludeBC: true);
                    Codend.UpdateResidual();

                    if (addStiff0 == 0 && restartsCount > 0)  // if the scheme doesnt work without extra stiffness
                    {
                        addStiff0 = 1;
                    }
                    addStiff = addStiff0;
                    tolStiff = SolverSettings.StiffnessTol;
                    //===========================
                    // Newton-Raphson loop
                    //===========================

                    while (!hasConverged)
                    {
                        // check if diverged
                        if (Codend.R > SolverSettings.ResidualMax)
                        {
                            hasDiverged = true;
                            break;
                        }

                        // check whether to add less diagonal stiffness
                        if (Codend.R < tolStiff)
                        {
                            addStiff *= SolverSettings.ReduceStiffnessBy;
                            tolStiff *= SolverSettings.ReduceStiffnessBy;
                        }

                        // check if converged and no stiffness is added
                        if (Codend.R < SolverSettings.ResidualTol && hNorm < SolverSettings.DisplacementTol)
                        {
                            break;
                        }

                        Codend.UpdateTotalJacobian(kDiag: -addStiff, IncludeBC: true);

                        LU = SparseLU.Create(Codend.J, LUorder, LUtolerance);
                        LU.Solve(Codend.F, h);

                        hNorm = DisplacmentNorm(h);
                        Codend.UpdatePosition(h, 1);

                        Codend.UpdateTotalForces(IncludeBC: true);
                        Codend.UpdateResidual();

                        iter++;                                                   // display iteration status
                        Console.WriteLine(
                            PrintIter(iter, 0, addStiff, Codend.R, hNorm));
                    }

                    //===================
                    // Restart routine
                    //===================

                    if (hasDiverged || IsIncorrectSolution())
                    {
                        restartsCount += 1;
                        addStiff0     *= SolverSettings.IncreaseStiffnessBy;
                        ReportRestartCause(hasDiverged);
                        hasDiverged = false;
                    }
                    else
                    {
                        correctSolution = true; // correct solution found
                        Console.WriteLine("\nConvergence acheived in {0} iterations and {1} restarts in {2} [ms]\n",
                                          iter, restartsCount, stopwatch.ElapsedMilliseconds);
                    }
                }


                if (usePrecalc)
                {
                    Codend.X.CopyTo(precalcX, 0);
                    Codend.ApplyCatch(PrevCatch);
                    Codend.ApplyTowing(PrevTowSpeed);

                    Console.WriteLine("\nInitial shape is precalculated. Moiving to and actual case.\n");
                    correctSolution = false;
                    usePrecalc      = false;
                    hasConverged    = false;
                }
                else
                {
                    break;
                }
            }
        }
Exemplo n.º 11
0
        public static void SolveSparseLU(this SparseMatrix matrix, Vector <double> result, Vector <double> rhs, double tol = 1.0)
        {
            LU lu = matrix.SparseLU(tol: tol);

            lu.Solve(rhs, result);
        }
Exemplo n.º 12
0
    public List <Vector <double> > CalculateARAPMesh(Vector3 targetPosition, int vertexIndex)
    {
        // A temporary vector to hold all the edge products for all the vertices.
        // This is the S matrix in equation (5).

        List <Matrix <double> > edge_product = new List <Matrix <double> >();

        for (int i = 0; i < mesh_vertices.Count; i++)
        {
            Matrix <double> edge_product_ = Matrix <double> .Build.Dense(3, 3);

            foreach (int j in neighbors[i])
            {
                double          weight      = weights[i, j];
                Matrix <double> edge        = mesh_vertices[i].ToRowMatrix() - mesh_vertices[j].ToRowMatrix();
                Matrix <double> edge_update =
                    deformed_vertices[i].ToRowMatrix() - deformed_vertices[j].ToRowMatrix();

                edge_product_ += weight * edge.Transpose() * edge_update;
                edge_product.Add(edge_product_);
            }
        }

        for (int v = 0; v < mesh_vertices.Count; ++v)
        {
            Svd <double>    svd      = edge_product[v].Svd(true);
            Matrix <double> rotation = svd.U.Transpose() * svd.VT.Transpose();
            rotations[v] = rotation;
        }

        // Step 2: compute the rhs in equation (9).
        // The right hand side of equation (9). The x, y and z coordinates are
        // computed separately.
        Matrix <double> rhs = Matrix <double> .Build.Dense(free_indices.Count, 3);

        for (int i = 0; i < free_indices.Count; ++i)
        {
            int i_pos = free_indices[i];
            foreach (int j_pos in neighbors[i_pos])
            {
                double          weight = weights[i_pos, j_pos];
                Matrix <double> vec    = weight * 0.5d
                                         * (rotations[i_pos] + rotations[j_pos])
                                         * (mesh_vertices[i_pos] - mesh_vertices[j_pos]).ToRowMatrix().Transpose();

                rhs.SetRow(i, rhs.Row(i) + vec.Column(0));
                if (fixed_indices.Exists(x => x == j_pos))
                {
                    rhs.SetRow(i, rhs.Row(i) + weight * deformed_vertices[j_pos]);
                }
            }
        }

        // Solve for free_vertices.
        Matrix <double> solution = solver.Solve(rhs);

        for (int i = 0; i < free_indices.Count; ++i)
        {
            int pos = free_indices[i];
            deformed_vertices[pos] = solution.Row(i);
        }


        return(deformed_vertices);
    }
Exemplo n.º 13
0
    public void DeformationPreprocess(Vector3 target_position, int target_idx)
    {
        //free_indices.Remove(target_idx);
        //fixed_indices.Add(target_idx);

        Matrix <double> meshMatrix = Matrix <double> .Build.Dense(
            mesh_vertices.Count, 3);

        Matrix <double> fixedMatrix = Matrix <double> .Build.Dense(
            fixed_indices.Count, 3);

        Matrix <double> deformedMatrix = Matrix <double> .Build.Dense(mesh_vertices.Count, 3);

        for (int i = 0; i < mesh_vertices.Count; i++)
        {
            meshMatrix.SetRow(i, mesh_vertices[i]);
            deformedMatrix.SetRow(i, mesh_vertices[i]);

            if (i < fixed_indices.Count)
            {
                fixedMatrix.SetRow(i, mesh_vertices[fixed_indices[i]]);
            }
        }

        fixedMatrix.SetRow(fixed_indices.Count - 1,
                           Utilities.ConvertFromUVectorToMNVector(target_position));

        Matrix <double> A = Matrix <double> .Build.Sparse(mesh_vertices.Count,
                                                          free_indices.Count);

        Matrix <double> B = Matrix <double> .Build.Sparse(mesh_vertices.Count,
                                                          fixed_indices.Count);

        for (int i = 0; i < mesh_vertices.Count; i++)
        {
            for (int j = 0; j < free_indices.Count; j++)
            {
                A[i, j] = weights[i, free_indices[j]];
            }

            for (int j = 0; j < fixed_indices.Count; j++)
            {
                B[i, j] = weights[i, fixed_indices[j]];
            }
        }

        Matrix <double> left             = A.Transpose() * A;
        LU <double>     naive_lap_solver = left.LU();

        for (int c = 0; c < 3; c++)
        {
            Vector <double> b     = weights * meshMatrix.Column(c) - B * fixedMatrix.Column(c);
            Vector <double> right = A.Transpose() * b;
            Vector <double> x     = naive_lap_solver.Solve(right);

            for (int i = 0; i < free_indices.Count; ++i)
            {
                deformedMatrix[free_indices[i], c] = x[i];
            }
        }


        //// simple initial guess
        //List<Vector<double>> def_vertices = mesh_vertices;
        //Vector<double> targetDistance = Utilities.ConvertFromUVectorToMNVector(target_position) - def_vertices[target_idx];
        //Vector<double> startPosition = def_vertices[target_idx];
        //double maxDistance = 0.0f;
        //for (int i = 0; i < def_vertices.Count; i++)
        //{
        //    double dist = (def_vertices[i] - def_vertices[target_idx]).L2Norm() *
        //        (def_vertices[i] - def_vertices[target_idx]).L2Norm();
        //    if (dist > maxDistance)
        //    {
        //        maxDistance = (def_vertices[i] - def_vertices[target_idx]).L2Norm();
        //    }
        //}
        //for (int i = 0; i < def_vertices.Count; i++)
        //{
        //    double dist = (def_vertices[i] - startPosition).L2Norm() *
        //        (def_vertices[i] - startPosition).L2Norm();
        //    double originalDistance = dist / maxDistance;
        //    def_vertices[i] += targetDistance * (1 - originalDistance);
        //    for (int c = 0; c < 3; c++)
        //    {
        //        deformedMatrix[i, c] = def_vertices[i][c];
        //    }
        //}


        // initial rotation
        deformed_vertices = new List <Vector <double> >();
        for (int i = 0; i < mesh_vertices.Count; i++)
        {
            deformed_vertices.Add(deformedMatrix.Row(i));
        }

        for (int i = 0; i < fixed_indices.Count; i++)
        {
            deformed_vertices[fixed_indices[i]] = fixedMatrix.Row(i);
        }

        List <Matrix <double> > edge_product = new List <Matrix <double> >();

        for (int i = 0; i < mesh_vertices.Count; i++)
        {
            Matrix <double> edge_product_ = Matrix <double> .Build.Dense(3, 3);

            foreach (int j in neighbors[i])
            {
                double          weight      = weights[i, j];
                Matrix <double> edge        = mesh_vertices[i].ToRowMatrix() - mesh_vertices[j].ToRowMatrix();
                Matrix <double> edge_update =
                    deformed_vertices[i].ToRowMatrix() - deformed_vertices[j].ToRowMatrix();

                edge_product_ += weight * edge.Transpose() * edge_update;
                edge_product.Add(edge_product_);
            }
        }

        rotations = new List <Matrix <double> >();
        for (int v = 0; v < mesh_vertices.Count; ++v)
        {
            Svd <double>    svd      = edge_product[v].Svd(true);
            Matrix <double> rotation = svd.U.Transpose() * svd.VT.Transpose();
            rotations.Add(rotation);
        }
    }
Exemplo n.º 14
0
        /// <summary>
        ///     Perform one iteration of training.
        /// </summary>
        public void Iteration()
        {
            int rowCount   = _trainingData.Count;
            int coeffCount = _algorithm.LongTermMemory.Length;

            var working = new double[rowCount, coeffCount];
            var errors  = new double[rowCount];
            var weights = new double[rowCount];

            for (int i = 0; i < rowCount; i++)
            {
                BasicData element = _trainingData[i];

                working[i, 0] = 1;
                for (int j = 0; j < element.Input.Length; j++)
                {
                    working[i, j + 1] = element.Input[j];
                }
            }

            for (int i = 0; i < rowCount; i++)
            {
                BasicData element = _trainingData[i];
                double    y       = _algorithm.ComputeRegression(element.Input)[0];
                errors[i]  = y - element.Ideal[0];
                weights[i] = y * (1.0 - y);
            }

            for (int i = 0; i < coeffCount; i++)
            {
                _gradient[i, 0] = 0;
                for (int j = 0; j < coeffCount; j++)
                {
                    _hessian[i, j] = 0;
                }
            }

            for (int j = 0; j < rowCount; j++)
            {
                for (int i = 0; i < coeffCount; i++)
                {
                    _gradient[i, 0] += working[j, i] * errors[j];
                }
            }

            for (int k = 0; k < weights.Length; k++)
            {
                for (int j = 0; j < coeffCount; j++)
                {
                    for (int i = 0; i < coeffCount; i++)
                    {
                        _hessian[j, i] += working[k, i] * working[k, j] * weights[k];
                    }
                }
            }

            LU <double> lu = _hessian.LU();

            Matrix <double> deltas = lu.Solve(_gradient);

            var prev = (double[])_algorithm.LongTermMemory.Clone();

            for (int i = 0; i < _algorithm.LongTermMemory.Length; i++)
            {
                _algorithm.LongTermMemory[i] -= deltas[i, 0];
            }

            double max = 0;

            for (int i = 0; i < deltas.ColumnCount; i++)
            {
                max = Math.Max(Math.Abs(deltas[i, 0]) / Math.Abs(prev[i]), max);
            }

            _error = max;
        }
Exemplo n.º 15
0
 public void Init()
 {
     decomposition.Solve(new DenseVector(Columns, 0));
 }