示例#1
0
    public bool Equals(DynamicMatrix m)
    {
        if (m == null)
        {
            return(false);
        }

        if (this == m)
        {
            return(true);
        }

        if (numRows != m.numRows || numCols != m.numCols)
        {
            return(false);
        }

        for (int i = 0; i < numRows; i++)
        {
            for (int j = 0; j < numCols; j++)
            {
                if (get(i, j) != m.get(i, j))
                {
                    return(false);
                }
            }
        }

        return(true);
    }
示例#2
0
        public void RowsAndColumns_test()
        {
            var matrix = new DynamicMatrix <int>(5, 3);

            Assert.AreEqual(5, matrix.RowsCount);
            Assert.AreEqual(3, matrix.ColumnsCount);
            Assert.IsFalse(matrix.IsSquare);
        }
示例#3
0
 public DynamicMatrix(DynamicMatrix m)
 {
     createElement(m.getNumRows(), m.getNumCols());
     for (int row = 0; row < getNumRows(); row++)
     {
         for (int col = 0; col < getNumCols(); col++)
         {
             set(row, col, m.get(row, col));
         }
     }
 }
示例#4
0
    public IKSolver(int nJoints)
    {
        m_Jacobian    = new        DynamicMatrix(6, nJoints);
        m_farrError   = new  DynamicMatrix(6, 1);
        m_QDerivative = new     DynamicMatrix(nJoints, 1);
        m_arrAxis     = new  Vector3[nJoints];

        iTries             = 0;
        m_fTargetThreshold = 1.5f;
        m_iTryLimit        = 4;
    }
示例#5
0
    /// <summary>
    /// Updates the GridRepository's records of the entity's position on the grid, making changes as the entity's location changes.
    /// Entity tracking is primarily used for collision detection with abilities.
    /// </summary>
    private void UpdateTileTracking()
    {
        //Calculate the tile buffer parameters needed for the current physical radius of the entity
        int tileOffset = Mathf.FloorToInt(PhysicalRadius) + 1;
        int tileRange  = (2 * tileOffset) + 1;

        //Grab the tiles currently within the buffer around the entity
        CoordinatePair coordinates = GridRepository.Instance.GridCoordinatesFromPosition(transform.position);

        Tile[,] currentTiles = GridRepository.Instance.GetUnboundedGridSample(coordinates.x - tileOffset, coordinates.y - tileOffset, tileRange, tileRange);

        //Determine if the entity is not currently being tracked or is now within a different buffer than the one recorded in
        bool noTrackedTiles = null == trackingTiles;
        bool differentTiles = true;

        if (!noTrackedTiles)
        {
            differentTiles = !coordinates.Equals(previousTrackingLocation);
        }

        //If new tracking information needs to be recorded, adjust the tracking record for the tiles involved
        if (noTrackedTiles || differentTiles)
        {
            //if (!noTrackedTile) {
            //    foreach (Tile tile in trackingTiles)
            //        tile.Entities.Remove(gameObject);
            //}

            //TEMPORARY: Remove all tiles' tracking record for this entity.
            for (int i = 0; i < GridRepository.Instance.GridWidth; i++)
            {
                for (int j = 0; j < GridRepository.Instance.GridHeight; j++)
                {
                    GridRepository.Instance.GetTileAt(i, j).Entities.Remove(this);
                    //Debug.Log("REMOVING FROM " + GridRepository.Instance.GetTileAt(i, j).GridCoordinates + " for size of " + GridRepository.Instance.GetTileAt(i, j).Entities.Size + ": " + GridRepository.Instance.GetTileAt(i, j).Entities.ToString());
                }
            }

            //TEMPORARY: Add the tracking record for this entity to all tiles within the buffer
            foreach (Tile tile in currentTiles)
            {
                tile.Entities.AddUnique(this);
                //Debug.Log("Adding to " + tile.GridCoordinates + " for size of " + tile.Entities.Size + ": " + tile.Entities.ToString());
            }

            //TEMPORARY: Store the tiles tracking this entity as an instantiation of DynamicMatrix
            trackingTiles = new DynamicMatrix <Tile>(currentTiles);
        }

        //Record the coordinates for which this tracking information will remain valid
        previousTrackingLocation = coordinates;
    }
        GlowContainer IElementVisitor <ElementToGlowOptions, GlowContainer> .Visit(DynamicMatrix element, ElementToGlowOptions state)
        {
            var glow = MatrixToGlow(element, state);

            if (state.DirFieldMask == GlowFieldFlags.All)
            {
                glow.MatrixType          = GlowMatrixType.NToN;
                glow.ParametersLocation  = new GlowParametersLocation(element.ParametersSubIdentifier);
                glow.GainParameterNumber = 1;
            }

            return(glow);
        }
示例#7
0
    public DynamicMatrix multiply(float s)
    {
        DynamicMatrix ret = new DynamicMatrix(getNumRows(), getNumCols());

        for (int i = 0; i < getNumRows(); i++)
        {
            for (int j = 0; j < getNumCols(); j++)
            {
                ret.set(i, j, get(i, j) * s);
            }
        }
        return(ret);
    }
示例#8
0
    /**
     * @return the transposed matrix with dimensions getNumCols() x getNumRows()
     */
    public DynamicMatrix transpose()
    {
        DynamicMatrix ret = new DynamicMatrix(getNumCols(), getNumRows());

        for (int r = 0; r < getNumRows(); r++)
        {
            for (int c = 0; c < getNumCols(); c++)
            {
                ret.set(c, r, get(r, c));
            }
        }
        return(ret);
    }
示例#9
0
    public float dot(DynamicMatrix m)
    {
        if (getNumRows() != m.getNumRows() || getNumCols() != m.getNumCols())
        {
            throw new Exception("dimensions bad in dot()");
        }
        float sum = 0;

        for (int r = 0; r < getNumRows(); r++)
        {
            for (int c = 0; c < getNumCols(); c++)
            {
                sum += this.get(r, c) * m.get(r, c);
            }
        }

        return(sum);
    }
示例#10
0
    public DynamicMatrix subtractFrom(DynamicMatrix m)
    {
        if (getNumRows() != m.getNumRows() || getNumCols() != m.getNumCols())
        {
            throw new Exception("dimensions bad in addTo()");
        }
        DynamicMatrix ret = new DynamicMatrix(getNumRows(), getNumCols());

        for (int r = 0; r < getNumRows(); r++)
        {
            for (int c = 0; c < getNumCols(); c++)
            {
                ret.set(r, c, this.get(r, c) - m.get(r, c));
            }
        }

        return(ret);
    }
示例#11
0
        //TODO: unit-test
        /// <summary>
        ///     Creates a new instance of <see cref="DynamicMatrix{T}"/> which contains elements from
        ///     <see cref="IEnumerable{T}"/>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static DynamicMatrix <T> CreateDynamicMatrix <T>(this IEnumerable <IEnumerable <T> > source)
        {
            if (ReferenceEquals(source, null))
            {
                throw new ArgumentNullException(nameof(source));
            }

            var enumerables = source as IEnumerable <T>[] ?? source.ToArray();

            if (enumerables.Any(item => ReferenceEquals(item, null)))
            {
                throw new ArgumentNullException(nameof(source) + ": one of enumerables was null");
            }

            var columnsCount = enumerables[0]
                               .Count();

            if (enumerables.All(item => item.Count() == columnsCount))
            {
                throw new ArgumentException("Number of elements in inner enumerables should be equal");
            }

            var matrix = new DynamicMatrix <T>(enumerables.Length,
                                               enumerables[0]
                                               .Count());

            var rowIndex    = 0;
            var columnIndex = 0;

            foreach (var row in enumerables)
            {
                foreach (var item in row)
                {
                    matrix[rowIndex, columnIndex] = item;
                    columnIndex++;
                }

                rowIndex++;
                columnIndex = 0;
            }

            return(matrix);
        }
示例#12
0
        //TODO: unit-test
        /// <summary>
        ///     Converts a vanilla .NET matrix <see langword="T"/>[,] to <see cref="DynamicMatrix{T}"/>
        /// </summary>
        /// <typeparam name="T">ANY</typeparam>
        /// <param name="matrix">Initial matrix to convert</param>
        /// <returns><see cref="DynamicMatrix{T}"/>, made on base <paramref name="matrix"/></returns>
        public static DynamicMatrix <T> ToDynamicMatrix <T>(this T[,] matrix)
        {
            if (matrix == null)
            {
                throw new ArgumentNullException(nameof(matrix));
            }

            var newMatrix = new DynamicMatrix <T>(matrix.GetLength(0), matrix.GetLength(1));

            for (var i = 0; i < newMatrix.RowsCount; i++)
            {
                for (var j = 0; j < newMatrix.ColumnsCount; j++)
                {
                    newMatrix[i, j] = matrix[i, j];
                }
            }

            return(newMatrix);
        }
示例#13
0
    public DynamicMatrix multiply(DynamicMatrix m)
    {
        if (getNumCols() != m.getNumRows())
        {
            throw new Exception(this.getDimension() + " * " + m.getDimension() + " dimensions bad in multiply()");
        }

        DynamicMatrix ret = new DynamicMatrix(getNumRows(), m.getNumCols());

        for (int r = 0; r < getNumRows(); r++)
        {
            for (int c = 0; c < m.getNumCols(); c++)
            {
                for (int k = 0; k < getNumCols(); k++)
                {
                    ret.set(r, c, ret.get(r, c) + (this.get(r, k) * m.get(k, c)));
                }
            }
        }

        return(ret);
    }
示例#14
0
                public Cursor(DynamicMatrix owner)
                {
                    _owner    = owner ?? throw new ArgumentNullException(nameof(owner));
                    _rowIndex = -1;

                    var getters = new List <Delegate>();

                    for (var i = 0; i < _owner.Schema.Count; i++)
                    {
                        var column = _owner.Schema[i];
                        if (column.Type == NumberDataViewType.Single)
                        {
                            getters.Add(new ValueGetter <float>((ref float value) =>
                            {
                                value = (float)_owner._data[_rowIndex][column.Index];
                            }));
                        }
                        else if (column.Type == DateTimeDataViewType.Instance)
                        {
                            getters.Add(new ValueGetter <DateTime>((ref DateTime value) =>
                            {
                                value = (DateTime)_owner._data[_rowIndex][column.Index];
                            }));
                        }
                        else if (column.Type == TextDataViewType.Instance)
                        {
                            getters.Add(new ValueGetter <ReadOnlyMemory <char> >((ref ReadOnlyMemory <char> value) =>
                            {
                                value = (ReadOnlyMemory <char>)_owner._data[_rowIndex][column.Index];
                            }));
                        }
                        else
                        {
                            throw new Exception($"Unsupported type of column detected: {column.Type}");
                        }
                    }
                    _getters = getters.ToArray();
                }
示例#15
0
        //TODO: unit-test
        /// <summary>
        ///     Creates a new instance of <see cref="DynamicMatrix{T}"/> from <see cref="JuggedMatrix{T}"/>
        /// </summary>
        /// <typeparam name="T">ANY</typeparam>
        /// <param name="juggedMatrix">Initial matrix</param>
        /// <returns>A new instance of <see cref="IMatrix{T}"/></returns>
        public static DynamicMatrix <T> ToDynamicMatrix <T>(this JuggedMatrix <T> juggedMatrix)
        {
            var matrix = new DynamicMatrix <T>(juggedMatrix.RowsCount,
                                               juggedMatrix.CountOnEachRow()
                                               .Max());

            for (var i = 0; i < juggedMatrix.RowsCount; i++)
            {
                for (var j = 0; j < matrix.ColumnsCount; j++)
                {
                    if (juggedMatrix.ElementsInRow(i) < matrix.ColumnsCount)
                    {
                        matrix[i, j] = juggedMatrix[i, j];
                    }
                    else
                    {
                        matrix[i, j] = default;
                    }
                }
            }

            return(matrix);
        }
示例#16
0
        public static void DoClustering(MLContext ctx, IDataView data)
        {
            if (ctx is null)
            {
                throw new ArgumentNullException(nameof(ctx));
            }
            if (data is null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            // Prepare to make a column which contains a vector made from "{sepal|petal}x{length|width}"
            var featuresColumnName = "Features";
            var inputColumnNames   = data.Schema.Take(data.Schema.Count - 1).Select(s => s.Name).ToArray();

            // Train
            var estimatorChain = ctx.Transforms
                                 .Concatenate(featuresColumnName, inputColumnNames)        // Make a feature vector column
                                 .Append(ctx.Transforms.SelectColumns(featuresColumnName)) // Keep only the feature vector column
                                 .Append(ctx.Clustering.Trainers.KMeans(featuresColumnName, numberOfClusters: 3));
            var transformerChain = estimatorChain.Fit(data);

            // Get output schema by examining the transformation pipeline
            var builder = new DataViewSchema.Builder();

            builder.AddColumn(featuresColumnName, new VectorDataViewType(NumberDataViewType.Single, inputColumnNames.Length));
            var outputSchema = transformerChain.GetOutputSchema(data.Schema);

            Console.WriteLine("[Transformation]");
            Console.WriteLine("    From:");
            foreach (var column in data.Schema)
            {
                Console.WriteLine($"        {column.Name} <{column.Type} ({column.Type.RawType})>");
            }
            Console.WriteLine("    To:");
            foreach (var column in outputSchema)
            {
                Console.WriteLine($"        {column.Name} <{column.Type} ({column.Type.RawType})> ");
            }
            Console.WriteLine();

            // Extract model parameters
            int k;
            var centroids  = new VBuffer <float> [3];
            var parameters = transformerChain.LastTransformer.Model;

            parameters.GetClusterCentroids(ref centroids, out k);
            Console.WriteLine("[Model Parameters]");
            Console.WriteLine($"    k: {k}");
            Console.WriteLine($"    centroids:");
            foreach (var centroid in centroids)
            {
                Console.WriteLine($"        ({string.Join(", ", centroid.DenseValues())})");
            }
            Console.WriteLine();

            // Predict a new sample
            var newSamples = new DynamicMatrix(new object[][]
            {
                new object[] { 5.1f, 3.5f, 1.4f, 0.2f },
            },
                                               inputColumnNames);
            var prediction = transformerChain.Transform(newSamples);

            using (var cursor = prediction.GetRowCursor(prediction.Schema))
            {
                var getFeatures       = cursor.GetGetter <VBuffer <float> >(prediction.Schema[featuresColumnName]);
                var getPredictedLabel = cursor.GetGetter <UInt32>(prediction.Schema["PredictedLabel"]);
                var getScore          = cursor.GetGetter <VBuffer <float> >(prediction.Schema["Score"]);
                Console.WriteLine("[Prediction]");
                while (cursor.MoveNext())
                {
                    var    features       = new VBuffer <float>();
                    UInt32 predictedLabel = 0;
                    var    score          = new VBuffer <float>();

                    getFeatures(ref features);
                    getPredictedLabel(ref predictedLabel);
                    getScore(ref score);
                    Console.WriteLine("    Input Feature:   {0}", string.Join(", ", features.DenseValues()));
                    Console.WriteLine("    Predicted Label: {0}", predictedLabel);
                    Console.WriteLine("    Score:           {0}", string.Join(", ", score.DenseValues()));
                }
                Console.WriteLine();
            }
        }
示例#17
0
 public ErDiagram(string name, IEnumerable<ErEssence> essences, DynamicMatrix<ErRelationship> diagramGraf)
 {
     Name = name;
     Essences = new List<ErEssence>(essences);
     DiagramGraf = diagramGraf.Clone();
 }
示例#18
0
 public ErDiagram()
 {
     Essences = new List<ErEssence>();
     DiagramGraf = new DynamicMatrix<ErRelationship>();
 }
示例#19
0
 //MONOBEHAVIOUR Start
 void Start()
 {
     trackingTiles = null;
 }
示例#20
0
    /**
     * Calculates the matrix's Moore-Penrose pseudoinverse
     * @return an MxN (row x col) matrix which is the matrix's pseudoinverse.
     */
    public DynamicMatrix pseudoInverse()
    {
        int r, c;

        int           k = 1;
        DynamicMatrix ak = new DynamicMatrix(getNumRows(), 1);
        DynamicMatrix dk, ck, bk;

        DynamicMatrix R_plus;

        for (r = 0; r < getNumRows(); r++)
        {
            ak.set(r, 0, this.get(r, 0));
        }

        if (!ak.EqualsZero())
        {
//		if (!ak.equals(0.0)) {
            R_plus = ak.transpose().multiply(1.0f / (ak.dot(ak)));
        }
        else
        {
            R_plus = new DynamicMatrix(1, getNumCols());
        }

        while (k < this.getNumCols())
        {
            for (r = 0; r < getNumRows(); r++)
            {
                ak.set(r, 0, this.get(r, k));
            }

            dk = R_plus.multiply(ak);
            DynamicMatrix T = new DynamicMatrix(getNumRows(), k);
            for (r = 0; r < getNumRows(); r++)
            {
                for (c = 0; c < k; c++)
                {
                    T.set(r, c, this.get(r, c));
                }
            }

            ck = ak.subtractFrom(T.multiply(dk));

            if (!ck.EqualsZero())
            {
//			if (!ck.equals(0.0)) {
                bk = ck.transpose().multiply(1.0f / (ck.dot(ck)));
            }
            else
            {
                bk = dk.transpose().multiply(1.0f / (1.0f + dk.dot(dk)))
                     .multiply(R_plus);
            }

            DynamicMatrix N = R_plus.subtractFrom(dk.multiply(bk));
            R_plus = new DynamicMatrix(N.getNumRows() + 1, N.getNumCols());

            for (r = 0; r < N.getNumRows(); r++)
            {
                for (c = 0; c < N.getNumCols(); c++)
                {
                    R_plus.set(r, c, N.get(r, c));
                }
            }
            for (c = 0; c < N.getNumCols(); c++)
            {
                R_plus.set(R_plus.getNumRows() - 1, c, bk.get(0, c));
            }

            k++;
        }
        return(R_plus);
    }