Пример #1
0
        public static Tuple <double, double> LeastSquareLinearRegression(double[] xdata, double[] ydata)
        {
            // build matrices
            var X = DenseMatrix.OfColumnVectors(
                new[] { DenseVector.Create(xdata.Length, 1), new DenseVector(xdata) });
            var y = new DenseVector(ydata);

            // solve using QR
            var p = X.QR().Solve(y);

            return(new Tuple <double, double>(p[0], p[1]));
        }
        public void DetermineStatusWithNonMatchingSourceVectorThrowsArgumentException()
        {
            var criterium = new ResidualStopCriterium(1e-8, 50);

            Assert.IsNotNull(criterium, "There should be a criterium");

            Assert.Throws <ArgumentException>(() => criterium.DetermineStatus(
                                                  1,
                                                  DenseVector.Create(3, i => 4),
                                                  DenseVector.Create(4, i => 4),
                                                  DenseVector.Create(3, i => 4)));
        }
Пример #3
0
        public IVector Rotate(int blockCount)
        {
            var vectorList = new List <IIndexableVector>();
            var blockSize  = Count / blockCount;

            foreach (var item in Split(blockCount).Reverse())
            {
                vectorList.Add(item.Reverse().AsIndexable());
            }

            return(new CpuVector(DenseVector.Create(Count, i => vectorList[i / vectorList.Count][i % blockSize])));
        }
        public void DetermineStatusWithIllegalIterationNumberThrowsArgumentOutOfRangeException()
        {
            var criterium = new ResidualStopCriterium(1e-8, 50);

            Assert.IsNotNull(criterium, "There should be a criterium");

            Assert.Throws <ArgumentOutOfRangeException>(() => criterium.DetermineStatus(
                                                            -1,
                                                            DenseVector.Create(3, i => 4),
                                                            DenseVector.Create(3, i => 5),
                                                            DenseVector.Create(3, i => 6)));
        }
        public void DetermineStatus()
        {
            var criterium = new IterationCountStopCriterium <Complex>(10);

            Assert.IsNotNull(criterium, "A criterium should have been created");

            criterium.DetermineStatus(5, DenseVector.Create(3, i => 1), DenseVector.Create(3, i => 2), DenseVector.Create(3, i => 3));
            Assert.IsInstanceOf(typeof(CalculationRunning), criterium.Status, "Should be running");

            criterium.DetermineStatus(10, DenseVector.Create(3, i => 1), DenseVector.Create(3, i => 2), DenseVector.Create(3, i => 3));
            Assert.IsInstanceOf(typeof(CalculationStoppedWithoutConvergence), criterium.Status, "Should be finished");
        }
Пример #6
0
        public IVector ConvertToVector()
        {
            var vectorList = _data.Select(m => m.ConvertInPlaceToVector().AsIndexable()).ToArray();
            var size       = _rows * _columns;
            var ret        = DenseVector.Create(Depth * size, i => {
                var offset = i / size;
                var index  = i % size;
                return(vectorList[offset][index]);
            });

            return(new CpuVector(ret));
        }
        public void ResetCalculationState()
        {
            var criterium = new IterationCountStopCriterium <Complex>(10);

            Assert.IsNotNull(criterium, "A criterium should have been created");

            criterium.DetermineStatus(5, DenseVector.Create(3, i => 1), DenseVector.Create(3, i => 2), DenseVector.Create(3, i => 3));
            Assert.IsInstanceOf(typeof(CalculationRunning), criterium.Status, "Should be running");

            criterium.ResetToPrecalculationState();
            Assert.IsInstanceOf(typeof(CalculationIndetermined), criterium.Status, "Should not have started");
        }
Пример #8
0
        public void DetermineStatusWithNullSolutionVectorThrowsArgumentNullException()
        {
            var criterium = new ResidualStopCriterium(1e-8, 50);

            Assert.IsNotNull(criterium, "There should be a criterium");

            Assert.Throws <ArgumentNullException>(() => criterium.DetermineStatus(
                                                      1,
                                                      null,
                                                      DenseVector.Create(3, i => 5),
                                                      DenseVector.Create(3, i => 6)));
        }
    /// <param name="srcPoints">need 4 or more points before translate </param>
    /// <param name="dstPoints">need 4 or more points after translate</param>
    /// <exception cref="ArgumentException">srcPoints and dstPoints must require 4 or more points</exception>
    /// <exception cref="ArgumentException">srcPoints and dstPoints must same num</exception>
    /// <returns>Homography Matrix</returns>
    public static SingleHomographyMatrix Find(IReadOnlyList <Point2 <float> > srcPoints, IReadOnlyList <Point2 <float> > dstPoints)
    {
        if (srcPoints.Count < 4 || dstPoints.Count < 4)
        {
            throw new ArgumentException("srcPoints and dstPoints must require 4 or more points");
        }
        if (srcPoints.Count != dstPoints.Count)
        {
            throw new ArgumentException("srcPoints and dstPoints must same num");
        }

        // q(dst vector) = A(nx8 coefficient matrix) * p(homography matrix parameter)
        // p = A^-1 * q
        int pointNum          = srcPoints.Count;
        var coefficientMatrix = DenseMatrix.Create(pointNum * 2, 8, 0);

        for (int i = 0; i < pointNum; i++)
        {
            var src = srcPoints[i];
            var dst = dstPoints[i];

            SetCoefficientMatrixParametersForDstX(coefficientMatrix, src.X, src.Y, dst.X, 2 * i);
            SetCoefficientMatrixParametersForDstY(coefficientMatrix, src.X, src.Y, dst.Y, 2 * i + 1);
        }

        var dstVec = DenseVector.Create(pointNum * 2, 0);

        for (int i = 0; i < pointNum; i++)
        {
            dstVec[i * 2]     = dstPoints[i].X;
            dstVec[i * 2 + 1] = dstPoints[i].Y;
        }

        var inverseCoefficientMatrix = pointNum == 4 ? coefficientMatrix.Inverse() : coefficientMatrix.PseudoInverse();

        var parameterVec = inverseCoefficientMatrix * dstVec;

        var elements = new float[9];

        elements[0] = parameterVec[0];
        elements[1] = parameterVec[1];
        elements[2] = parameterVec[2];

        elements[3] = parameterVec[3];
        elements[4] = parameterVec[4];
        elements[5] = parameterVec[5];

        elements[6] = parameterVec[6];
        elements[7] = parameterVec[7];
        elements[8] = 1;

        return(new SingleHomographyMatrix(elements));
    }
Пример #10
0
        /// <summary>
        /// Procustes statistics which gives a (di)similiarity measure of two set of points, by removing translation, rotation and dilation(stretching) degrees of freedom.
        /// Zero as result means the two sets of points are basically the same after translation, rotation and dilation with the corresponding matrices.
        /// Reference: Modern Multidimensional Scaling, Theory and Applications, page 436, Procrustes Analysis
        /// </summary>
        /// <param name="A"></param>
        /// <param name="B"></param>
        /// <returns></returns>
        public static Tuple <String, double> ProcrustesStatistics(List <Point> A, List <Point> B)
        {
            int n = A.Count;
            //make A to be unitlength
            double minX = A.Min(p => p.X);
            double maxX = A.Max(p => p.X);
            double minY = A.Min(p => p.Y);
            double maxY = A.Max(p => p.Y);

            double deltaX = maxX - minX;
            double deltaY = maxY - minY;
            double scale  = Math.Max(deltaX, deltaY);


            A = A.Select(p => new Point(p.X / scale, p.Y / scale)).ToList();


            var centerA = new Point(A.Average(a => a.X), A.Average(a => a.Y));
            var centerB = new Point(B.Average(b => b.X), B.Average(b => b.Y));

            Matrix X = DenseMatrix.Create(n, 2, (i, j) => j == 0 ? A[i].X:A[i].Y);
            Matrix Y = DenseMatrix.Create(n, 2, (i, j) => j == 0 ? B[i].X:B[i].Y);

            Matrix Xc = DenseMatrix.Create(n, 2, (i, j) => j == 0 ? A[i].X - centerA.X : A[i].Y - centerA.Y);
            Matrix Yc = DenseMatrix.Create(n, 2, (i, j) => j == 0 ? B[i].X - centerB.X : B[i].Y - centerB.Y);

            //Reference: Modern Multidimensional Scaling, Theory and Applications, page 436, Procrustes Analysis
            DenseMatrix C = (DenseMatrix)(Xc.Transpose() * Y);

            Svd svd = new DenseSvd(C, true);
            //rotation
            Matrix <double> T = (svd.VT().Transpose()) * (svd.U().Transpose());
            //dilation
            double s = ((C * T).Trace()) / ((Yc.Transpose() * Y).Trace());
            //column Vector with n times 1
            Vector <double> vector1 = DenseVector.Create(n, i => 1);
            //translation vector
            Vector <double> t = (1.0 / n) * (X - s * Y * T).Transpose() * vector1;

            Matrix translationMatrix = DenseMatrix.Create(n, 2, (i, j) => t.At(j));

            Matrix <double> YPrime = s * Y * T + translationMatrix;
            Matrix <double> delta  = X - YPrime;

            double rSquare = 0;

            for (int i = 0; i < n; i++)
            {
                rSquare += delta.Row(i) * delta.Row(i);
            }
            return(Tuple.Create("ProcrustesStatistics", Math.Sqrt(rSquare)));
        }
Пример #11
0
        /// <summary>
        /// Computes mean of every column.
        /// </summary>
        /// <param name="matrix">Matrix to compute means of columns.</param>
        /// <returns>Vector where every element is a mean of corresponding column in the source matrix.</returns>
        public static Vector MeanOfEveryColumn(this Matrix <double> matrix)
        {
            Vector result = DenseVector.Create(matrix.ColumnCount, i => 0.0);

            foreach (var row in matrix.RowEnumerator())
            {
                result.Add(row.Item2, result);
            }

            result.Divide(matrix.RowCount, result);

            return(result);
        }
        public void ResetCalculationState()
        {
            var criterium = new IterationCountStopCriterium <double>(10);

            Assert.IsNotNull(criterium, "A criterium should have been created");

            var status = criterium.DetermineStatus(5, DenseVector.Create(3, i => 1), DenseVector.Create(3, i => 2), DenseVector.Create(3, i => 3));

            Assert.AreEqual(IterationStatus.Running, status, "Should be running");

            criterium.ResetToPrecalculationState();
            Assert.AreEqual(IterationStatus.Indetermined, criterium.Status, "Should not have started");
        }
Пример #13
0
        private double CreateC(Matrix <double> leftMatrix)
        {
            var c = DenseVector.Create(leftMatrix.RowCount, 0);

            for (var rowIndex = 0; rowIndex < leftMatrix.RowCount; rowIndex++)
            {
                var row = leftMatrix.Row(rowIndex).Map(Math.Abs);
                var sumWithoutDiagonal = row.Where((it, index) => index != rowIndex).Sum();
                c[rowIndex] = sumWithoutDiagonal / row[rowIndex];
            }

            return(c.Max());
        }
Пример #14
0
        private static Vector <double> DistributionToVector(IDictionary <TracerFormula, double> distribution, IDictionary <TracerFormula, int> indexes)
        {
            var result = DenseVector.Create(indexes.Count, double.NaN);

            foreach (var entry in distribution)
            {
                int index;
                if (indexes.TryGetValue(entry.Key, out index))
                {
                    result[indexes[entry.Key]] = entry.Value;
                }
            }
            return(result);
        }
        public void DetermineStatus()
        {
            var criterium = new IterationCountStopCriterium <double>(10);

            Assert.IsNotNull(criterium, "A criterium should have been created");

            var status = criterium.DetermineStatus(5, DenseVector.Create(3, i => 1), DenseVector.Create(3, i => 2), DenseVector.Create(3, i => 3));

            Assert.AreEqual(IterationStatus.Running, status, "Should be running");

            var status2 = criterium.DetermineStatus(10, DenseVector.Create(3, i => 1), DenseVector.Create(3, i => 2), DenseVector.Create(3, i => 3));

            Assert.AreEqual(IterationStatus.StoppedWithoutConvergence, status2, "Should be finished");
        }
        static public Vector <double> RowAbsoluteSums(Matrix <double> matrix)
        {
            Vector <double> vector = DenseVector.Create(matrix.RowCount, 0);

            for (int line = 0; line < matrix.RowCount; line++)
            {
                double sum_value = 0;
                for (int col = 0; col < matrix.ColumnCount; col++)
                {
                    sum_value += Math.Abs(matrix[line, col]);
                }
                vector[line] = sum_value;
            }
            return(vector);
        }
Пример #17
0
    private void ResetState()
    {
        // Estimate d_-1 using euler time formula. F=ma => a = F/m
        var test = ComputeGlobalConsistentMassMatrix();

        ApplyConstraints(test);
        var startupAcceleration = test.Solve(ComputeForceVector());

        nodeDisplacementOld = startupAcceleration * (Time.fixedDeltaTime * Time.fixedDeltaTime * 0.5f);
        ApplyConstraints(nodeDisplacementOld);

        nodeDisplacement = DenseVector.Create(Nodes.Count * 2, 0.0f);
        nodeSpeed        = DenseVector.Create(Nodes.Count * 2, 0.0f);
        nodeAcceleration = DenseVector.Create(Nodes.Count * 2, 0.0f);
    }
Пример #18
0
    private Vector <float> ComputeGlobalVector(Func <TElementType, IList <Node>, Vector <float> > getElementVectorFunc)
    {
        Vector <float> vector = DenseVector.Create(Nodes.Count * 2, 0.0f);

        foreach (var e in Elements)
        {
            var elementVector = getElementVectorFunc(e, Nodes);
            for (int r = 0; r < NodesPerElement * 2; ++r)
            {
                int globalR = e.LocalComponentIndexToGlobal(r);
                vector[globalR] += elementVector[r];
            }
        }

        return(vector);
    }
Пример #19
0
    private Vector <float> ComputeForceVector()
    {
        Vector <float> forceVector = DenseVector.Create(Nodes.Count * 2, 0.0f);

        foreach (var f in Forces)
        {
            forceVector[f.NodeIndex * 2]     += f.Vector.x;
            forceVector[f.NodeIndex * 2 + 1] += f.Vector.y;
        }

        var scaledGravity = Physics2D.gravity * GravityScale;

        ApplyGravityToForceVector(forceVector, scaledGravity);

        return(forceVector);
    }
Пример #20
0
        public void TestWeightedClassificationToy()
        {
            foreach (var name in CLF_TREES)
            {
                var clf = CreateClassifier <double>(name, random: new Random(0));

                clf.Fit(X, y, sampleWeight: DenseVector.Create(X.GetLength(0), i => 1.0).ToArray());
                AssertExt.ArrayEqual(clf.Predict(T), trueResult,
                                     "Failed with {0}".Frmt(name));


                clf.Fit(X, y, sampleWeight: DenseVector.Create(X.GetLength(0), i => 0.5).ToArray());
                AssertExt.ArrayEqual(clf.Predict(T), trueResult,
                                     "Failed with {0}".Frmt(name));
            }
        }
Пример #21
0
        static void LoadSin(out HashSet <TrainingData> data, int n)
        {
            data = new HashSet <TrainingData>();
            ContinuousUniform rand = new ContinuousUniform(0, Math.PI);

            for (var i = 0; i < n; i++)
            {
                double       x     = rand.Sample();
                TrainingData td    = new TrainingData(1, 1);
                double       scale = Math.PI;
                td.Data[0]  = x / scale;
                td.Response = DenseVector.Create(1, Math.Sin(x));

                data.Add(td);
            }
        }
Пример #22
0
        //Generates the pagerank of the page, returned as a vector, which will be iterated on n times, parsed to the function.
        public DenseVector GeneratePageRank(int n)
        {
            DenseVector resultVector = DenseVector.Create(nrOfPages, 0.0);

            resultVector[0] = 1.0;
            var pageRank = ((1 - randomProbability) * TransitionProbabilityMatrix) + (randomProbability * TransitionRandomMatrix);

            //Console.WriteLine(TransitionProbabilityMatrix.Column(30));
            //Console.WriteLine(TransitionRandomMatrix.Column(30));
            //Console.WriteLine(pageRank.Column(30));

            for (int i = 0; i < n; i++)
            {
                resultVector = (DenseVector)(resultVector * pageRank);
            }
            return(resultVector);
        }
        public Tuple <Matrix <float>, Vector <float> > BuildData(List <TrainingInstance> trainingInstances)
        {
            IState[] states = trainingInstances.Select(x => x.State).ToArray();

            double[] pathCosts = trainingInstances.Select(x => x.Response).ToArray();

            Matrix <float> trainingData = DenseMatrix.Create(states.Length, numInputs, 0);

            for (int r = 0; r < trainingData.RowCount; r++)
            {
                IState state = states[r];

                byte[] stateArr = state.Arr;

                int count = 0;

                for (byte i = 0; i < stateArr.Length; i++)
                {
                    int index = Array.IndexOf(stateArr, i);

                    var coord = SlidingPuzzle.IndexToCoord(index);

                    trainingData[r, count + coord.Item1 - 1] = 1;

                    trainingData[r, count + dim + coord.Item2 - 1] = 1;

                    count += dim + dim;
                }
            }

            Vector <float> response = DenseVector.Create(pathCosts.Length, 0);

            for (int i = 0; i < pathCosts.Length; i++)
            {
                double y = pathCosts[i];

                if (responseFunc != null)
                {
                    y = responseFunc(y);
                }

                response[i] = (float)y;
            }

            return(new Tuple <Matrix <float>, Vector <float> >(trainingData, response));
        }
        private void createClocalForElement(Element el)
        {
            Vector <double> funkcje_ksztaltu = DenseVector.Create(4, 0.0);
            Matrix <double> tmp;

            double[] matrix = new double[4];
            double[] X      = new double[4]
            {
                _mesh.Nodes[el.IDS[0]].X,
                _mesh.Nodes[el.IDS[1]].X,
                _mesh.Nodes[el.IDS[2]].X,
                _mesh.Nodes[el.IDS[3]].X
            };
            double[] Y = new double[4]
            {
                _mesh.Nodes[el.IDS[0]].Y,
                _mesh.Nodes[el.IDS[1]].Y,
                _mesh.Nodes[el.IDS[2]].Y,
                _mesh.Nodes[el.IDS[3]].Y
            };

            Matrix <double> c = DenseMatrix.Create(4, 4, 0);

            foreach (PointF p in _points.Points)
            {
                tmp = DenseVector.OfArray(new double[]
                {
                    0.25 * ((1 - p.X) * (1 - p.Y)), // N1 w punkcie p
                    0.25 * ((1 + p.X) * (1 - p.Y)), // N2 w punkcie p
                    0.25 * ((1 + p.X) * (1 + p.Y)), // N3 w punkcie P
                    0.25 * ((1 - p.X) * (1 + p.Y))  // N4 w punkcie p
                }).ToRowMatrix();

                // funkcje_ksztaltu.Add(tmp,funkcje_ksztaltu);
                // sumujemy poszczególne funkcje kształtu we wszystkich punktach

                Matrix <double> m = tmp.Transpose();
                c = c.Add(m.Multiply(tmp));
            }

            //Matrix<double> m = funkcje_ksztaltu.ToRowMatrix();
            c = c.Multiply(_jacobianMatrix.Determinant());
            //Matrix<double> m1 = m.Transpose().Multiply(m);
            el.C = c.Multiply(_simulationData.Density * _simulationData.Specific_Heat).ToArray();
            //el.C = c.ToArray(); ;
        }
Пример #25
0
        public static DenseVector VectorOfVertexPositions(HalfEdgeMesh mesh)
        {
            int numVertices = mesh.Vertices.Length;

            DenseVector vec = DenseVector.Create(3 * numVertices, 0);

            for (int i = 0; i < numVertices; i++)
            {
                Vector3 pos   = mesh.Vertices[i].position;
                int     vBase = 3 * i;
                vec[vBase + 0] = pos.x;
                vec[vBase + 1] = pos.y;
                vec[vBase + 2] = pos.z;
            }

            return(vec);
        }
Пример #26
0
        public void DetermineStatusWithNullResidualVectorThrowsArgumentNullException()
        {
            var criteria = new List <IIterationStopCriterium <float> >
            {
                new FailureStopCriterium(),
                new DivergenceStopCriterium(),
                new IterationCountStopCriterium <float>(),
                new ResidualStopCriterium()
            };
            var iterator = new Iterator(criteria);

            Assert.Throws <ArgumentNullException>(() => iterator.DetermineStatus(
                                                      1,
                                                      DenseVector.Create(3, i => 4),
                                                      DenseVector.Create(3, i => 5),
                                                      null));
        }
Пример #27
0
        public IVector CosineDistance(IReadOnlyList <IVector> data, ref float[] dataNorm)
        {
            var norm = DotProduct(this);

            if (dataNorm == null)
            {
                dataNorm = data.Select(d => d.DotProduct(d)).ToArray();
            }

            var ret = new float[data.Count];

            for (var i = 0; i < data.Count; i++)
            {
                ret[i] = Convert.ToSingle(1d - DotProduct(data[i]) / Math.Sqrt(norm * dataNorm[i]));
            }
            return(new CpuVector(DenseVector.Create(data.Count, i => ret[i])));
        }
Пример #28
0
        public void TestAddDiagonalMatrix(int size)
        {
            var A = MatrixLoader.A(size);

            int rows = A.RowCount;
            int cols = A.ColumnCount;

            var a = DenseVector.Create(rows, (i) => 1.0 + i);
            var D = DiagonalMatrix.OfDiagonal(rows, cols, a);

            var B = A.Add(D);
            var C = A.Clone() as SparseMatrix;

            C.FastAddDiagonalMatrix(Util.GetData(a), C);

            Assert.IsTrue(MatrixComparer.Equals(B, C, EPS));
        }
Пример #29
0
        public void DetermineStatusWithNegativeIterationNumberThrowsArgumentOutOfRangeException()
        {
            var criteria = new List <IIterationStopCriterium <Complex32> >
            {
                new FailureStopCriterium(),
                new DivergenceStopCriterium(),
                new IterationCountStopCriterium <Complex32>(),
                new ResidualStopCriterium()
            };
            var iterator = new Iterator <Complex32>(criteria);

            Assert.Throws <ArgumentOutOfRangeException>(() => iterator.DetermineStatus(
                                                            -1,
                                                            DenseVector.Create(3, i => 4),
                                                            DenseVector.Create(3, i => 5),
                                                            DenseVector.Create(3, i => 6)));
        }
Пример #30
0
        private void calculateProbDens()
        {
            if (dvData.Count == 0)
            {
                return;
            }
            if (binsCount == 0)
            {
                return;
            }

            double dataMaxValue     = dvData.Values.Max();
            double dataMinValue     = dvData.Values.Min();
            double binCentersStep   = (dataMaxValue - dataMinValue) / (double)binsCount;
            double currentBinCenter = dataMinValue + binCentersStep / 2.0d;

            dvbinsCenters = DenseVector.Create(binsCount, i =>
            {
                return((double)i * binCentersStep + binCentersStep * 0.5d + dataMinValue);
            });

            dvProbDens = DenseVector.Create(binsCount, i =>
            {
                double binMin = dvbinsCenters[i] - binCentersStep * 0.5d;
                double binMax = dvbinsCenters[i] + binCentersStep * 0.5d;
                List <double> listCurrData = new List <double>();
                if (i == binsCount - 1)
                {
                    listCurrData = DataAnalysis.DataAnalysisStatic.DataListedWithCondition(dvData, (dVal => ((dVal >= binMin) && (dVal <= binMax))));
                }
                else
                {
                    listCurrData = DataAnalysis.DataAnalysisStatic.DataListedWithCondition(dvData, (dVal => ((dVal >= binMin) && (dVal < binMax))));
                }

                if (listCurrData == null)
                {
                    return(0.0d);
                }
                return((double)listCurrData.Count);
            });
            double sum = dvProbDens.Values.Sum();

            dvProbDens = (DenseVector)dvProbDens.Divide(sum);
        }