Ejemplo n.º 1
0
        public override RectCallback getRectCallback(RenderBox referenceBox)
        {
            return(() => {
                RenderObject cell = referenceBox;
                AbstractNodeMixinDiagnosticableTree table = cell.parent;
                Matrix4 transform = Matrix4.identity();
                while (table is RenderObject && !(table is RenderTable))
                {
                    RenderObject parentBox = table as RenderObject;
                    parentBox.applyPaintTransform(cell, transform);
                    D.assert(table == cell.parent);
                    cell = parentBox;
                    table = table.parent;
                }

                if (table is RenderTable renderTable)
                {
                    TableCellParentData cellParentData = cell.parentData as TableCellParentData;
                    Rect rect = renderTable.getRowBox(cellParentData.y);
                    // The rect is in the table's coordinate space. We need to change it to the
                    // TableRowInkWell's coordinate space.
                    renderTable.applyPaintTransform(cell, transform);
                    Offset offset = MatrixUtils.getAsTranslation(transform);
                    if (offset != null)
                    {
                        return rect.shift(-offset);
                    }
                }

                return Rect.zero;
            }
                   );
        }
Ejemplo n.º 2
0
        private bool InternalOverlapBounds(int index1, int index2, float lerpVal, ref Bounds bounds)
        {
            var bounds1 = Snapshots[index1].ProximityBounds;
            var bounds2 = Snapshots[index2].ProximityBounds;

            return(MatrixUtils.LerpBounds(ref bounds1, ref bounds2, lerpVal).Intersects(bounds));
        }
Ejemplo n.º 3
0
        ///
        protected override void AddUser(int user_id)
        {
            base.AddUser(user_id);

            user_factors.AddRows(user_id + 1);
            MatrixUtils.RowInitNormal(user_factors, InitMean, InitStdev, user_id);
        }
Ejemplo n.º 4
0
 public override void ReadFromFile(MemoryStream stream, bool isBigEndian)
 {
     base.ReadFromFile(stream, isBigEndian);
     Unk05     = stream.ReadByte8();
     Unk06     = stream.ReadInt32(isBigEndian);
     Unk07     = stream.ReadInt32(isBigEndian);
     Transform = MatrixUtils.ReadFromFile(stream, isBigEndian);
     Unk09     = stream.ReadInt32(isBigEndian);
     Unk10     = stream.ReadInt32(isBigEndian);
     Unk08     = new float[10];
     for (int i = 0; i < 10; i++)
     {
         Unk08[i] = stream.ReadSingle(isBigEndian);
     }
     Unk11  = stream.ReadInt32(isBigEndian);
     Unk12  = stream.ReadInt32(isBigEndian);
     Name33 = stream.ReadString16(isBigEndian);
     Unk14  = new float[9];
     for (int i = 0; i < 9; i++)
     {
         Unk14[i] = stream.ReadSingle(isBigEndian);
     }
     Unk15 = stream.ReadByte8();
     Unk16 = new float[12];
     for (int i = 0; i < 12; i++)
     {
         Unk16[i] = stream.ReadSingle(isBigEndian);
     }
 }
Ejemplo n.º 5
0
        /// <summary>Iterate once over rating data and adjust corresponding factors (stochastic gradient descent)</summary>
        /// <param name="rating_indices">a list of indices pointing to the ratings to iterate over</param>
        /// <param name="update_user">true if user factors to be updated</param>
        /// <param name="update_item">true if item factors to be updated</param>
        protected virtual void Iterate(IList <int> rating_indices, bool update_user, bool update_item)
        {
            foreach (int index in rating_indices)
            {
                int u = ratings.Users[index];
                int i = ratings.Items[index];

                double p   = Predict(u, i, false);
                double err = ratings[index] - p;

                // Adjust factors
                for (int f = 0; f < NumFactors; f++)
                {
                    double u_f = user_factors[u, f];
                    double i_f = item_factors[i, f];

                    // compute factor updates
                    double delta_u = err * i_f - Regularization * u_f;
                    double delta_i = err * u_f - Regularization * i_f;

                    // if necessary, apply updates
                    if (update_user)
                    {
                        MatrixUtils.Inc(user_factors, u, f, LearnRate * delta_u);
                    }
                    if (update_item)
                    {
                        MatrixUtils.Inc(item_factors, i, f, LearnRate * delta_i);
                    }
                }
            }
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            //string path = @"C:\Users\tom.swedlund\Documents\GitHub\calibration\";
            //string path = @"c:\Users\tom\Documents\GitHub\calibration\";
            string        path  = "C:\\Users\\visha\\Downloads\\calibration-master1\\calibration-master\\";
            Matrix        image = ImageUtils.LoadGrayscale(Path.Combine(path, "corner.png"));
            Matrix        harris;
            List <Vector> corners = ImageUtils.HarrisCornerDetector(image, out harris);

            foreach (Vector corner in corners)
            {
                image[(int)corner[0], (int)corner[1]] = 1;
            }
            ImageUtils.SaveAsImage(image, Path.Combine(path, "overlay.png"));

            Matrix shift = new Matrix(harris.Height, harris.Width, MatrixUtils.MaxNeg(harris));

            harris += shift;
            harris /= MatrixUtils.Max(harris);
            ImageUtils.SaveAsImage(harris, Path.Combine(path, "harris.png"));

            Matrix cornerIm = new Matrix(harris.Height, harris.Width);

            foreach (Vector pt in corners)
            {
                cornerIm[(int)pt[0], (int)pt[1]] = 1;
            }
            ImageUtils.SaveAsImage(cornerIm, Path.Combine(path, "corner.png"));
        }
Ejemplo n.º 7
0
    // Creates a GameObject representing a given BVHJoint and recursively creates GameObjects for it's child joints
    GameObject CreateJoint(BVHJoint joint, Vector3 parentPosition)
    {
        joint.gameObject      = new GameObject();
        joint.gameObject.name = joint.name;

        var translateMatrix = MatrixUtils.Translate(parentPosition + joint.offset);

        if (joint == data.rootJoint)
        {
            Debug.Log(translateMatrix + " " + joint.offset);
        }
        var scaleFactor   = joint.name == "Head" ? new Vector3(8, 8, 8) : new Vector3(2, 2, 2);
        var scalingMatrix = MatrixUtils.Scale(scaleFactor);


        var newSphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);

        newSphere.transform.parent = joint.gameObject.transform;

        MatrixUtils.ApplyTransform(newSphere, scalingMatrix);
        MatrixUtils.ApplyTransform(joint.gameObject, translateMatrix);

        foreach (var child in joint.children)
        {
            var childJoint = CreateJoint(child, joint.gameObject.transform.position);
            var cylinder   = CreateCylinderBetweenPoints(childJoint.gameObject.transform.position,
                                                         joint.gameObject.transform.position, .5f);
            cylinder.transform.parent = joint.gameObject.transform;
        }

        return(joint.gameObject);
    }
Ejemplo n.º 8
0
    // Transforms BVHJoint according to the keyframe channel data, and recursively transforms its children
    private void TransformJoint(BVHJoint joint, Matrix4x4 parentTransform, float[] keyframe)
    {
        Matrix4x4 localRMatrix = Matrix4x4.identity;

        if (!joint.isEndSite)
        {
            Matrix4x4[] rMatrices = new Matrix4x4[3];
            rMatrices[joint.rotationOrder.x] = MatrixUtils.RotateX(keyframe[joint.rotationChannels.x]);
            rMatrices[joint.rotationOrder.y] = MatrixUtils.RotateY(keyframe[joint.rotationChannels.y]);
            rMatrices[joint.rotationOrder.z] = MatrixUtils.RotateZ(keyframe[joint.rotationChannels.z]);
            localRMatrix = rMatrices[0] * rMatrices[1] * rMatrices[2];
        }

        Matrix4x4 localTMatrix = MatrixUtils.Translate(joint.offset);
        Matrix4x4 localTRS     = localTMatrix * localRMatrix;

        Matrix4x4 globalTransform = parentTransform * localTRS;

        MatrixUtils.ApplyTransform(joint.gameObject, globalTransform);

        foreach (BVHJoint childJoint in joint.children)
        {
            TransformJoint(childJoint, globalTransform, keyframe);
        }
    }
Ejemplo n.º 9
0
    // Returns a Matrix4x4 representing a rotation aligning the up direction of an object with the given v
    Matrix4x4 RotateTowardsVector(Vector3 v)
    {
        // Your code here
        Vector3 normV = v.normalized;

        Debug.Log("normV is:");
        Debug.Log(normV);
        float     thetaX = 90 - Mathf.Atan2(normV.y, normV.z) * Mathf.Rad2Deg;
        Matrix4x4 rX     = MatrixUtils.RotateX(-thetaX);
        Vector3   rxV    = rX * normV;

        Debug.Log("The z coordinate should be 0:");
        Debug.Log(rxV);
        float     thetaZ = 90 - Mathf.Atan2(rxV.y, rxV.x) * Mathf.Rad2Deg;
        Matrix4x4 rZ     = MatrixUtils.RotateZ(thetaZ);
        Vector3   rzrxV  = rZ * rxV;

        Debug.Log("This vector should be (0,1,0):");
        Debug.Log(rzrxV);
        Matrix4x4 rXinv  = rX.inverse;
        Matrix4x4 rZinv  = rZ.inverse;
        Matrix4x4 rXIrZI = rXinv * rZinv;

        return(rXIrZI);
    }
Ejemplo n.º 10
0
    // Creates a GameObject representing a given BVHJoint and recursively creates GameObjects for it's child joints
    GameObject CreateJoint(BVHJoint joint, Vector3 parentPosition)
    {
        joint.gameObject = new GameObject(joint.name);
        GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);

        sphere.transform.parent = joint.gameObject.transform;
        Vector3 scale;

        if (joint.name == "Head")
        {
            scale = new Vector3(8, 8, 8);
        }
        else
        {
            scale = new Vector3(2, 2, 2);
        }
        MatrixUtils.ApplyTransform(sphere, MatrixUtils.Scale(scale));
        Matrix4x4 t = MatrixUtils.Translate(parentPosition + joint.offset);

        MatrixUtils.ApplyTransform(joint.gameObject, t);

        foreach (BVHJoint child in joint.children)
        {
            GameObject childObject = CreateJoint(child, joint.gameObject.transform.position);
            GameObject bone        = CreateCylinderBetweenPoints(joint.gameObject.transform.position,
                                                                 childObject.transform.position, 0.5f);
            bone.transform.parent = joint.gameObject.transform;
        }


        return(joint.gameObject);
    }
Ejemplo n.º 11
0
    // Transforms BVHJoint according to the keyframe channel data, and recursively transforms its children
    private void TransformJoint(BVHJoint joint, Matrix4x4 parentTransform, float[] keyframe)
    {
        Matrix4x4 t, m;

        if (joint == data.rootJoint)
        {
            Vector3 position = new Vector3(keyframe[joint.positionChannels[0]], keyframe[joint.positionChannels[1]],
                                           keyframe[joint.positionChannels[2]]);
            t = MatrixUtils.Translate(position);
        }
        else
        {
            t = MatrixUtils.Translate(joint.offset);
        }

        if (!joint.isEndSite)
        {
            Matrix4x4[] r_array = new Matrix4x4[3];
            r_array[joint.rotationOrder[0]] = MatrixUtils.RotateX(keyframe[joint.rotationChannels[0]]);
            r_array[joint.rotationOrder[1]] = MatrixUtils.RotateY(keyframe[joint.rotationChannels[1]]);
            r_array[joint.rotationOrder[2]] = MatrixUtils.RotateZ(keyframe[joint.rotationChannels[2]]);
            Matrix4x4 r = r_array[0] * r_array[1] * r_array[2];
            m = parentTransform * t * r;
        }
        else
        {
            m = parentTransform * t;
        }

        MatrixUtils.ApplyTransform(joint.gameObject, m);
        foreach (BVHJoint child in joint.children)
        {
            TransformJoint(child, m, keyframe);
        }
    }
        public List <SimulationResult> Simulate()
        {
            LogMessageDelegate?.Invoke($"Solving the equation...");

            CalculateConstantValues();
            var results = new List <SimulationResult>();

            LogMessageDelegate?.Invoke($"Simulating the process");

            for (double i = StepTime; i <= SimulationTime; i += StepTime)
            {
                SearchingTemperatures = MatrixUtils.MultiplyMatrices(HMatrixInverted, NewPVector);
                var minMax = SearchingTemperatures.FindMinAndMaxValue();
                var min    = minMax.Item1;
                var max    = minMax.Item2;
                LogMessageDelegate?.Invoke($"StepTime = {i}; Min temp = {min}; Max temp = {max}");
                results.Add(new SimulationResult {
                    Values = SearchingTemperatures.GetColumn(0),
                    Max    = max,
                    Min    = min,
                    Tau    = i
                });
                CalculateNewP(SearchingTemperatures);
            }

            return(results);
        }
Ejemplo n.º 13
0
        /**
         * Returns the Hessenberg matrix H of the transform.
         *
         * @return the H matrix
         */
        public RealMatrix getH()
        {
            if (cachedH == null)
            {
                int        m = householderVectors.Length;
                double[][] h = Java.CreateArray <double[][]>(m, m);// new double[m][m];
                for (int i = 0; i < m; ++i)
                {
                    if (i > 0)
                    {
                        // copy the entry of the lower sub-diagonal
                        h[i][i - 1] = householderVectors[i][i - 1];
                    }

                    // copy upper triangular part of the matrix
                    for (int j = i; j < m; ++j)
                    {
                        h[i][j] = householderVectors[i][j];
                    }
                }
                cachedH = MatrixUtils.CreateRealMatrix(h);
            }

            // return the cached matrix
            return(cachedH);
        }
Ejemplo n.º 14
0
        private void CalculateBoundaryConditions(double alpha, double ambientTemperature)
        {
            for (int i = 0; i < ELEMENT_NODES_COUNT; i++)
            {
                var current = Nodes[i];
                var next    = Nodes[(i + 1) % ELEMENT_NODES_COUNT];
                if (current.IsBoundary && next.IsBoundary)
                {
                    //boundary edge
                    int edgeIndex               = i;
                    var jacobianDet             = CalculateEdgeJacobian1DDeterminal(edgeIndex);
                    var pointsProjectedOntoEdge = UniversalElement.GetIntegrationPointsProjectedOntoEdge(edgeIndex);
                    for (int j = 0; j < pointsProjectedOntoEdge.Length; j++)
                    {
                        var point    = pointsProjectedOntoEdge[j];
                        var NValues  = UniversalElement.CalculateNValues(point);
                        var NValuesT = NValues.Transpose();

                        // [Hbc]
                        var NxN        = MatrixUtils.MultiplyMatrices(NValues.ToMatrix(), NValuesT);
                        var factor     = point.WeightKsi * point.WeightEta * jacobianDet * alpha;
                        var HBcPartial = MatrixUtils.MultiplyMatrix(NxN, factor);
                        HBcLocalMatrix = MatrixUtils.AddMatrices(HBcLocalMatrix, HBcPartial);

                        // {P}
                        var vectPFactor    = point.WeightKsi * point.WeightEta * jacobianDet * alpha * ambientTemperature;
                        var vectorPPartial = MatrixUtils.MultiplyMatrix(NValues.ToMatrix(), vectPFactor);
                        PVector = MatrixUtils.AddMatrices(PVector, vectorPPartial);
                    }
                }
            }
        }
Ejemplo n.º 15
0
            /**
             * Get the inverse of the decomposed matrix.
             *
             * @return the inverse matrix.
             * @throws SingularMatrixException if the decomposed matrix is singular.
             */
            public RealMatrix getInverse()
            {
                if (!isNonSingular())
                {
                    throw new Exception("SingularMatrixException");
                }

                int m = realEigenvalues.Length;

                double[][] invData = Java.CreateArray <double[][]>(m, m);// new double[m][m];

                for (int i = 0; i < m; ++i)
                {
                    double[] invI = invData[i];
                    for (int j = 0; j < m; ++j)
                    {
                        double invIJ = 0;
                        for (int k = 0; k < m; ++k)
                        {
                            double[] vK = eigenvectors[k].getDataRef();
                            invIJ += vK[i] * vK[j] / realEigenvalues[k];
                        }
                        invI[j] = invIJ;
                    }
                }
                return(MatrixUtils.CreateRealMatrix(invData));
            }
Ejemplo n.º 16
0
        public void GetRandomMatrixOfEquitableRepeatedValuesWithBadSize()
        {
            var list = Enumerable.Range(0, 3).ToArray();

            Assert.Throws <ArgumentOutOfRangeException>(() =>
                                                        MatrixUtils.GetRandomMatrixOfEquitableRepeatedValues(-1, list));
        }
Ejemplo n.º 17
0
        ///
        public override void IterateMapping()
        {
            // stochastic gradient descent
            int user_id = SampleUserWithAttributes();

            double[] est_factors = MapUserToLatentFactorSpace(user_attributes[user_id]);

            for (int j = 0; j < num_factors; j++)
            {
                // TODO do we need an absolute term here???
                double diff = est_factors[j] - user_factors[user_id, j];
                if (diff > 0)
                {
                    foreach (int attribute in user_attributes[user_id])
                    {
                        double w     = attribute_to_factor[attribute, j];
                        double deriv = diff * w + reg_mapping * w;
                        MatrixUtils.Inc(attribute_to_factor, attribute, j, learn_rate_mapping * -deriv);
                    }
                    // bias term
                    double w_bias     = attribute_to_factor[NumUserAttributes, j];
                    double deriv_bias = diff * w_bias + reg_mapping * w_bias;
                    MatrixUtils.Inc(attribute_to_factor, NumUserAttributes, j, learn_rate_mapping * -deriv_bias);
                }
            }
        }
Ejemplo n.º 18
0
        // Serialization

        /// <summary>
        /// Serialize the message.
        /// </summary>
        /// <param name="cout">Cout.</param>
        public override void Serialize(IBinaryWriter cout)
        {
            base.Serialize(cout);

            var indices = MatrixUtils.IndicesOf(Value);

            if (indices != null)
            {
                var namelist = indices.NameList;
                cout.WriteInt32(namelist.Length);
                for (int i = 0; i < namelist.Length; i++)
                {
                    cout.WriteString(namelist[i], Encoding.ASCII);
                }
            }
            else
            {
                cout.WriteInt32(0);
            }

            cout.WriteInt32(Value.Count);
            for (int i = 0; i < Value.Count; i++)
            {
                cout.WriteDouble(Value[i]);
            }
        }
Ejemplo n.º 19
0
        /// <summary>Iterate once over rating data (stochastic gradient descent)</summary>
        /// <remarks></remarks>
        public virtual void Iterate()
        {
            foreach (int index in ratings.RandomIndex)
            {
                int u = ratings.Users[index];
                int i = ratings.Items[index];

                double p   = Predict(u, i);
                double err = ratings[index] - p;

                // Adjust factors
                for (int f = 0; f < NumFactors; f++)
                {
                    double u_f = user_factors[u, f];
                    double i_f = item_factors[i, f];

                    // compute factor updates
                    double delta_u = err * i_f - Regularization * u_f;
                    double delta_i = err * u_f - Regularization * i_f;

                    // apply updates
                    MatrixUtils.Inc(user_factors, u, f, LearnRate * delta_u);
                    MatrixUtils.Inc(item_factors, i, f, LearnRate * delta_i);
                }
            }
        }
Ejemplo n.º 20
0
        public virtual void Validate()
        {
            if (Model.A == null ||
                Model.B == null ||
                Model.Pi == null ||
                Model.F == null)
            {
                _errors.Add("Some of the general model parameters are not set");
                return;
            }
            if (Model.N != Model.A.GetLength(1) ||
                Model.N != Model.Pi.Length ||
                Model.N != Model.B.GetLength(1) ||
                Model.N != Model.F.GetLength(1))
            {
                _errors.Add("Inconsistent matrices and arrays dimensions");
                return;
            }

            if (!MatrixUtils.IsTwiceStochastic(Model.A))
            {
                _errors.Add("Matrix A should be twice stochastic");
            }

            if (!MatrixUtils.IsStochasticByRows(Model.B))
            {
                _errors.Add("Matrix B should be stochastic by rows");
            }

            if (!MatrixUtils.IsStochasticByRows(Model.F))
            {
                _errors.Add("Matrix F should be stochastic by rows");
            }
        }
        private Matrix4x4 buildTransformationMatrix()
        {
            Matrix4x4 translationMatrix = MatrixUtils.TransformationMatrixFromTranslation(translation);
            Matrix4x4 rotationMatrix    = MatrixUtils.TransformationMatrixFromQuaternion(rotation);

            return(translationMatrix * rotationMatrix);
        }
        ///
        public override void LearnAttributeToFactorMapping()
        {
            this.attribute_to_factor = new Matrix <double>(NumItemAttributes, num_hidden_factors);            // TODO change name
            this.output_layer        = new Matrix <double>(num_hidden_factors, num_factors);

            Console.Error.WriteLine("BPR-MULTILAYER-MAP training");
            Console.Error.WriteLine("num_item_attributes=" + NumItemAttributes);
            Console.Error.WriteLine("num_hidden_factors=" + num_hidden_factors);

            MatrixUtils.InitNormal(attribute_to_factor, InitMean, InitStdev);
            MatrixUtils.InitNormal(output_layer, InitMean, InitStdev);

            //Console.Error.WriteLine("iteration -1 fit {0,0:0.#####} ", ComputeFit());
            for (int i = 0; i < num_iter_mapping; i++)
            {
                IterateMapping();
                //ComputeMappingFit();
                //Console.Error.WriteLine("iteration {0} fit {1,0:0.#####} ", i, ComputeFit());
            }

            // set item_factors to the mapped ones:                     // TODO: put into a separate method
            for (int item_id = 0; item_id < MaxItemID + 1; item_id++)
            {
                // only map factors for items where we know attributes
                if (item_attributes[item_id].Count == 0)
                {
                    continue;
                }

                double[] est_factors = MapToLatentFactorSpace(item_id);

                item_factors.SetRow(item_id, est_factors);
            }
        }
Ejemplo n.º 23
0
        public void ReadFromFile(BinaryReader reader)
        {
            frameRef    = reader.ReadUInt64();
            unk_byte    = reader.ReadByte();
            colType     = (CollisionTypes)reader.ReadByte();
            idHash      = reader.ReadUInt64();
            colMaterial = reader.ReadInt16();
            Matrix      = MatrixUtils.ReadFromFile(reader);
            unkByte     = reader.ReadByte();

            if (colType == CollisionTypes.Box)
            {
                collision = new CollisionBox(reader);
            }
            else if (colType == CollisionTypes.Sphere)
            {
                collision = new CollisionSphere(reader);
            }
            else if (colType == CollisionTypes.Capsule)
            {
                collision = new CollisionCapsule(reader);
            }
            else if (colType == CollisionTypes.Convex)
            {
                collision = new CollisionConvex(reader);
            }
            else
            {
                Log.WriteLine("Failed to parse collision type " + colType, LoggingTypes.WARNING, LogCategoryTypes.FUNCTION);
            }
        }
Ejemplo n.º 24
0
    public void Execute(int colB)
    {
        unsafe
        {
            int sz = bs * bs * 4;

            ;           float *blockA = (float *)UnsafeUtility.Malloc(sz, 4, Allocator.TempJob);
            float *            blockB = (float *)UnsafeUtility.Malloc(sz, 4, Allocator.TempJob);
            float *            blockC = (float *)UnsafeUtility.Malloc(sz, 4, Allocator.TempJob);

            for (int rowA = 0; rowA < AN; rowA += bs)
            {
                //for (int colB = 0; colB < BM; colB += bs)
                {
                    for (int l = 0; l < AM; l += bs)
                    {
                        MatrixUtils.CopyBlockWithPadding(A, rowA, AN, l, AM, blockA, bs, transposeA);
                        MatrixUtils.CopyBlockWithPadding(B, l, BN, colB * bs, BM, blockB, bs, transposeB);
                        MatrixUtils.CopyBlockWithPadding(C, rowA, CN, colB * bs, CM, blockC, bs);

                        MatrixUtils.MultiplyBlockUnroll8xhPadded(blockA, blockB, blockC, bs);

                        MatrixUtils.CopyBlockWithPadding(blockC, C, rowA, CN, colB * bs, CM, bs);
                    }
                }
            }

            UnsafeUtility.Free(blockA, Allocator.TempJob);
            UnsafeUtility.Free(blockB, Allocator.TempJob);
            UnsafeUtility.Free(blockC, Allocator.TempJob);
        }
    }
Ejemplo n.º 25
0
        public static void DisplayVectors(List <TagVector <T> > tagVectors, int h, int w)
        {
            Console.WriteLine();
            var matrix = ConvertVectorsToMatrix(tagVectors, h, w);

            MatrixUtils.DisplayMatrix(matrix);
        }
Ejemplo n.º 26
0
        public void MatrixConsoleOutputShouldBeAsExpectedWhenAValidMatrixIsCreated()
        {
            using (StringWriter testStringWriter = new StringWriter())
            {
                Console.SetOut(testStringWriter);
                RotatingWalkInMatrix.Main();
                Matrix testMatrix  = new Matrix(6);
                var    matrixUtils = new MatrixUtils(testMatrix, PossibleDirections.AllDirections, startingCell);
                matrixUtils.FillMatrix();
                StringBuilder expected = new StringBuilder();
                for (int i = 0; i < testMatrix.Field.GetLength(0); i++)
                {
                    for (int j = 0; j < testMatrix.Field.GetLength(0); j++)
                    {
                        expected.AppendFormat("{0,3}", testMatrix.Field[i, j]);
                    }

                    expected.Append(Environment.NewLine);
                }
                expected.Append(Environment.NewLine);
                string expectedString = expected.ToString();

                Assert.AreEqual(expectedString, testStringWriter.ToString());
            }
        }
Ejemplo n.º 27
0
        public void TakeSnapshot(int frame, int index)
        {
            if (frame > CurrentSnapshotFrame)
            {
                CurrentSnapshotFrame = frame;
                var snapShot = Snapshots[index];

                if (frame % _snapshotInterval == 0)
                {
                    snapShot.Real = true;
                    var ltw = transform.localToWorldMatrix;
                    snapShot.ProximityBounds = MatrixUtils.LocalToWorld(ref _bounds, ref ltw);

                    //grab LTW for body parts
                    for (int hitboxIndex = 0; hitboxIndex < _transforms.Length; hitboxIndex++)
                    {
                        snapShot.LocalToWorld[hitboxIndex] = _transforms[hitboxIndex].localToWorldMatrix;
                    }
                }
                else
                {
                    snapShot.Real = false;
                }
            }
            else
            {
                Debug.LogError($"Requesting snapshot frame <= current snapshot frame: {frame}, Current: {CurrentSnapshotFrame}", this);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Perform one iteration of the mapping learning process
        /// </summary>
        public override void IterateMapping()
        {
            _MapToLatentFactorSpace = __MapToLatentFactorSpace;             // make sure we don't memoize during training

            // stochastic gradient descent
            int item_id = SampleItem();

            double[] est_factors = MapToLatentFactorSpace(item_id);

            for (int j = 0; j < num_factors; j++)
            {
                // TODO do we need an absolute term here???
                double diff = est_factors[j] - item_factors[item_id, j];
                if (diff > 0)
                {
                    foreach (int attribute in item_attributes[item_id])
                    {
                        double w     = attribute_to_factor[attribute, j];
                        double deriv = diff * w + reg_mapping * w;
                        MatrixUtils.Inc(attribute_to_factor, attribute, j, learn_rate_mapping * -deriv);
                    }
                    // bias term
                    double w_bias     = attribute_to_factor[NumItemAttributes, j];
                    double deriv_bias = diff * w_bias + reg_mapping * w_bias;
                    MatrixUtils.Inc(attribute_to_factor, NumItemAttributes, j, learn_rate_mapping * -deriv_bias);
                }
            }
        }
Ejemplo n.º 29
0
        ///
        protected override void AddItem(int item_id)
        {
            base.AddItem(item_id);

            item_factors.AddRows(item_id + 1);
            MatrixUtils.RowInitNormal(item_factors, InitMean, InitStdev, item_id);
        }
Ejemplo n.º 30
0
        public override void ReadFromFile(MemoryStream stream, bool isBigEndian)
        {
            base.ReadFromFile(stream, isBigEndian);
            Unk05       = stream.ReadByte8();
            Unk06       = stream.ReadInt32(isBigEndian);
            Unk07       = stream.ReadInt32(isBigEndian);
            Transform   = MatrixUtils.ReadFromFile(stream, isBigEndian);
            Unk09       = stream.ReadInt32(isBigEndian);
            UnknownSize = stream.ReadInt32(isBigEndian);

            if (UnknownSize == 0) // Mostly the same as AeOmniLight, but with 12 floats rather than 10.
            {
                // TODO: Why does OmniLight and SpotLight have different array sizes?
                AeLightType0 LightType0 = new AeLightType0();
                LightType0.SetNumFloats(12);
                LightType0.ReadFromFile(stream, isBigEndian);
                LightInfo = LightType0;
            }
            else if (UnknownSize == 1) // This is exactly the same as AeOmniLight. Maybe this is apart of some big type for lights?
            {
                LightInfo = new AeLightType1();
                LightInfo.ReadFromFile(stream, isBigEndian);
            }
            else if (UnknownSize == 2) // Mostly the same as AeOmniLight, but with 12 floats rather than 10.
            {
                LightInfo = new AeLightType2();
                LightInfo.ReadFromFile(stream, isBigEndian);
            }
            else
            {
                throw new FileFormatException();
            }
        }