Example #1
0
        public override double[] GetPriorProbabilities(OptimizationParameterList discreteParameters)
        {
            const double eps = 0.0001;

            double[] priors = new double[NonMissingClassCount];

            try
            {
                EigenPair       eig         = LinearAlgebra.ComputeSparseEigenPair(LinearAlgebra.Transpose(GetTransitionProbabilityMatrix(discreteParameters, 1)));
                ComplexNumber[] eigenValues = eig.EigenValues;
                for (int i = 0; i < 4; i++)
                {
                    if (ComplexNumber.ApproxEqual(eigenValues[i], 1, eps))
                    {
                        priors = LinearAlgebra.Abs(LinearAlgebra.ComplexToDouble(LinearAlgebra.Transpose(eig.EigenVectors)[i]));
                        break;
                    }
                }

                priors = LinearAlgebra.Normalize(priors);
            }
            catch (Exception e)
            {
                throw new NotComputableException("Problem computing the prior: " + e.Message);
            }

            return(priors);
        }
Example #2
0
 private void numM_ValueChanged(object sender, EventArgs e)
 {
     double[,] matrix = { { (double)numM11.Value, (double)numM12.Value, (double)numM13.Value },
                          { (double)numM21.Value, (double)numM22.Value, (double)numM23.Value },
                          { (double)numM31.Value, (double)numM32.Value, (double)numM33.Value } };
     txtDeterminant.Text = LinearAlgebra.GetDeterminant(matrix).ToString();
 }
        public static void TestLUDecomposition()
        {
            //-----------------------------
            //| 0.18 | 0.41 | 0.14 | 0.51 |
            //| 0.60 | 0.24 | 0.30 | 0.13 |
            //| 0.57 | 0.99 | 0.97 | 0.19 |
            //| 0.96 | 0.58 | 0.66 | 0.85 |
            //-----------------------------

            Matrix matrix = new Matrix(4, 4);

            matrix.SetValue(0, 0, 0.18);
            matrix.SetValue(0, 1, 0.60);
            matrix.SetValue(0, 2, 0.57);
            matrix.SetValue(0, 3, 0.96);
            matrix.SetValue(1, 0, 0.41);
            matrix.SetValue(1, 1, 0.24);
            matrix.SetValue(1, 2, 0.99);
            matrix.SetValue(1, 3, 0.58);
            matrix.SetValue(2, 0, 0.14);
            matrix.SetValue(2, 1, 0.30);
            matrix.SetValue(2, 2, 0.97);
            matrix.SetValue(2, 3, 0.66);
            matrix.SetValue(3, 0, 0.51);
            matrix.SetValue(3, 1, 0.13);
            matrix.SetValue(3, 2, 0.19);
            matrix.SetValue(3, 3, 0.85);
            Vector b = new Vector(4);

            b.SetValue(0, 1);
            b.SetValue(1, 2);
            b.SetValue(2, 3);
            b.SetValue(3, 4);
            Vector x = new Vector(4);

            //LU分解による解法
            int         sig;
            Permutation perm = new Permutation(4);

            LinearAlgebra.LUDecomposition(ref matrix, ref perm, out sig);
            LinearAlgebra.LUSolve(matrix, perm, b, ref x);
            LinearAlgebra.LUSolve(matrix, perm, ref b);

            //QR分解による解法

            /*Vector tau = new Vector(4);
             * LinearAlgebra.QRDecomposition(ref matrix, ref tau);
             * LinearAlgebra.QRSolve(matrix, tau, b, ref x);*/

            Console.WriteLine(x.GetValue(0));
            Console.WriteLine(x.GetValue(1));
            Console.WriteLine(x.GetValue(2));
            Console.WriteLine(x.GetValue(3));
        }
Example #4
0
    private int FindCutPoint(Vector3 start, Vector3 end, PolygonSide neighbor)
    {
        Vector3 p0 = vertices[neighbor.left];
        Vector3 p1 = vertices[neighbor.right];
        float   d;
        var     cutPoint = LinearAlgebra.getClosest(start, end, p0, p1, out d);
        int     index    = AddCutPoint(cutPoint, sside);

        cutEdges[index] = neighbor;
        return(index);
    }
Example #5
0
        public override void HandleRotationChanged(double angleX, double angleY)
        {
            var a = new Vec3(0, 0, 0);
            var b = new Vec3(0, 0, 1);

            foreach (var f in this.model.Faces)
            {
                var n = f.GetNormal();
                LinearAlgebra.PlaneVectorIntersection(a, b, n, f.GetVertexPositions().First());
            }
            base.HandleRotationChanged(angleX, angleY);
        }
Example #6
0
 private bool isOnPolygonSide(Vector3 intersection, MPolygon polygon, out PolygonSide intersectSide)
 {
     foreach (var side in polygon.GetSides())
     {
         if (LinearAlgebra.isInSegment(intersection, vertices[side.left], vertices[side.right]))
         {
             intersectSide = side;
             return(true);
         }
     }
     intersectSide = null;
     return(false);
 }
Example #7
0
 private bool isPolygonCorner(Vector3 intersection, MPolygon polygon, out int intersectCorner)
 {
     foreach (var corner in polygon)
     {
         if (LinearAlgebra.IsNear(intersection, vertices[corner]))
         {
             intersectCorner = corner;
             return(true);
         }
     }
     intersectCorner = -1;
     return(false);
 }
Example #8
0
    private List <int> CutUpPolygons(int triangle, PolygonSide side, Vector3 pointSide, int corner, Vector3 pointCorner, out List <MPolygon> newPolys, out MPolygon remove)
    {
        var polys           = polyAtTriangle[triangle];
        var cutPointIndices = new List <int> ();

        newPolys = null;
        remove   = null;
        if (!LinearAlgebra.isInSegment(pointCorner, vertices[side.left], vertices[side.right]))
        {
            for (int j = 0; j < polys.Count; j++)
            {
                var polygon     = polys[j];
                var numNewVerts = -1;

                bool entryInPolygon = isPolygonCorner(pointCorner, polygon, out corner);
                bool exitInPolygon  = isOnPolygonSide(pointSide, polygon, out side);

                if (entryInPolygon && exitInPolygon)
                {
                    remove      = polygon;
                    numNewVerts = CutPolygon(polygon, out newPolys, side, corner);
                }

                if (numNewVerts > 0)
                {
                    var newV1 = vertices.Count;
                    if (!vertices.Contains(pointSide))
                    {
                        vertices.Add(pointSide);
                        normals.Add(GetMiddleNormal(side, pointSide));
                        cutPointIndices.Add(newV1);
                    }
                    else
                    {
                        var newIndex = vertices.IndexOf(pointSide);
                        foreach (var pol in newPolys)
                        {
                            int index = pol.IndexOf(newV1);
                            pol.RemoveAt(index);
                            pol.Insert(index, newIndex);
                        }
                        cutPointIndices.Add(newIndex);
                    }
                    break;
                }
            }
        }
        return(cutPointIndices);
    }
        /// <summary>
        /// ouput coeffcient , ax+by+c=0
        /// Solve : [0] = [x1   y1  1]  [a]
        ///         [0]   [x2   y2  1]  [b]
        ///                             [c]
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public override void OnValueChanged(object sender, EventArgs args)
        {
            Mat        xVectors = new Mat();
            List <Mat> coord    = new List <Mat> {
                m_end1.Point.Transpose(),
                       m_end2.Point.Transpose()
            };

            //vertical concate
            Cv2.VConcat(coord.ToArray(), xVectors);
            m_coeff = LinearAlgebra.RightSingularVector(xVectors);;


            base.OnValueChanged(sender, args);
        }
Example #10
0
    public double[] SuggestXs(int count, PhiEquationSolution[] solutions, Random rand)
    {
        if (solutions.Length < count + 1)
        {
            return(new NearBestSolution().SuggestXs(count, solutions, rand));
        }

        double[] suggestedXs = new double[count];

        PhiEquationSolution referenceSolution = solutions[count];

        // 2D array of error differences vs. the Nth solution
        double[,] Mm = new double[count, count];
        for (int j = 0; j < count; j++)
        {
            for (int k = 0; k < count; k++)
            {
                Mm[j, k] = solutions[k].Errors[j] - referenceSolution.Errors[j];
            }
        }

        // 1d array of errors for the worst solution known
        double[] mF0 = new double[count];
        for (int j = 0; j < count; j++)
        {
            mF0[j] = -referenceSolution.Errors[j];
        }

        // 2D array of phis differences vs. the worst solution
        double[,] Vm = new double[count, count];
        for (int j = 0; j < count; j++)
        {
            for (int k = 0; k < count; k++)
            {
                Vm[j, k] = solutions[k].Phis[j] - referenceSolution.Phis[j];
            }
        }

        double[] u     = LinearAlgebra.Solve(Mm, mF0);
        double[] delta = LinearAlgebra.Product(Vm, u);

        for (int j = 0; j < count; j++)
        {
            suggestedXs[j] = referenceSolution.Phis[j] + delta[j];
        }

        return(suggestedXs);
    }
Example #11
0
    public void Test_SolveRandomDataset_SolutionIsValid()
    {
        Random rand = new Random(0);

        int arrayLength = 10;

        double[,] input2d = LinearAlgebra.RandomArray2d(arrayLength, arrayLength, rand);
        double[] input1d = LinearAlgebra.RandomArray1d(arrayLength, rand);

        double[] solution = LinearAlgebra.Solve(input2d, input1d);
        double[] product  = LinearAlgebra.Product(input2d, solution);

        for (int rowIndex = 0; rowIndex < arrayLength; rowIndex++)
        {
            double difference = Math.Abs(product[rowIndex] - input1d[rowIndex]);
            Assert.That(difference < 1E-10);
        }
    }
    bool DetectWallAhead(float distance, out RaycastHit hit, Vector3 origin)
    {
        Vector3 surfaceNormal = CalculateAverageNormalVector(transform.position.x, transform.position.z);
        Vector3 vectorA       = LinearAlgebra.FindNormalVectors(surfaceNormal)[0];
        Vector3 vectorB       = LinearAlgebra.FindNormalVectors(surfaceNormal)[1];
        Vector3 forwardVector;

        if (vectorA.x == 0)
        {
            forwardVector = vectorA;
        }
        else if (vectorB.x == 0)
        {
            forwardVector = vectorB;
        }
        else
        {
            float scalingFactor = vectorB.x / vectorA.x;

            Debug.Log(vectorA + " - " + vectorB + scalingFactor);

            forwardVector = vectorA - scalingFactor * vectorB;
        }


        forwardVector = (forwardVector.z > 0) ? -1 * forwardVector : forwardVector;

        Vector3 rayOrigin = origin - 0.75f * surfaceNormal;

        Ray ray = new Ray(rayOrigin, forwardVector.normalized);

        //Debug.Log(transform.position + " " + transform.position + forwardVector*5f);
        Debug.DrawLine(rayOrigin, rayOrigin + forwardVector.normalized * distance);

        if (Physics.Raycast(ray, out hit, distance, wallMask))
        {
            Debug.DrawLine(rayOrigin, rayOrigin + forwardVector.normalized * distance, Color.red);
            return(true);
        }
        else
        {
            return(false);
        }
    }
Example #13
0
        public void TestOrederVertices2()
        {
            var vertices = new List <Vec3>()
            {
                new Vec3(0, 1, 1),
                new Vec3(0, -1, 1),
                new Vec3(0, -1, -1),
                new Vec3(0, 1, -1),
            };
            var result = LinearAlgebra.OrderVertices(vertices);

            for (int i = 0; i < 4; i++)
            {
                var a         = result[i];
                var b         = result[(i + 1) % 4];
                var totalDiff = a - b;
                Assert.IsTrue(totalDiff.Mag() <= 2);
            }
        }
        public override void OnValueChanged(object sender, EventArgs args)
        {
            //TODO invoke fitting methods
            //output m_end1 , m_end2
            Mat xVectors = new Mat();
            var coords   = m_dependencies.Select((ElementBase p) =>
            {
                return((p as PointBase).Point.Transpose());
            });

            //
            Cv2.VConcat(coords.ToArray(), xVectors);
            m_coeff =
                LinearAlgebra.DataFitting(xVectors,
                                          Mat.Zeros(xVectors.Rows, 1, xVectors.Type()),
                                          LinearAlgebra.FittingCategrory.Polynominal);

            base.OnValueChanged(sender, args);
        }
Example #15
0
        /// <summary>
        /// Calculate the intersection of two lines
        /// May expanded to line-circle , circle-circle
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public override void OnValueChanged(object sender, EventArgs args)
        {
            Mat        xVectors = new Mat();
            List <Mat> lineCoes = new List <Mat>
            {
                m_line1.Coefficient().Transpose(),
                       m_line2.Coefficient().Transpose()
            };

            //vertical concate
            Cv2.VConcat(lineCoes.ToArray(), xVectors);

            m_point = LinearAlgebra.RightSingularVector(xVectors);

            //homogenous
            m_point /= m_point.Get <double>(m_point.Rows - 1);


            base.OnValueChanged(sender, args);
        }
Example #16
0
		public override LinearAlgebra.DoubleVector Search(LinearAlgebra.DoubleVector x, LinearAlgebra.DoubleVector direction, double step)
		{
			DoubleVector retx = new DoubleVector(x);
			double oldVal = FunctionEvaluation(retx);
			double newVal = oldVal;

			// First find the initial direction
			double valPos = FunctionEvaluation(retx + direction * step);
			double valNeg = FunctionEvaluation(retx - direction * step);
			if (valPos >= oldVal && valNeg < oldVal) // we reverse the direction only if the other direction really gives the smaller result
			{
				retx -= direction * step;
				oldVal = valNeg;
				step = -step;
			}
			else if (valPos < oldVal)
			{
				retx += direction * step;
				oldVal = valPos;
			}

			// now iterate
			for (; ; )
			{
				retx += direction * step;
				newVal = FunctionEvaluation(retx);

				if (newVal > oldVal)
				{
					step /= -2;
				}
				else if (!(newVal != oldVal))
				{
					break;
				}
				oldVal = newVal;
			}

			return retx;
		}
Example #17
0
        public override void EnterState()
        {
            mModel.SetupAnimationClips();

            // Walk to the nearest point on the end finish line
            Vector3 start2End = (mLevel.End.First - mLevel.Start.First).normalized;

            Vector3 start2EndCrossUp = Vector3.Cross(start2End, Vector3.up).normalized;

            Vector3 endLineStart = (start2EndCrossUp * 0.5f * mLevel.EndWidth) + mLevel.End.First;
            Vector3 endLineEnd   = (start2EndCrossUp * -0.5f * mLevel.EndWidth) + mLevel.End.First;

            mModel.WalkTo
            (
                new Pair <Vector3>
                (
                    LinearAlgebra.NearestPointOnLineSegment(endLineStart, endLineEnd, mModel.UnityGameObject.transform.position),
                    start2End
                ),
                mModel.TargetReached
            );
        }
Example #18
0
        public override void EnterState()
        {
            Vector3 middlePathPoint = LinearAlgebra.NearestPointOnLineSegment(mLevel.Start.First, mLevel.End.First, mModel.UnityGameObject.transform.position);

            mModel.WalkTo
            (
                new Pair <Vector3>
                (
                    Vector3.Lerp
                    (
                        middlePathPoint,
                        mModel.UnityGameObject.transform.position,
                        Mathf.Lerp(0.0f, 0.5f, UnityEngine.Random.value)
                    ),
                    (mLevel.Start.First - mLevel.End.First).normalized
                ),
                delegate()
            {
                mModel.WalkToEndTarget();
            }
            );
        }
    // Returns a prediction with the current weights and bias'
    private double FeedForward(double[] example)
    {
        double prediction;

        // Index of 0 indicates the input layer
        neurons[0] = example;

        for (int layer = 0; layer < no_layers - 1; layer++)
        {
            // Mulitiply by the weights then add the bias
            neurons[layer + 1] = LinearAlgebra.mult2d_vec(all_weights[layer], neurons[layer]);
            neurons[layer + 1] = LinearAlgebra.Addvec_vec(neurons[layer + 1], all_bias[layer]);

            // Don't apply the activation function to the last layer output neurons
            if (!(layer + 1 == no_layers - 1))
            {
                Sigmoid(ref neurons[layer + 1]);
            }
        }
        prediction = neurons[no_layers - 1][0]; // 0 Since there is only one ouput node

        return(prediction);
    }
Example #20
0
    private Vector3 FindPointOnTriangle(int t1, Vector3 start, Vector3 end, ref PolygonSide closestSide)
    {
        var     triangle        = GetTriangle(t1);
        var     sides           = triangle.GetSides();
        var     minDist         = float.MaxValue;
        Vector3 closestCutPoint = default(Vector3);

        foreach (var side in sides)
        {
            if (!side.SameAs(closestSide))
            {
                float distance;
                var   minCutPoint = LinearAlgebra.getClosest(start, end, vertices[side.left], vertices[side.right], out distance);
                // Misc.DebugSphere (closestIntersection, Color.magenta, "Intersection point on Side for " + hit1);
                if (distance < minDist)
                {
                    closestCutPoint = minCutPoint;
                    closestSide     = side;
                    minDist         = distance;
                }
            }
        }
        return(closestCutPoint);
    }
Example #21
0
		public override LinearAlgebra.DoubleVector Search(LinearAlgebra.DoubleVector x, LinearAlgebra.DoubleVector direction, double step)
		{
			return Search(x, x + direction * step, _numberOfInitialDivisions, _numberOfSubsequentDivisions, _divisionDepth);
		}
Example #22
0
		private int SearchMinimumByDivision(LinearAlgebra.DoubleVector bound0, LinearAlgebra.DoubleVector bound1, int numberOfInitialDivisions)
		{
			double minValue = double.PositiveInfinity;
			int imin = -1;

			for (int i = 0; i <= numberOfInitialDivisions; i++)
			{
				double r = i / (double)numberOfInitialDivisions;
				double actValue = FunctionEvaluation(bound0 * (1 - r) + bound1 * r);
				if (actValue < minValue)
				{
					minValue = actValue;
					imin = i;
				}
			}
			return imin;
		}
Example #23
0
 public new double[,] CallLayer(double[,] X)
 {
     // Call Dense Layer w/ Input X
     return(LinearAlgebra.MatrixProduct(W, X));
 }
        private void linear_Algebra_Click(object sender, EventArgs e)
        {
            LinearAlgebra page = new LinearAlgebra();

            page.Show();
        }
 public void CanConvertArrayToSparseVector()
 {
     var array = new[] {0.0f, 1.0f, 2.0f, 3.0f, 4.0f};
     var vector = SparseVector.OfEnumerable(array);
     Assert.IsInstanceOf(typeof (SparseVector), vector);
     CollectionAssert.AreEqual(vector, array);
 }
        public static void TestInverse()
        {
            //----------------------
            //| 0.18 | 0.41 | 0.14 |
            //| 0.60 | 0.24 | 0.30 |
            //| 0.57 | 0.99 | 0.97 |
            //----------------------

            Matrix matrix  = new Matrix(3, 3);
            Matrix matrix2 = new Matrix(4, 4);

            matrix.SetValue(0, 0, 0.18);
            matrix.SetValue(0, 1, 0.41);
            matrix.SetValue(0, 2, 0.14);
            matrix.SetValue(1, 0, 0.60);
            matrix.SetValue(1, 1, 0.24);
            matrix.SetValue(1, 2, 0.30);
            matrix.SetValue(2, 0, 0.57);
            matrix.SetValue(2, 1, 0.99);
            matrix.SetValue(2, 2, 0.97);
            double[,] test = matrix.ToArray();
            for (uint i = 0; i < matrix.Columns; i++)
            {
                for (uint j = 0; j < matrix.Rows; j++)
                {
                    matrix2.SetValue(i + 1, j + 1, matrix.GetValue(i, j));
                }
            }

            //LU分解による方法
            Matrix      inv = new Matrix(3, 3);
            int         sig;
            Permutation perm = new Permutation(3);

            perm.Initialize();
            LinearAlgebra.LUDecomposition(ref matrix, ref perm, out sig);
            LinearAlgebra.LUInvert(matrix, perm, ref inv);
            for (uint i = 0; i < inv.Columns; i++)
            {
                for (uint j = 0; j < inv.Rows; j++)
                {
                    Console.Write(inv.GetValue(i, j).ToString("F4").PadLeft(8) + " | ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();

            //部分行列のテスト
            perm.Initialize();
            Matrix     inv2     = new Matrix(4, 4);
            MatrixView mView    = new MatrixView(matrix2, 1, 1, 3, 3);
            MatrixView mViewINV = new MatrixView(inv2, 0, 1, 3, 3);

            LinearAlgebra.LUDecomposition(ref mView, ref perm, out sig);
            LinearAlgebra.LUInvert(mView, perm, ref mViewINV);
            for (uint i = 0; i < mViewINV.ColumnSize; i++)
            {
                for (uint j = 0; j < mViewINV.RowSize; j++)
                {
                    Console.Write(mViewINV.GetValue(i, j).ToString("F4").PadLeft(8) + " | ");
                }
                Console.WriteLine();
            }
            Console.WriteLine();

            for (uint i = 0; i < inv2.Columns; i++)
            {
                for (uint j = 0; j < inv2.Rows; j++)
                {
                    Console.Write(inv2.GetValue(i, j).ToString("F4").PadLeft(8) + " | ");
                }
                Console.WriteLine();
            }

            Console.Read();
        }
Example #27
0
		public LinearAlgebra.DoubleVector Search(LinearAlgebra.DoubleVector bound0, LinearAlgebra.DoubleVector bound1, int numberOfInitialDivisions, int numberOfSubsequentDivisions, int divisionDepth)
		{
			if (numberOfInitialDivisions < 2)
				throw new ArgumentOutOfRangeException("Number of initial divisions must not smaller than 2");
			if (numberOfSubsequentDivisions < 2)
				throw new ArgumentOutOfRangeException("Number of subsequent divisions must be not smaller than 2");

			int actualNumberOfDivisions = numberOfInitialDivisions;
			int imin = SearchMinimumByDivision(bound0, bound1, actualNumberOfDivisions);

			if (imin < 0)
				throw new ArgumentOutOfRangeException("Function evaluation resulted in either all invalid or infinite function values");

			double r = imin / (double)actualNumberOfDivisions;
			double rstep = 1 / (double)actualNumberOfDivisions;

			double rmin = Math.Max(0, r - rstep);
			double rmax = Math.Min(1, r + rstep);

			DoubleVector xLeft = bound0 * (1 - rmin) + bound1 * rmin;
			DoubleVector xRight = bound0 * (1 - rmax) + bound1 * rmax;

			if (divisionDepth <= 0)
			{
				return bound0 * (1 - r) + bound1 * r;
			}
			else if (numberOfSubsequentDivisions == 2)
			{
				DoubleVector xMiddle = bound0 * (1 - r) + bound1 * r;
				return BinaryMinimumSearch(xLeft, FunctionEvaluation(xLeft), xMiddle, FunctionEvaluation(xMiddle), xRight, FunctionEvaluation(xRight), divisionDepth);
			}
			else
			{
				return SearchMinimumByRecursiveDivisions(xLeft, xRight, numberOfSubsequentDivisions, divisionDepth);
			}
		}
Example #28
0
dgtsl(int n, double[] c, double[] d, double[] e, LinearAlgebra.IVector b)
			{
				/* solves a tridiagonal matrix A x = b

					 c[1 .. n - 1]   subdiagonal of the matrix A
					 d[0 .. n - 1]   diagonal of the matrix A
					 e[0 .. n - 2]   superdiagonal of the matrix A

					 b[0 .. n - 1]   right hand side, replaced by the solution vector x */

				int k;

				c[0] = d[0];

				if (n == 0)
				{
					return GSL_ERR.GSL_SUCCESS;
				}

				if (n == 1)
				{
					b[0] = b[0] / d[0];
					return GSL_ERR.GSL_SUCCESS;
				}

				d[0] = e[0];
				e[0] = 0;
				e[n - 1] = 0;

				for (k = 0; k < n - 1; k++)
				{
					int k1 = k + 1;

					if (Math.Abs(c[k1]) >= Math.Abs(c[k]))
					{
						{
							double t = c[k1];
							c[k1] = c[k];
							c[k] = t;
						};
						{
							double t = d[k1];
							d[k1] = d[k];
							d[k] = t;
						};
						{
							double t = e[k1];
							e[k1] = e[k];
							e[k] = t;
						};
						{
							double t = b[k1];
							b[k1] = b[k];
							b[k] = t;
						};
					}

					if (c[k] == 0)
					{
						return GSL_ERR.GSL_FAILURE;
					}

					{
						double t = -c[k1] / c[k];

						c[k1] = d[k1] + t * d[k];
						d[k1] = e[k1] + t * e[k];
						e[k1] = 0;
						b[k1] = b[k1] + t * b[k];
					}
				}

				if (c[n - 1] == 0)
				{
					return GSL_ERR.GSL_FAILURE;
				}

				b[n - 1] = b[n - 1] / c[n - 1];

				b[n - 2] = (b[n - 2] - d[n - 2] * b[n - 1]) / c[n - 2];

				for (k = n; k > 2; k--)
				{
					int kb = k - 3;
					b[kb] = (b[kb] - d[kb] * b[kb + 1] - e[kb] * b[kb + 2]) / c[kb];
				}

				return GSL_ERR.GSL_SUCCESS;
			}
        public void CanPointwiseMultiplySparseVector()
        {
            var zeroArray = new[] {0.0f, 1.0f, 0.0f, 1.0f, 0.0f};
            var vector1 = SparseVector.OfEnumerable(Data);
            var vector2 = SparseVector.OfEnumerable(zeroArray);
            var result = new SparseVector(vector1.Count);

            vector1.PointwiseMultiply(vector2, result);

            for (var i = 0; i < vector1.Count; i++)
            {
                Assert.AreEqual(Data[i]*zeroArray[i], result[i]);
            }

            var resultStorage = (SparseVectorStorage<float>) result.Storage;
            Assert.AreEqual(2, resultStorage.ValueCount);
        }
    public override void Process(NPVoxModel model, NPVoxMeshTempData tempdata, Vector3[] inNormals, ref Vector3[] outNormals)
    {
        if (meshReference != null)
        {
            Vector3 sizeVoxel = tempdata.voxToUnity.VoxeSize;
            if (!dataAlreadyCollected)
            {
                Vector3  sizeVoxModel   = tempdata.voxToUnity.UnityVoxModelSize;
                NPVoxBox boundsVoxModel = model.BoundingBox;
                Bounds   boundsMesh     = meshReference.bounds;

                offset = boundsMesh.min;

                scale = new Vector3(
                    boundsMesh.size.x / sizeVoxModel.x,
                    boundsMesh.size.y / sizeVoxModel.z,
                    boundsMesh.size.z / sizeVoxModel.y
                    );

                meshReference.GetNormals(meshNormals);

                meshReference.GetVertices(meshVertices);
                triangleList = meshReference.GetTriangles(0);
            }

            Vector3 x = new Vector3(
                (tempdata.voxCoord.X + 0.5f) * sizeVoxel.x,
                (tempdata.voxCoord.Y + 0.5f) * sizeVoxel.y,
                (tempdata.voxCoord.Z + 0.5f) * sizeVoxel.z
                );

            x = new Vector3(
                x.x * scale.x,
                x.z * scale.z,
                x.y * scale.y
                );

            x += offset;

            int     bestTriangle        = -1;
            float   bestDistanceSquared = float.PositiveInfinity;
            Vector3 bestNormal          = Vector3.zero;
            Vector3 bestPoint           = Vector3.zero;

            for (int triangle = 0; triangle < triangleList.Length; triangle += 3)
            {
                Vector3 v1 = meshVertices[triangleList[triangle + 0]];
                Vector3 v2 = meshVertices[triangleList[triangle + 1]];
                Vector3 v3 = meshVertices[triangleList[triangle + 2]];

                Bounds boundTest = new Bounds(v1, Vector3.zero);
                boundTest.Encapsulate(v2);
                boundTest.Encapsulate(v3);
                boundTest.Expand(0.1f);

                if (!boundTest.Contains(x))
                {
                    continue;
                }

                Vector3 n = LinearAlgebra.ComputePlaneNormal(v1, v2, v3);

                Vector3 xProjected;
                LinearAlgebra.ProjectPointToPlane(v1, n, x, out xProjected);

                Vector3 xBarycentric = LinearAlgebra.WorldToBarycentric3(v1, v2, v3, xProjected);

                if (xBarycentric.x < 0.0)
                {
                    xProjected = LinearAlgebra.ClampToLine(v2, v3, xProjected);
                }

                else if (xBarycentric.y < 0.0)
                {
                    xProjected = LinearAlgebra.ClampToLine(v3, v1, xProjected);
                }

                else if (xBarycentric.z < 0.0)
                {
                    xProjected = LinearAlgebra.ClampToLine(v1, v2, xProjected);
                }

                float sqaredDistance = (xProjected - x).sqrMagnitude;

                if (!float.IsNaN(sqaredDistance) && sqaredDistance < bestDistanceSquared)
                {
                    bestDistanceSquared = sqaredDistance;
                    bestTriangle        = triangle;
                    bestNormal          = n;
                    bestPoint           = xProjected;
                }
            }

            Vector3 average = Vector3.zero;

            bool smoothNormals = true;

            if (bestTriangle != -1)
            {
                if (smoothNormals)
                {
                    average = LinearAlgebra.BarycentricToWorld(
                        meshNormals[triangleList[bestTriangle + 0]],
                        meshNormals[triangleList[bestTriangle + 1]],
                        meshNormals[triangleList[bestTriangle + 2]],
                        LinearAlgebra.WorldToBarycentric3(
                            meshVertices[triangleList[bestTriangle + 0]],
                            meshVertices[triangleList[bestTriangle + 1]],
                            meshVertices[triangleList[bestTriangle + 2]],
                            bestPoint)
                        );
                }
                else
                {
                    average = meshNormals[triangleList[bestTriangle]];
                    //average = new Vector3(
                    //    bestNormal.x,
                    //    bestNormal.z,
                    //    bestNormal.y
                    //    );
                }


                average = new Vector3(
                    average.x / scale.x,
                    average.z / scale.z,
                    average.y / scale.y
                    );
            }

            for (int t = 0; t < tempdata.numVertices; t++)
            {
                outNormals[tempdata.vertexIndexOffsetBegin + t] = average;
            }
        }
        else
        {
            for (int t = 0; t < tempdata.numVertices; t++)
            {
                outNormals[tempdata.vertexIndexOffsetBegin + t] = inNormals[tempdata.vertexIndexOffsetBegin + t];
            }
        }
    }
Example #31
0
        public float[,] GetMappingTransform(
            PointF p1,
            PointF p2,
            PointF p3,
            PointF desP1,
            PointF desP2,
            PointF desP3)
        {
            // Well, we're basically trying to solve two systems of linear
            // equations here.  They are:
            //
            // x'0 = a11 * x0 + a12 * y0 + a13
            // x'1 = a11 * x1 + a12 * y1 + a13
            // x'2 = a11 * x2 + a12 * y2 + a13
            //
            // and
            //
            // y'0 = a21 * x0 + a22 * y0 + a23
            // y'1 = a21 * x1 + a22 * y1 + a23
            // y'2 = a21 * x2 + a22 * y2 + a23
            //
            // So, we're going to put our known quantities in an augmented
            // matrix form, and solve for the a(rc)'s that will transform
            // the initial four points to the desired four points.

            float[,] a = new float[3, 3];
            float[,] b = new float[3, 4];

            for (int i = 0; i < 3; i++)
            {
                a[i, 2] = 1.0f;
            }

            a[0, 0] = p1.X;
            a[0, 1] = p1.Y;

            a[1, 0] = p2.X;
            a[1, 1] = p2.Y;

            a[2, 0] = p3.X;
            a[2, 1] = p3.Y;

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

            b[0, 3] = (float)desP1.X;
            b[1, 3] = (float)desP2.X;
            b[2, 3] = (float)desP3.X;

            // First, we'll find the transformation coefficients
            // which will map the contour.
            LinearAlgebra.GaussJ(ref a, 3, ref b, 4);

            float[,] transformCoeff = new float[2, 3];

            for (int i = 0; i < 3; i++)
            {
                transformCoeff[0, i] = b[i, 3];
            }

            // Ok, now we have one row of coefficients.  We now need to reinitialize
            // the a and b matrices since the gaussj() solver function has changed
            // their values
            for (int i = 0; i < 3; i++)
            {
                a[i, 2] = 1.0f;
            }

            a[0, 0] = p1.X;
            a[0, 1] = p1.Y;

            a[1, 0] = p2.X;
            a[1, 1] = p2.Y;

            a[2, 0] = p3.X;
            a[2, 1] = p3.Y;

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

            // This time, we're going to solve for the second row of
            // coefficients, so we'll put the desired y values in the augmented
            // section
            b[0, 3] = (float)desP1.Y;
            b[1, 3] = (float)desP2.Y;
            b[2, 3] = (float)desP3.Y;

            LinearAlgebra.GaussJ(ref a, 3, ref b, 4);

            // Save the transform coefficients
            for (int i = 0; i < 3; i++)
            {
                transformCoeff[1, i] = b[i, 3];
            }

            return(transformCoeff);
        }
    public override void Process(NPVoxModel model, NPVoxMeshData tempdata, Vector3[] inNormals, ref Vector3[] outNormals)
    {
        if (m_meshReference != null && !tempdata.isHidden)
        {
            Vector3 sizeVoxel = tempdata.voxToUnity.VoxeSize;
            if (!m_dataAlreadyCollected)
            {
                Vector3 sizeVoxModel = model.BoundingBoxMinimal.Size.ToVector3();
                Bounds  boundsMesh   = m_meshReference.bounds;

                m_offsetVox  = model.BoundingBoxMinimal.LeftDownBack.ToVector3();
                m_offsetMesh = boundsMesh.min;
                m_scaleVox   = model.BoundingBoxMinimal.Size.ToVector3();
                m_scaleMesh  = new Vector3(boundsMesh.size.x, boundsMesh.size.y, boundsMesh.size.z);

                m_meshReference.GetNormals(m_meshNormals);

                m_meshReference.GetVertices(m_meshVertices);
                m_triangleList = m_meshReference.GetTriangles(0);

                m_dataAlreadyCollected = true;
                Swap <bool>(m_swapAxes, ref m_flipX, ref m_flipY, ref m_flipZ);
            }

            Vector3 localOffset;
            ComputeLocalOffset(tempdata, out localOffset);
            Vector3 x = tempdata.voxCoord.ToVector3() - m_offsetVox;
            //x += localOffset;

            x += new Vector3(0.5f, 0.5f, 0.5f);
            x  = LinearAlgebra.DivideComponents(x, m_scaleVox);

            Swap(m_swapAxes, ref x);
            FlipPosition(m_flipX, m_flipY, m_flipZ, new Vector3(1.0f, 1.0f, 1.0f), ref x);

            x  = LinearAlgebra.MultiplyComponents(x, m_scaleMesh);
            x += m_offsetMesh;


            int     bestTriangle        = -1;
            float   bestDistanceSquared = float.PositiveInfinity;
            Vector3 bestNormal          = Vector3.zero;
            Vector3 bestPoint           = Vector3.zero;

            for (int triangle = 0; triangle < m_triangleList.Length; triangle += 3)
            {
                Vector3 v1 = m_meshVertices[m_triangleList[triangle + 0]];
                Vector3 v2 = m_meshVertices[m_triangleList[triangle + 1]];
                Vector3 v3 = m_meshVertices[m_triangleList[triangle + 2]];

                Vector3 n = LinearAlgebra.ComputePlaneNormal(v1, v2, v3);

                Vector3 xProjected;
                LinearAlgebra.ProjectPointToPlane(v1, n, x, out xProjected);

                Vector3 xBarycentric = LinearAlgebra.WorldToBarycentric3(v1, v2, v3, xProjected);

                if (xBarycentric.x < 0.0)
                {
                    xProjected = LinearAlgebra.ClampToLine(v2, v3, xProjected);
                }

                else if (xBarycentric.y < 0.0)
                {
                    xProjected = LinearAlgebra.ClampToLine(v3, v1, xProjected);
                }

                else if (xBarycentric.z < 0.0)
                {
                    xProjected = LinearAlgebra.ClampToLine(v1, v2, xProjected);
                }

                float sqaredDistance = (xProjected - x).sqrMagnitude;

                if (!float.IsNaN(sqaredDistance) && sqaredDistance < bestDistanceSquared)
                {
                    bestDistanceSquared = sqaredDistance;
                    bestTriangle        = triangle;
                    bestNormal          = n;
                    bestPoint           = xProjected;
                }
            }

            Vector3 average = Vector3.zero;

            if (bestTriangle != -1)
            {
                if (m_smoothNormals)
                {
                    average = LinearAlgebra.BarycentricToWorld(
                        m_meshNormals[m_triangleList[bestTriangle + 0]],
                        m_meshNormals[m_triangleList[bestTriangle + 1]],
                        m_meshNormals[m_triangleList[bestTriangle + 2]],
                        LinearAlgebra.WorldToBarycentric3(
                            m_meshVertices[m_triangleList[bestTriangle + 0]],
                            m_meshVertices[m_triangleList[bestTriangle + 1]],
                            m_meshVertices[m_triangleList[bestTriangle + 2]],
                            bestPoint)
                        );
                }
                else
                {
                    average = m_meshNormals[m_triangleList[bestTriangle]];
                }



                average = LinearAlgebra.DivideComponents(average, m_scaleMesh);

                FlipNormal(m_flipX, m_flipY, m_flipZ, ref average);
                Swap(m_swapAxes, ref average);

                average = LinearAlgebra.MultiplyComponents(average, m_scaleVox);

                //Debug.Log("Computed normal for Coord" + tempdata.voxCoord.X + " " + tempdata.voxCoord.Y + " " + tempdata.voxCoord.Z + ": " + average.normalized.ToString() + " Triangle: " + bestTriangle);
            }

            for (int t = 0; t < tempdata.numVertices; t++)
            {
                outNormals[tempdata.vertexIndexOffsetBegin + t] = average;
            }
        }
        else
        {
            for (int t = 0; t < tempdata.numVertices; t++)
            {
                outNormals[tempdata.vertexIndexOffsetBegin + t] = inNormals[tempdata.vertexIndexOffsetBegin + t];
            }
        }
    }
 public void CanConvertArrayToDenseVector()
 {
     var array = new[] {0.0f, 1.0f, 2.0f, 3.0f, 4.0f};
     var vector = (DenseVector) array;
     Assert.IsInstanceOf(typeof (DenseVector), vector);
     CollectionAssert.AreEqual(array, array);
 }