예제 #1
0
        /// <summary>
        /// returns the eigen values and eigen vectors of a matrix
        /// IMPORTANT: THIS METHOD NEEDS DEBUGGING.
        /// IT RETURNS THE NEGATIVE VALUES OF THE EIGEN VECTORS ON A TOY EXMAPLE
        ///                 double[,] matrix = {
        ///                                { 3.0, -1.0 },
        ///                                { -1.0, 3.0 }
        ///                            };
        /// eigen values are correct ie, 2.0, 4.0; but in the wrong order.
        /// </summary>
        public static Tuple <double[], double[, ]> EigenVectors(double[,] matrix)
        {
            Evd <double> eigen = DenseMatrix.OfArray(matrix).Evd();
            Vector <System.Numerics.Complex> eigenvaluesComplex = eigen.EigenValues;

            //WriteArrayOfComplexNumbers(eigenvalues);

            double[] eigenvaluesReal = new double[eigenvaluesComplex.Count];
            for (int i = 0; i < eigenvaluesComplex.Count; i++)
            {
                System.Numerics.Complex c = eigenvaluesComplex[i];
                double magnitude          = c.Magnitude;
                Console.WriteLine("eigen value[{0}]     {1}     Magnitude={2}", i, c.ToString(), magnitude);
            }

            Matrix <double> eigenvectorsComplex = eigen.EigenVectors;

            double[,] eigenvectorsReal = new double[eigenvaluesComplex.Count, matrix.GetLength(0)];
            for (int col = 0; col < eigenvectorsComplex.RowCount; col++)
            {
                Vector <double> ev = eigenvectorsComplex.Column(col);
                for (int i = 0; i < ev.Count; i++)
                {
                    eigenvectorsReal[col, i] = ev[i];
                    Console.WriteLine("eigen vector {0}, value {1} = {2}", col, i, ev[i]);
                }
            }

            return(Tuple.Create(eigenvaluesReal, eigenvectorsReal));
        }
예제 #2
0
        public PrincipalComponents(Matrix <double> data)
        {
            var dt = data.Clone();

            dt.Transpose();
            sampleCov = dt * data * (1.0 / data.RowCount);
            //covDecomposition = new EigenvalueDecomposition(sampleCov);
            covDecomposition = sampleCov.Evd();
            covDecomposition.Solve(sampleCov);

            var evs     = new double[sampleCov.RowCount];
            var indices = new int[sampleCov.RowCount];

            for (var i = 0; i < sampleCov.RowCount; ++i)
            {
                evs[i]     = covDecomposition.EigenValues[i].Real;
                indices[i] = i;
            }

            Array.Sort(evs, indices);

            var permutation = Matrix <double> .Build.Dense(sampleCov.RowCount, sampleCov.RowCount);

            for (var i = 0; i < sampleCov.RowCount; ++i)
            {
                permutation[indices[i], i] = 1.0;
            }

            var v = covDecomposition.EigenVectors;

            SortedComponents  = v * permutation;
            SortedEigenvalues = Vector <double> .Build.DenseOfArray(evs);
        }
예제 #3
0
        public void ConstructorThrowsForNotDiagonalizableMatrix()
        {
            var notDiagonalizable = Matrix <double> .Build
                                    .DenseOfArray(
                new[, ]
            {
                {
                    0d,
                    -1d,
                },
                {
                    1d,
                    0d,
                },
            });

            this._covariancesDecomposition = notDiagonalizable.Evd();
            Assert.Throws <IndexOutOfRangeException>(
                () => new CmaEsElements(
                    this._configuration,
                    this._generation,
                    this._distributionMean,
                    this._stepSize,
                    covariances: notDiagonalizable,
                    covariancesDecomposition: this._covariancesDecomposition,
                    evolutionPath: this._evolutionPath,
                    conjugateEvolutionPath: this._conjugateEvolutionPath));
        }
예제 #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CmaEsElementsTest"/> class.
        /// </summary>
        public CmaEsElementsTest()
        {
            this._configuration    = new CmaEsConfiguration(20, Vector <double> .Build.Random(3), 0.1);
            this._distributionMean = Vector <double> .Build.DenseOfArray(new[] { 1.8, 4.9 });

            this._evolutionPath = Vector <double> .Build.DenseOfArray(new[] { 2.1, 3.2 });

            this._conjugateEvolutionPath = Vector <double> .Build.DenseOfArray(new[] { 1.7, 4.1 });

            this._covariances = Matrix <double> .Build
                                .DenseOfArray(
                new[, ]
            {
                {
                    3d,
                    1d,
                },
                {
                    1d,
                    3d,
                },
            });

            this._covariancesDecomposition = this._covariances.Evd(Symmetricity.Symmetric);
            this._diagonal     = this._covariancesDecomposition.D;
            this._eigenvectors = this._covariancesDecomposition.EigenVectors;
        }
예제 #5
0
        /*
         * public PPTCriterion(QuantumState state)
         * {
         *  State = state;
         *  StateOperator = StateOperator.FromQuantumState(state);
         * }
         *
         * public PPTCriterion(StateOperator @operator)
         * {
         *  StateOperator = @operator;
         * }
         */



        public void Evaluate(StateOperator state, SystemBipartition bipartition)
        {
            EvaluatedMatrix = state.PartialTranspose(bipartition);
            Evd <Complex> evd = EvaluatedMatrix.Matrix.Evd();

            Eigenvalues = evd.EigenValues.ToArray();
        }
예제 #6
0
            //returns the first eigenvector of the matrix
            private Matrix <double> getFirstEigenvector(Matrix <double> matrix)
            {
                Evd <double>    eigen   = matrix.Evd();
                Matrix <double> vectors = eigen.EigenVectors;

                return(vectors.SubMatrix(0, vectors.RowCount, vectors.ColumnCount - 1, 1)); //returns only last vector
            }
예제 #7
0
    public Vector3[] EigenVectors()
    {
        Matrix <double> mat = Matrix <double> .Build.Dense(3, 3);

        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                mat[i, j] = this[i, j];
            }
        }

        Evd <double> evd = mat.Evd();

        Matrix <double> eigenvect = evd.EigenVectors;

        Vector3[] eigen_vectors = new Vector3[3];

        for (int vect = 0; vect < 3; vect++)
        {
            for (int comp = 0; comp < 3; comp++)
            {
                eigen_vectors[vect][comp] = (float)eigenvect[comp, vect];
            }
        }

        return(eigen_vectors);
    }
예제 #8
0
    private void CalculateTensilAndCompressive(Matrix <double> stress)
    {
        Evd <double>    evd         = stress.Evd();
        Matrix <double> tensileComp = Matrix <double> .Build.Dense(3, 3);

        Matrix <double> compressiveComp = Matrix <double> .Build.Dense(3, 3);

        for (int i = 0; i < 3; ++i)
        {
            double          eval = evd.EigenValues[i].Real;
            Matrix <double> m    = Utilities.BuildM(evd.EigenVectors.Column(i).Normalize(2));

            tensileComp     += System.Math.Max(0, eval) * m;
            compressiveComp += System.Math.Min(0, eval) * m;
        }

        for (int i = 0; i < 3; ++i)
        {
            Vector <double> ftensil = Vector <double> .Build.Dense(3);

            Vector <double> fcompressive = Vector <double> .Build.Dense(3);

            CalculatePointForce(ftensil, i, tensileComp);

            fcompressive = forcesP[i] - ftensil;

            FracParticle fp = p[i].GetComponent <FracParticle>();
            fp.AddTensilLoad(ftensil);
            fp.AddCompressiveLoad(fcompressive);
        }
    }
예제 #9
0
        public PrincipalComponents(Matrix <double> covMatrix)
        {
            sampleCov = covMatrix;

            // covDecomposition = new EigenvalueDecomposition(sampleCov);
            covDecomposition = sampleCov.Evd();
            covDecomposition.Solve(sampleCov);
            var evs     = new double[sampleCov.RowCount];
            var indices = new int[sampleCov.RowCount];

            for (int i = 0; i < sampleCov.RowCount; ++i)
            {
                evs[i]     = covDecomposition.EigenValues[i].Real;
                indices[i] = i;
            }
            Array.Sort(evs, indices);

            var permutation = Matrix <double> .Build.Dense(sampleCov.RowCount, sampleCov.RowCount);

            for (int i = 0; i < sampleCov.RowCount; ++i)
            {
                permutation[indices[i], i] = 1.0;
            }

            Matrix <double> v = covDecomposition.EigenVectors;

            SortedComponents  = v * permutation;
            SortedEigenvalues = Vector <double> .Build.DenseOfArray(evs);
        }
예제 #10
0
        public static void SetInertia(this Link.Inertial.Inertia inertia, Rigidbody rigidbody)
        {
            Evd <float> Evd = inertia.Unity3DCoordTrafo().ToMatrix().Evd(Symmetricity.Symmetric);

            rigidbody.inertiaTensor         = Evd.EigenValues.GetReal().ToVector3().FixMinInertia(); // optionally check vector for imaginary part = 0
            rigidbody.inertiaTensorRotation = Evd.EigenVectors.ToQuaternion();                       // optionally check matrix for determinant = 1
        }
예제 #11
0
        /// <summary>
        /// Calculates the complex roots of the Polynomial by eigenvalue decomposition
        /// </summary>
        /// <returns>a vector of complex numbers with the roots</returns>
        public Complex[] GetRoots()
        {
            DenseMatrix A = this.GetEigValMatrix();

            Complex[] c_vec;

            if (A == null)
            {
                if (Coeffs.Length < 2)
                {
                    var val = Coeffs.Length == 1 ? Coeffs[0] : Double.NaN;
                    c_vec = new Complex[1] {
                        val
                    };
                }
                else
                {
                    c_vec = new Complex[1] {
                        new Complex(-Coeffs[0] / Coeffs[1], 0)
                    }
                };
            }
            else
            {
                Evd <double> eigen = A.Evd(Symmetricity.Asymmetric);
                c_vec = eigen.EigenValues.ToArray();
            }
            return(c_vec);
        }
예제 #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CmaEsElements"/> class.
        /// </summary>
        /// <param name="configuration">Fixed parameters for CMA-ES.</param>
        /// <param name="generation">The current generation.</param>
        /// <param name="distributionMean">The current distribution mean.</param>
        /// <param name="stepSize">The current step size.</param>
        /// <param name="covariances">The current covariance matrix.</param>
        /// <param name="covariancesDecomposition">The current eigendecomposition of the covariance matrix.</param>
        /// <param name="evolutionPath">The current evolution path.</param>
        /// <param name="conjugateEvolutionPath">The conjugate evolution path.</param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Thrown if <paramref name="generation"/> or <paramref name="stepSize"/> are negative.
        /// </exception>
        public CmaEsElements(
            CmaEsConfiguration configuration,
            int generation,
            Vector <double> distributionMean,
            double stepSize,
            Matrix <double> covariances,
            Evd <double> covariancesDecomposition,
            Vector <double> evolutionPath,
            Vector <double> conjugateEvolutionPath)
        {
            if (generation < 0)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(generation),
                          $"Generation must be nonnegative, but was {generation}.");
            }

            if (stepSize < 0)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(stepSize),
                          $"Step size must be nonnegatives, but was {stepSize}.");
            }

            this.Configuration            = configuration;
            this.Generation               = generation;
            this._distributionMean        = distributionMean?.Clone();
            this.StepSize                 = stepSize;
            this._covariances             = covariances?.Clone();
            this._covariancesDiagonal     = covariancesDecomposition == null ? null : DiagonalMatrix.OfMatrix(covariancesDecomposition.D);
            this._covariancesEigenVectors = covariancesDecomposition?.EigenVectors.Clone();
            this._evolutionPath           = evolutionPath?.Clone();
            this._conjugateEvolutionPath  = conjugateEvolutionPath?.Clone();
        }
예제 #13
0
    public bool isFracturing(double toughness, List <Vector <double> > fracPlaneNormals)
    {
        fracPlaneNormals.Clear();

        CalculatePointSeparationTensor();
        Evd <double> evd = separationTensor.Evd();

        double vp = evd.EigenValues.AbsoluteMaximum().Real;
        bool   fracturesAtNode = vp > toughness; // does at least one eigenvalue exceeds toughness

        //Debug.Log("vp = " + vp + "\n");


        // Note : More efficient to simply loop on all since there's just 3 eigenvalue. Sorting is not that useful here.
        for (int i = 0; fracturesAtNode && i < evd.EigenValues.Count; ++i)
        {
            if (evd.EigenValues[i].Real > toughness)
            {
                Vector <double> fracPlaneNormal = evd.EigenVectors.Column(i);
                fracPlaneNormals.Add(fracPlaneNormal);
            }
        }

        return(fracturesAtNode);
    }
예제 #14
0
파일: Form1.cs 프로젝트: Astro1247/FL_1
        private void GetEigenNumbersButton_Click(object sender, EventArgs e)
        {
            Matrix matr1 = Matrix.Parse(baseMatrixBox.Text);

            if (!matr1.IsSquare())
            {
                MessageBox.Show("Матрица должна быть квадратной!");
                return;
            }
            double[] values  = new double[matr1.Rows * matr1.Columns];
            int      counter = 0;

            for (int i = 0; i < matr1.Rows; i++)
            {
                for (int j = 0; j < matr1.Columns; j++)
                {
                    values[counter++] = matr1.Values[i, j];
                }
            }
            Evd <double> evd = MathNet.Numerics.LinearAlgebra.Matrix <double> .Build.Dense(matr1.Rows, matr1.Columns, values).Evd();

            eigenNumbersBox.Text = "";
            double[] eigenNumbers = new double[matr1.Rows];
            counter = 0;
            foreach (var eigenvalue in evd.EigenValues.AsEnumerable())
            {
                //if (eigenvalue.Magnitude.CoerceZero() < 0.001) eigenNumbers[counter++] = 0;
                //else eigenNumbers[counter++] = eigenvalue.Real;
                eigenNumbersBox.Text += eigenvalue.Magnitude.CoerceZero(0.00001) + "\r\n";
            }
        }
예제 #15
0
파일: Laws.cs 프로젝트: Hindi/C3P0GitHub
    /*************************************************************************************************
    * Private used functions                                                                        *
    *************************************************************************************************/
    /* Square root of a matrix using eigenvectors and eigenvalues (assuming it can be applied, undefined if not) */
    /// <summary>
    /// Square root of a matrix using eigenvectors and eigenvalues (assuming it can be applied, undefined if not)
    /// </summary>
    /// <param name="M">A Matrix</param>
    /// <returns>The square root of M if applicable</returns>
    private static Matrix sqrtm(Matrix M)
    {
        MathNet.Numerics.LinearAlgebra.Matrix <double> sqrtM;
        // Calculating M^(1/2);
        Evd <double> eigenVs = M.Evd();

        DenseVector values = new DenseVector(M.RowCount);

        double[] tempValues = new double[M.RowCount];
        int      i          = 0;

        foreach (MathNet.Numerics.Complex c in eigenVs.EigenValues.ToArray())
        {
            tempValues[i] = c.Real;
            i++;
        }
        values.SetValues(tempValues);
        values.MapInplace(System.Math.Sqrt);

        DiagonalMatrix newValues = new DiagonalMatrix(M.RowCount, M.RowCount, values.ToArray());

        sqrtM = (eigenVs.EigenVectors * newValues) * eigenVs.EigenVectors.Inverse();

        return((Matrix)sqrtM);
    }
예제 #16
0
        public List <double> ComputeEVD(Matrix <double> laplacian)
        {
            Evd <double> evd = laplacian.Evd();

            var column = new List <double>(evd.EigenVectors.Column(1).Storage.ToArray());

            return(column);
        }
예제 #17
0
        static Matrix <double> GetEigen(List <List <double> > covariance, int N)
        {
            Matrix <double> matrix = ConvToMatrix(covariance);
            Evd <double>    eigen  = matrix.Evd();
            //Vector<Complex> eigenValues = eigen.EigenValues;
            //Console.WriteLine(eigenValues.ToString());
            Matrix <double> eigenVectors = eigen.EigenVectors;

            return(eigenVectors.SubMatrix(0, eigenVectors.RowCount, 0, N));
        }
        public static double Eigenvalue(double[,] array)
        {
            Matrix <double> A = DenseMatrix.OfArray(array);

            Evd <double>     eigen       = A.Evd();
            Matrix <double>  eigenvect   = eigen.EigenVectors;
            Vector <Complex> eigenvalues = eigen.EigenValues;

            return(eigenvalues.AbsoluteMaximum().Real);
        }
예제 #19
0
        /// <summary>
        /// Compute the plane that best fit a set of input points (least squared orthogonal distance)
        /// </summary>
        /// <param name="points">The input points</param>
        /// <param name="planeOrigin">The output plane origin</param>
        /// <param name="planeNormal">The output plane normal vector</param>
        /// <returns>0 if the input points are identical, 1 if the input points are colinear, 2 if the input points are coplanar (already on a plane), 3 otherwise</returns>
        public static int ComputeBestFitPlane(List <Triple> points, out Triple planeOrigin, out Triple planeNormal)
        {
            Triple centroid = Triple.Zero;

            for (int i = 0; i < points.Count; i++)
            {
                centroid += points[i];
            }
            centroid /= points.Count;

            float[,] P = new float[points.Count, 3];

            for (int i = 0; i < points.Count; i++)
            {
                P[i, 0] = points[i].X - centroid.X;
                P[i, 1] = points[i].Y - centroid.Y;
                P[i, 2] = points[i].Z - centroid.Z;
            }

            Matrix <float> covariance = Matrix <float> .Build.Dense(3, 3);

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    for (int k = 0; k < points.Count; k++)
                    {
                        covariance[i, j] += P[k, i] * P[k, j];
                    }
                }
            }

            Evd <float> evd = covariance.Evd();

            planeOrigin = centroid;

            if (evd.Rank == 0) // The input points are idendtical, so we just pick an arbitrary normal vector
            {
                planeNormal = Triple.BasisZ;
            }
            else if (evd.Rank == 1
                     ) // The input points are colinear, so we just pick an arbitrary vector perpendicular to the only eigen vector
            {
                planeNormal = new Triple(evd.EigenVectors[0, 1], evd.EigenVectors[1, 1], evd.EigenVectors[2, 1])
                              .GeneratePerpendicular();
            }
            else // The normal is perpendicular to the two dominant eigen vectors
            {
                Triple e1 = new Triple(evd.EigenVectors[0, 1], evd.EigenVectors[1, 1], evd.EigenVectors[2, 1]);
                Triple e2 = new Triple(evd.EigenVectors[0, 2], evd.EigenVectors[1, 2], evd.EigenVectors[2, 2]);
                planeNormal = e2.Cross(e1).Normalise();
            }

            return(evd.Rank);
        }
예제 #20
0
파일: icpv2.cs 프로젝트: 0000duck/ICPv2
    // Compute the optimal rotation and translation vectors
    // Accepts the Matrix4X4 registration matrix, center of mass of source and target point sets
    //outputs the rotationMatrix and the translation vector
    public static void GetTransformationVectors
        (float[,] registrationMatrix, Vector3 SourceCenterOfMass, Vector3 TargeCenterOfMass, out Vector3 TranslationVector, out Quaternion UnityQuat)
    {
        //initialise matrix builder
        MatrixBuilder <float> regMatrix = Matrix <float> .Build;

        //fill matrix builder with contents of our params registrationmatri to create a Matrix
        Matrix <float> reg = regMatrix.DenseOfArray(registrationMatrix);

        //EVD decompose to generate our eignevalues
        Evd <float> registrationevd = reg.Evd();

        //Cholesky<float> registrationevd = reg.Cholesky();
        Console.WriteLine("Symmetric" + registrationevd.IsSymmetric);

        //get inex of maximum eigenvalue for correspond eigenvector
        double maxValue = double.NegativeInfinity;

        //int maxEigenValue = registrationevd.EigenValues.
        int index = 0;

        for (int i = 0; i < registrationevd.EigenValues.Count; i++)
        {
            if (registrationevd.EigenValues[i].Real > maxValue)
            {
                maxValue = registrationevd.EigenValues[i].Real;
                index    = i;
            }
        }

        //Get the eigenvalue index and copy the vector as our unit eigenvector.
        //Our unit EigenVector below
        MathNet.Numerics.LinearAlgebra.Vector <float> unitEigenVector = registrationevd.EigenVectors.Column(index);

        float q0 = unitEigenVector.At(0);
        float q1 = unitEigenVector.At(1);
        float q2 = unitEigenVector.At(2);
        float q3 = unitEigenVector.At(3);

        UnityQuat = new Quaternion(q1, q2, q3, q0);

        Matrix4x4 rotMatrix = Matrix4x4.CreateFromQuaternion(UnityQuat);



        Vector3 y = new Vector3(0, 0, 0);

        //get optimal translation vector
        // Vector3 y = Matrix4x4.Rotate(UnityQuat).MultiplyPoint(SourceCenterOfMass);


        Vector3 optimalTranslation = TargeCenterOfMass - y;

        TranslationVector = optimalTranslation;
    }
예제 #21
0
            public static bool Calculate(Graph g)
            {
                if (g.order == 0)
                {
                    return(true);
                }
                Matrix <double>  lMatrix     = DenseMatrix.OfArray(Utils.Spectral.SignlessLaplacianMatrix(g));
                Evd <double>     evd         = lMatrix.Evd(Symmetricity.Symmetric);
                Vector <Complex> eigenvalues = evd.EigenValues;
                double           x           = eigenvalues.ElementAt(g.order - 1).Real;

                return(Utils.Spectral.ApproxToInt(x) % 1 == 0);
            }
        public double Calculate(Graph g)
        {
            if (g.order == 0)
            {
                return(0);
            }
            Matrix <double>  lMatrix     = DenseMatrix.OfArray(Utils.Spectral.LaplacianMatrix(g));
            Evd <double>     evd         = lMatrix.Evd(Symmetricity.Symmetric);
            Vector <Complex> eigenvalues = evd.EigenValues;
            double           a           = eigenvalues.ElementAt(1).Real;

            return(Utils.Spectral.ApproxToInt(a));
        }
        public double Calculate(Graph g)
        {
            if (g.order <= 1)
            {
                return(0);
            }
            Matrix <double>  lMatrix     = DenseMatrix.OfArray(Utils.Spectral.AdjacencyMatrix(g));
            Evd <double>     evd         = lMatrix.Evd(Symmetricity.Symmetric);
            Vector <Complex> eigenvalues = evd.EigenValues;
            double           x           = eigenvalues.ElementAt(g.order - 2).Real;

            return(Utils.Spectral.ApproxToInt(x));
        }
예제 #24
0
파일: WITools.cs 프로젝트: Lyngse/P7
        public double[][] GetEigenVectors(List <User> uList)
        {
            Matrix <double> diagonalMatrix;

            Matrix <double> associationMatrix = FillMatrix(uList, out diagonalMatrix);

            Matrix <double> laplacianMatrix = diagonalMatrix - associationMatrix;

            Evd <double> eigen        = laplacianMatrix.Evd(Symmetricity.Symmetric);
            var          eigenVectors = eigen.EigenVectors.ToRowArrays();

            return(eigenVectors);
        }
        public ModalSynthesizer(Mesh mesh, SM_Material properties, int sampleRate = 44100)
        {
            this.sampleRate = sampleRate;
            SpringMesh fem = new SpringMesh(mesh, properties);

            mMass      = fem.GetMassMatrix();
            mStiffness = fem.GetGlobalStiffnessMatrix();

            if (mStiffness.RowCount > USE_EXT_TOL)
            {
                /*
                 * ext = ExternalLinalgHandler.Instance;
                 * ParentBehaviour?.StartCoroutine(ext.UnityDebugProcessOutput());
                 * ext.ComputeExternal(mStiffness);
                 * mGain = ext.EigenVectors;
                 * mGain_inv = ext.EigenVectors_Inv;
                 * mEig = ext.EigenValues;
                 */

                /*
                 * using (ExternalLinalgHandler ext = new ExternalLinalgHandler())
                 * {
                 *  ParentBehaviour?.StartCoroutine(ext.UnityDebugProcessOutput());
                 *  ext.ComputeExternal(K);
                 *  mGain = ext.EigenVectors;
                 *  mGain_inv = ext.EigenVectors_Inv;
                 *  mEig = ext.EigenValues;
                 * }
                 */
                //ext.Dispose();
            }
            else
            {
                Evd <double> evd = mStiffness.Evd(Symmetricity.Hermitian);
                mGain     = evd.EigenVectors;
                mGain_inv = mGain.Inverse();
                mEig      = evd.EigenValues;
            }

            props       = properties;
            nmodes      = mEig.Count;
            omega_plus  = new zdouble[nmodes];
            omega_minus = new zdouble[nmodes];
            SetModeProperties();

            cGains = new zdouble[nmodes];
            for (int i = 0; i < nmodes; i++)
            {
                cGains[i] = new zdouble(0.0, 0.0);
            }
        }
예제 #26
0
    public void Rescale()
    {
        Center();
        Matrix <double> A     = PositionMatrix();
        Matrix <double> cov   = 1.0f / ((float)A.RowCount) * A.Transpose() * A;
        Evd <double>    eigen = cov.Evd();

        MathNet.Numerics.LinearAlgebra.Vector <System.Numerics.Complex> eigenvals = eigen.EigenValues;
        double l1 = eigenvals[0].Real; //1 / Math.Sqrt(eigenvals[0].Real);
        double l2 = eigenvals[1].Real; //1 / Math.Sqrt(eigenvals[1].Real);
        double l3 = eigenvals[2].Real; // / Math.Sqrt(eigenvals[2].Real);

        Debug.Log("l1: " + l1 + ", l2: " + l2 + ", l3: " + l3);
        double vol = l1 * l2 * l3;
        double max = eigenvals.AbsoluteMaximum().Real;

        Debug.Log("max=" + max);
        //double det = cov.Determinant();

        A = A / Math.Sqrt(max) * 0.2;
        Debug.Log(A);

        //Debug.Log("determinant:");
        for (int i = 0; i < A.RowCount; i++)
        {
            poses_[i].Translation = new Vector3((float)A[i, 0], (float)A[i, 1], (float)A[i, 2]);
        }



        /* Matrix<double> A = PositionMatrix();
         * Matrix<double> cov = 1.0f / ((float)A.RowCount ) *A.Transpose() * A;
         *
         *
         * Debug.Log(cov.ToString());
         * Evd<double> eigen = cov.Evd();
         * Matrix<double> m = eigen.EigenVectors;
         * Matrix<double> points = m * A * m.Inverse();
         *
         * points = points * cov.Determinant() / 10;
         * points = m * points * m.Inverse();
         * for (int i = 0; i < points.RowCount; i++)
         * {
         *   poses_[i].Translation =new Vector3((float)points[i, 0], (float)points[i, 1], (float)points[i, 2]);
         * }*/
        /*double det = cov.Determinant();
         * cov_rotated = cov_rotated / det;
         * Matrix<double> cov_recovered = m * cov_rotated * m.Inverse();*/
        //Debug.Log(cov_recovered.ToString());
    }
        // Return the eigenvector associated with the smallest eigenvalue
        // and convert it into a Quaternion
        static Quaternion SmallestEigenVector(Matrix4x4 m)
        {
            Matrix <double> mCopy = Matrix <double> .Build.Dense(4, 4);

            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    mCopy[i, j] = m[i, j];
                }
            }

            Evd <double> evd = mCopy.Evd();

            System.Numerics.Complex min = evd.EigenValues[0];
            int indiceMin = 0;

            for (int i = 1; i < 4; i++)
            {
                if (evd.EigenValues[i].Imaginary == 0)
                {
                    if ((evd.EigenValues[i].Real > 0 && evd.EigenValues[i].Real < min.Real))
                    {
                        min       = evd.EigenValues[i];
                        indiceMin = i;
                    }
                }
            }

            Quaternion result = new Quaternion();

            result.w = (float)evd.EigenVectors[0, indiceMin];

            // There could be a problem with quaternion sign, so... :
            if (result.w < 0)
            {
                result.w = -(float)evd.EigenVectors[0, indiceMin];
                result.x = -(float)evd.EigenVectors[1, indiceMin];
                result.y = -(float)evd.EigenVectors[2, indiceMin];
                result.z = -(float)evd.EigenVectors[3, indiceMin];
            }
            else
            {
                result.x = (float)evd.EigenVectors[1, indiceMin];
                result.y = (float)evd.EigenVectors[2, indiceMin];
                result.z = (float)evd.EigenVectors[3, indiceMin];
            }

            return(result);
        }
예제 #28
0
    /*************************************************************************************************
    * Private used functions                                                                        *
    *************************************************************************************************/
    /* Square root of a matrix using eigenvectors and eigenvalues (assuming it can be applied, undefined if not) */
    /// <summary>
    /// Square root of a matrix using eigenvectors and eigenvalues (assuming it can be applied, undefined if not)
    /// </summary>
    /// <param name="M">A Matrix</param>
    /// <returns>The square root of M if applicable</returns>
    private Matrix sqrtm(Matrix M)
    {
        MathNet.Numerics.LinearAlgebra.Matrix <double> sqrtM;
        // Calculating M^(1/2);
        Evd <double> eigenVs = M.Evd();

        DenseVector values = new DenseVector(M.RowCount);

        double[] tempValues = new double[M.RowCount];
        int      i          = 0;

        foreach (MathNet.Numerics.Complex c in eigenVs.EigenValues.ToArray())
        {
            tempValues[i] = c.Real;
            i++;
        }
        values.SetValues(tempValues);
        values.MapInplace(System.Math.Sqrt);

        DiagonalMatrix newValues = new DiagonalMatrix(M.RowCount, M.RowCount, values.ToArray());

        sqrtM = (eigenVs.EigenVectors * newValues) * eigenVs.EigenVectors.Inverse();

        /* This is debug to see what's actually inside M & M^1/2 */

        /*
         * Debug.Log("Old matrix");
         * for (int j = 0; j < M.RowCount; j++)
         * {
         *  string message = "";
         *  for (int k = 0; k < M.ColumnCount; k++)
         *  {
         *      message += M.Row(j).At(k).ToString(null, null) + "   ";
         *  }
         *  Debug.Log(message);
         * }
         * Debug.Log("New matrix");
         * for (int j = 0; j < sqrtM.RowCount; j++)
         * {
         *  string message = "";
         *  for (int k = 0; k < sqrtM.ColumnCount; k++)
         *  {
         *      message += sqrtM.Row(j).At(k).ToString(null, null) + "   ";
         *  }
         *  Debug.Log(message);
         * }
         */

        return((Matrix)sqrtM);
    }
예제 #29
0
        private static void AnBacahaytMEthod(int count, Matrix <double> arrayForA, Vector <double> arrayForB, Vector <double> oldVectorForX, Matrix <double> eye3, Matrix <double> c, double tao)
        {
            Console.WriteLine("\n\n*******************   An-Bacahayt-Method  *******************");
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            count = 0;
            ////anbacahayt
            Matrix <double> arrayForM = (2 * c) - tao * arrayForA;

            Console.WriteLine(arrayForM);
            Evd <double>     eigenM       = arrayForM.Evd();
            Vector <Complex> eigenVectroM = eigenM.EigenValues;

            if (eigenVectroM.All(item => item.Real > 0))
            {
                Console.WriteLine(eigenVectroM);
                Vector <double> newVectorForX;
                while (true)
                {
                    count++;
                    newVectorForX = (eye3 - tao * c.Inverse() * arrayForA) * oldVectorForX + (tao * c.Inverse() * arrayForB);


                    if (count == maximalIterationCount || Math.Abs(oldVectorForX.Sum() - newVectorForX.Sum()) < 0.00001)
                    {
                        Console.WriteLine("Iteration number count = {0} ", count);
                        Console.WriteLine(newVectorForX);
                        break;
                    }

                    if (count % 10 == 0)
                    {
                        Console.WriteLine("Iteration number count = {0} ", count);
                        Console.WriteLine(newVectorForX);
                    }
                    oldVectorForX = newVectorForX;
                }
            }
            else
            {
                Console.WriteLine("M matrxi EIG  is a NEGATIVE");
            }

            stopWatch.Start();
            TimeSpan ts          = stopWatch.Elapsed;
            string   elaspedTIme = String.Format("{0:00}.{1:00}", ts.Seconds, ts.Milliseconds / 10);

            Console.WriteLine("AnBacahayt Method RunTime: {0}", elaspedTIme);
        }
예제 #30
0
        private void InitContinuousModel(
            Matrix <double> A, Matrix <double> B, Matrix <double> C, Matrix <double> D
            )
        {
            this.A = A;
            this.B = B;
            this.C = C;
            this.D = D;

            Order = this.A.ColumnCount;
            Evd <double> decomposition = this.A.Evd();

            EigenValues  = decomposition.EigenValues;
            EigenVectors = decomposition.EigenVectors;
            I            = Matrix <double> .Build.DenseIdentity(order : Order);
        }