public virtual void Tan(float[] value, ref float[] returnValue)
 {
     Single.Vector input  = new Single.DenseVector(value);
     Single.Vector output = new Single.DenseVector(returnValue);
     output      = (Single.DenseVector)Single.Vector.Tan(input);
     returnValue = output.ToArray();
 }
 public virtual void Tan(float value, ref float returnValue)
 {
     Single.Vector input  = new Single.DenseVector(new float[] { value });
     Single.Vector output = new Single.DenseVector(new float[] { returnValue });
     output      = (Single.DenseVector)Single.Vector.Tan(input);
     returnValue = output[0];
 }
        public void HeapSortWithDecreasingDoubleArray()
        {
            var sortedIndices = new int[10];
            var values = new DenseVector(10);
            values[0] = 9;
            values[1] = 8;
            values[2] = 7;
            values[3] = 6;
            values[4] = 5;
            values[5] = 4;
            values[6] = 3;
            values[7] = 2;
            values[8] = 1;
            values[9] = 0;
            for (var i = 0; i < sortedIndices.Length; i++)
            {
                sortedIndices[i] = i;
            }

            ILUTPElementSorter.SortDoubleIndicesDecreasing(0, sortedIndices.Length - 1, sortedIndices, values);
            for (var i = 0; i < sortedIndices.Length; i++)
            {
                Assert.AreEqual(i, sortedIndices[i], "#01-" + i);
            }
        }
Ejemplo n.º 4
0
        public void SolveWideMatrixThrowsArgumentException()
        {
            var matrix = new SparseMatrix(2, 3);
            var input = new DenseVector(2);

            var solver = new MlkBiCgStab();
            Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
        }
Ejemplo n.º 5
0
        public void SolveLongMatrixThrowsArgumentException()
        {
            var matrix = new SparseMatrix(3, 2);
            var input = new DenseVector(3);

            var solver = new GpBiCg();
            Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
        }
Ejemplo n.º 6
0
        public void SolveWideMatrixThrowsArgumentException()
        {
            var matrix = new SparseMatrix(2, 3);
            var input = new DenseVector(2);

            var solver = new TFQMR();
            Assert.Throws<ArgumentException>(() => matrix.SolveIterative(input, solver));
        }
Ejemplo n.º 7
0
        public void SolveLongMatrixThrowsArgumentException()
        {
            var matrix = new SparseMatrix(3, 2);
            var input = new DenseVector(3);

            var solver = new MlkBiCgStab();
            Assert.Throws<ArgumentException>(() => matrix.SolveIterative(input, solver));
        }
 private float ComputeMecanumDriveMotorSpeed(DenseVector desiredMovement, VectorComponent wheelForceVectorInput)
 {
     var wheelForceVector = new DenseVector(new[] { wheelForceVectorInput.X, wheelForceVectorInput.Y });
      var wheelForceVectorUnit = wheelForceVector.Normalize(2);
      var scale = wheelForceVectorUnit.DotProduct(desiredMovement);
     //         Console.WriteLine(wheelForceVector + " " + wheelForceVectorUnit + " " + desiredMovement + " " + scale);
      return scale;
 }
 public void ApproximateWithNonInitializedPreconditionerThrowsArgumentException()
 {
     const int Size = 10;
     var vector = CreateStandardBcVector(Size);
     var preconditioner = CreatePreconditioner();
     var result = new DenseVector(vector.Count);
     Assert.Throws<ArgumentException>(() => preconditioner.Approximate(vector, result));
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Create standard vector.
        /// </summary>
        /// <param name="size">Size of the vector.</param>
        /// <returns>New vector.</returns>
        protected DenseVector CreateStandardBcVector(int size)
        {
            var vector = new DenseVector(size);
            for (var i = 0; i < size; i++)
            {
                vector[i] = i + 1;
            }

            return vector;
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Creates a new instance of the Vector class.
        /// </summary>
        /// <param name="data">The array to create this vector from.</param>
        /// <returns>The new <c>Vector</c>.</returns>
        protected override Vector<float> CreateVector(IList<float> data)
        {
            var vector = new DenseVector(data.Count);
            for (var index = 0; index < data.Count; index++)
            {
                vector[index] = data[index];
            }

            return vector;
        }
 // generating random vector
 public static Vector <float> GenerateRandomVector(int rows, params int[] parameters)
 {
     if (parameters.Length < 1)
     {
         throw new Exception("Pass no parameters");                  // check if at least 1 parameter has been passed
     }
     meanDistr  = new float[] { 0 };                                 // meanValues is zero
     sigmaDistr = new float[] { (float)Math.Sqrt(1.0 / 1) };         // sum of sigmas
     CreateDistribution(parameters);                                 // generate distirbiution
     return(DenseVector.CreateRandom(rows, continuousDistribution)); // create a matrix from continous distribtion;
 }
        public void DetermineStatus()
        {
            var criterion = new FailureStopCriterion<float>();
            Assert.IsNotNull(criterion, "There should be a criterion");

            var solution = new DenseVector(new[] { 3.0f, 2.0f, 1.0f });
            var source = new DenseVector(new[] { 1001.0f, 0.0f, 2003.0f });
            var residual = new DenseVector(new[] { 1.0f, 2.0f, 3.0f });

            var status = criterion.DetermineStatus(5, solution, source, residual);
            Assert.AreEqual(IterationStatus.Continue, status, "Should be running");
        }
        public HolonomicDriveValues MecanumDrive(HolonomicDriveTrain driveTrain, float x, float y, bool inputsSquared = false)
        {
            x = InputUtilities.TransformWithWarning(x, square: inputsSquared);
             y = InputUtilities.TransformWithWarning(y, square: inputsSquared);

             var desiredMovement = new DenseVector(new [] { x, y });
            //         var desiredMovement = new DenseVector(new [] { 1f, 0f });
             HolonomicDriveValues result = new HolonomicDriveValues();
             result.FrontLeft = ComputeMecanumDriveMotorSpeed(desiredMovement, driveTrain.FrontLeft.GetComponent<VectorComponent>(DeviceComponentType.DriveWheelForceVector));
             result.FrontRight = ComputeMecanumDriveMotorSpeed(desiredMovement, driveTrain.FrontRight.GetComponent<VectorComponent>(DeviceComponentType.DriveWheelForceVector));
             result.RearLeft = ComputeMecanumDriveMotorSpeed(desiredMovement, driveTrain.RearLeft.GetComponent<VectorComponent>(DeviceComponentType.DriveWheelForceVector));
             result.RearRight = ComputeMecanumDriveMotorSpeed(desiredMovement, driveTrain.RearRight.GetComponent<VectorComponent>(DeviceComponentType.DriveWheelForceVector));
             return result;
        }
Ejemplo n.º 15
0
        public void CanCreateDenseVectorFromArray()
        {
            var data = new float[Data.Length];
            Array.Copy(Data, data, Data.Length);
            var vector = new DenseVector(data);

            for (var i = 0; i < data.Length; i++)
            {
                Assert.AreEqual(data[i], vector[i]);
            }

            vector[0] = 100.0f;
            Assert.AreEqual(100.0f, data[0]);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Check the result.
        /// </summary>
        /// <param name="preconditioner">Specific preconditioner.</param>
        /// <param name="matrix">Source matrix.</param>
        /// <param name="vector">Initial vector.</param>
        /// <param name="result">Result vector.</param>
        protected override void CheckResult(IPreconditioner<float> preconditioner, SparseMatrix matrix, Vector<float> vector, Vector<float> result)
        {
            Assert.AreEqual(typeof (DiagonalPreconditioner), preconditioner.GetType(), "#01");

            // Compute M * result = product
            // compare vector and product. Should be equal
            var product = new DenseVector(result.Count);
            matrix.Multiply(result, product);

            for (var i = 0; i < product.Count; i++)
            {
                Assert.IsTrue(((double) vector[i]).AlmostEqualNumbersBetween(product[i], -Epsilon.Magnitude()), "#02-" + i);
            }
        }
        public void ApproximateReturningOldVector()
        {
            const int Size = 10;
            var newMatrix = CreateUnitMatrix(Size);
            var vector = CreateStandardBcVector(Size);

            var preconditioner = CreatePreconditioner();
            preconditioner.Initialize(newMatrix);

            var result = new DenseVector(vector.Count);
            preconditioner.Approximate(vector, result);

            CheckResult(preconditioner, newMatrix, vector, result);
        }
        public void CanMultiplyWithVector()
        {
            var matrix = TestMatrices["Singular3x3"];
            var x = new DenseVector(new[] { 1.0f, 2.0f, 3.0f });
            var y = matrix * x;

            Assert.AreEqual(matrix.RowCount, y.Count);

            for (var i = 0; i < matrix.RowCount; i++)
            {
                var ar = matrix.Row(i);
                var dot = ar * x;
                Assert.AreEqual(dot, y[i]);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Outer product of two vectors
        /// </summary>
        /// <param name="u">First vector</param>
        /// <param name="v">Second vector</param>
        /// <returns>Matrix M[i,j] = u[i]*v[j] </returns>
        /// <exception cref="ArgumentNullException">If the u vector is <see langword="null" />.</exception> 
        /// <exception cref="ArgumentNullException">If the v vector is <see langword="null" />.</exception> 
        public static DenseMatrix OuterProduct(DenseVector u, DenseVector v)
        {
            if (u == null)
            {
                throw new ArgumentNullException("u");
            }

            if (v == null)
            {
                throw new ArgumentNullException("v");
            }

            var matrix = new DenseMatrix(u.Count, v.Count);
            CommonParallel.For(
                0, 
                u.Count, 
                i =>
                {
                    for (var j = 0; j < v.Count; j++)
                    {
                        matrix.At(i, j, u._values[i] * v._values[j]);
                    }
                });
            return matrix;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Creates a vector containing specified elements.
        /// </summary>
        /// <param name="index">The first element to begin copying from.</param>
        /// <param name="length">The number of elements to copy.</param>
        /// <returns>A vector containing a copy of the specified elements.</returns>
        /// <exception cref="ArgumentOutOfRangeException"><list><item>If <paramref name="index"/> is not positive or
        /// greater than or equal to the size of the vector.</item>
        /// <item>If <paramref name="index"/> + <paramref name="length"/> is greater than or equal to the size of the vector.</item>
        /// </list></exception>
        /// <exception cref="ArgumentException">If <paramref name="length"/> is not positive.</exception>
        public override Vector<float> SubVector(int index, int length)
        {
            if (index < 0 || index >= _length)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            if (length <= 0)
            {
                throw new ArgumentOutOfRangeException("length");
            }

            if (index + length > _length)
            {
                throw new ArgumentOutOfRangeException("length");
            }

            var result = new DenseVector(length);

            CommonParallel.For(
                index, 
                index + length,
                i => result._values[i - index] = _values[i]);
            return result;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Returns a negated vector.
        /// </summary>
        /// <returns>The negated vector.</returns>
        /// <remarks>Added as an alternative to the unary negation operator.</remarks>
        public override Vector<float> Negate()
        {
            var result = new DenseVector(_length);
            CommonParallel.For(
                0, 
                _values.Length,
                index => result[index] = -_values[index]);

            return result;
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Converts the string representation of a real dense vector to float-precision dense vector equivalent.
        /// A return value indicates whether the conversion succeeded or failed.
        /// </summary>
        /// <param name="value">
        /// A string containing a real vector to convert.
        /// </param>
        /// <param name="formatProvider">
        /// An <see cref="IFormatProvider"/> that supplies culture-specific formatting information about value.
        /// </param>
        /// <param name="result">
        /// The parsed value.
        /// </param>
        /// <returns>
        /// If the conversion succeeds, the result will contain a complex number equivalent to value.
        /// Otherwise the result will be <c>null</c>.
        /// </returns>
        public static bool TryParse(string value, IFormatProvider formatProvider, out DenseVector result)
        {
            bool ret;
            try
            {
                result = Parse(value, formatProvider);
                ret = true;
            }
            catch (ArgumentNullException)
            {
                result = null;
                ret = false;
            }
            catch (FormatException)
            {
                result = null;
                ret = false;
            }

            return ret;
        }
Ejemplo n.º 23
0
 public HalForce6AxisVector(MathNet.Numerics.LinearAlgebra.Single.DenseVector vec)
     : base(vec.ToArray())
 {
 }
        public void ResetCalculationState()
        {
            var criterion = new ResidualStopCriterion<float>(1e-3f, 10);

            var solution = new DenseVector(new[] { 0.001f, 0.001f, 0.002f });
            var source = new DenseVector(new[] { 0.001f, 0.001f, 0.002f });
            var residual = new DenseVector(new[] { 1.000f, 1.000f, 2.001f });

            var status = criterion.DetermineStatus(5, solution, source, residual);
            Assert.AreEqual(IterationStatus.Continue, status, "Should be running");

            criterion.Reset();
            Assert.AreEqual(IterationStatus.Continue, criterion.Status, "Should not have started");
        }
        public void DetermineStatusWithConvergenceAtFirstIteration()
        {
            var criterion = new ResidualStopCriterion<float>(1e-6);

            var solution = new DenseVector(new[] { 1.0f, 1.0f, 1.0f });
            var source = new DenseVector(new[] { 1.0f, 1.0f, 1.0f });
            var residual = new DenseVector(new[] { 0.0f, 0.0f, 0.0f });

            var status = criterion.DetermineStatus(0, solution, source, residual);
            Assert.AreEqual(IterationStatus.Converged, status, "Should be done");
        }
        public void ApproximateWithVectorWithIncorrectLengthThrowsArgumentException()
        {
            const int Size = 10;
            var newMatrix = CreateUnitMatrix(Size);
            var vector = CreateStandardBcVector(Size);

            var preconditioner = CreatePreconditioner();
            preconditioner.Initialize(newMatrix);

            var result = new DenseVector(vector.Count + 10);
            Assert.That(() => preconditioner.Approximate(vector, result), Throws.ArgumentException);
        }
        public void DetermineStatusWithResidualNaN()
        {
            var criterium = new ResidualStopCriterium(1e-3f, 10);
            Assert.IsNotNull(criterium, "There should be a criterium");

            var solution = new DenseVector(new[] {1.0f, 1.0f, 2.0f});
            var source = new DenseVector(new[] {1.0f, 1.0f, 2.0f});
            var residual = new DenseVector(new[] {1000.0f, float.NaN, 2001.0f});

            var status = criterium.DetermineStatus(5, solution, source, residual);
            Assert.AreEqual(IterationStatus.Diverged, status, "Should be diverged");
        }
 public virtual float Dot(float[] a, float[] b)
 {
     Single.DenseVector vector_a = new Single.DenseVector(a);
     return(vector_a.DotProduct(new Single.DenseVector(b)));
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Converts the string representation of a real dense vector to float-precision dense vector equivalent.
 /// A return value indicates whether the conversion succeeded or failed.
 /// </summary>
 /// <param name="value">
 /// A string containing a real vector to convert.
 /// </param>
 /// <param name="result">
 /// The parsed value.
 /// </param>
 /// <returns>
 /// If the conversion succeeds, the result will contain a complex number equivalent to value.
 /// Otherwise the result will be <c>null</c>.
 /// </returns>
 public static bool TryParse(string value, out DenseVector result)
 {
     return(TryParse(value, null, out result));
 }
 public virtual double Norm(float[] a, double p)
 {
     Single.DenseVector vector_a = new Single.DenseVector(a);
     return(vector_a.Norm(p));
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Outer product of this and another vector.
 /// </summary>
 /// <param name="v">The vector to operate on.</param>
 /// <returns>
 /// Matrix M[i,j] = this[i] * v[j].
 /// </returns>
 /// <seealso cref="OuterProduct(DenseVector, DenseVector)"/>
 public Matrix<float> OuterProduct(DenseVector v)
 {
     return OuterProduct(this, v);
 }
        public void DetermineStatus()
        {
            var criterion = new ResidualStopCriterion<float>(1e-3f, 10);

            // the solution vector isn't actually being used so ...
            var solution = new DenseVector(new[] { float.NaN, float.NaN, float.NaN });

            // Set the source values
            var source = new DenseVector(new[] { 1.000f, 1.000f, 2.001f });

            // Set the residual values
            var residual = new DenseVector(new[] { 0.001f, 0.001f, 0.002f });

            var status = criterion.DetermineStatus(5, solution, source, residual);
            Assert.AreEqual(IterationStatus.Continue, status, "Should still be running");

            var status2 = criterion.DetermineStatus(16, solution, source, residual);
            Assert.AreEqual(IterationStatus.Converged, status2, "Should be done");
        }
 public static Vector <float> GenerateUnitVector(int rows) // generate unit vector
 {
     return(DenseVector.Create(rows, 1));
 }
        public void DetermineStatusWithSourceNaN()
        {
            var criterion = new ResidualStopCriterion<float>(1e-3f, 10);

            var solution = new DenseVector(new[] { 1.0f, 1.0f, 2.0f });
            var source = new DenseVector(new[] { 1.0f, 1.0f, float.NaN });
            var residual = new DenseVector(new[] { 1000.0f, 1000.0f, 2001.0f });

            var status = criterion.DetermineStatus(5, solution, source, residual);
            Assert.AreEqual(IterationStatus.Diverged, status, "Should be diverged");
        }
Ejemplo n.º 35
0
        public void CanSolveForRandomVectorWhenResultVectorGiven(int row, int column)
        {
            var matrixA = MatrixLoader.GenerateRandomDenseMatrix(row, column);
            var matrixACopy = matrixA.Clone();
            var factorSvd = matrixA.Svd(true);
            var vectorb = MatrixLoader.GenerateRandomDenseVector(row);
            var vectorbCopy = vectorb.Clone();
            var resultx = new DenseVector(column);
            factorSvd.Solve(vectorb, resultx);

            var matrixBReconstruct = matrixA * resultx;

            // Check the reconstruction.
            for (var i = 0; i < vectorb.Count; i++)
            {
                Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1e-4);
            }

            // Make sure A didn't change.
            for (var i = 0; i < matrixA.RowCount; i++)
            {
                for (var j = 0; j < matrixA.ColumnCount; j++)
                {
                    Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
                }
            }

            // Make sure b didn't change.
            for (var i = 0; i < vectorb.Count; i++)
            {
                Assert.AreEqual(vectorbCopy[i], vectorb[i]);
            }
        }
        public void DetermineStatusWithSolutionNaN()
        {
            var criterion = new FailureStopCriterion<float>();
            Assert.IsNotNull(criterion, "There should be a criterion");

            var solution = new DenseVector(new[] { 1, 1, float.NaN });
            var source = new DenseVector(new[] { 1001.0f, 0.0f, 2003.0f });
            var residual = new DenseVector(new[] { 1000.0f, 1000.0f, 2001.0f });

            var status = criterion.DetermineStatus(5, solution, source, residual);
            Assert.AreEqual(IterationStatus.Failure, status, "Should be failed");
        }
Ejemplo n.º 37
0
 /// <summary>
 /// Converts the string representation of a real dense vector to float-precision dense vector equivalent.
 /// A return value indicates whether the conversion succeeded or failed.
 /// </summary>
 /// <param name="value">
 /// A string containing a real vector to convert.
 /// </param>
 /// <param name="result">
 /// The parsed value.
 /// </param>
 /// <returns>
 /// If the conversion succeeds, the result will contain a complex number equivalent to value.
 /// Otherwise the result will be <c>null</c>.
 /// </returns>
 public static bool TryParse(string value, out DenseVector result)
 {
     return TryParse(value, null, out result);
 }
Ejemplo n.º 38
0
        /// <summary>
        /// Multiplies this matrix with another matrix and places the results into the result matrix.
        /// </summary>
        /// <param name="other">The matrix to multiply with.</param>
        /// <param name="result">The result of the multiplication.</param>
        protected override void DoMultiply(Matrix<float> other, Matrix<float> result)
        {
            result.Clear();
            var columnVector = new DenseVector(other.RowCount);

            var rowPointers = _storage.RowPointers;
            var columnIndices = _storage.ColumnIndices;
            var values = _storage.Values;

            for (var row = 0; row < RowCount; row++)
            {
                var startIndex = rowPointers[row];
                var endIndex = rowPointers[row + 1];

                if (startIndex == endIndex)
                {
                    continue;
                }

                for (var column = 0; column < other.ColumnCount; column++)
                {
                    // Multiply row of matrix A on column of matrix B
                    other.Column(column, columnVector);

                    var sum = 0f;
                    for (var index = startIndex; index < endIndex; index++)
                    {
                        sum += values[index] * columnVector[columnIndices[index]];
                    }

                    result.At(row, column, sum);
                }
            }
        }
Ejemplo n.º 39
0
 /// <summary>
 /// Outer product of this and another vector.
 /// </summary>
 /// <param name="v">The vector to operate on.</param>
 /// <returns>
 /// Matrix M[i,j] = this[i] * v[j].
 /// </returns>
 /// <seealso cref="OuterProduct(DenseVector, DenseVector)"/>
 public Matrix <float> OuterProduct(DenseVector v)
 {
     return(OuterProduct(this, v));
 }