Exemple #1
0
        private void DrawGeometry()
        {
            // screen space
            DrawPolyline(new[] { new Point3D(3, 20, 0), new Point3D(140, 20, 0) }, Space.Screen, Pens.Gray);

            // view space
            DrawPolyline(new[] { new Point3D(-0.9, -0.9, 0), new Point3D(0.9, -0.9, 0) }, Space.View, Pens.Gray);


            // world space bigger cube
            var angle       = GetDeltaTime(new TimeSpan(0, 0, 0, 5)) * Math.PI * 2;
            var matrixModel =
                MatrixEx.Scale(0.5) *
                MatrixEx.Rotate(new UnitVector3D(1, 0, 0), angle) *
                MatrixEx.Translate(1, 0, 0);

            foreach (var cubePolyline in CubePolylines)
            {
                DrawPolyline(matrixModel.Transform(cubePolyline), Space.World, Pens.White);
            }

            // world space smaller cube
            angle       = GetDeltaTime(new TimeSpan(0, 0, 0, 1)) * Math.PI * 2;
            matrixModel =
                MatrixEx.Scale(0.5) *
                MatrixEx.Rotate(new UnitVector3D(0, 1, 0), angle) *
                MatrixEx.Translate(0, 1, 0) *
                matrixModel;

            foreach (var cubePolyline in CubePolylines)
            {
                DrawPolyline(matrixModel.Transform(cubePolyline), Space.World, Pens.Yellow);
            }
        }
        /// <inheritdoc />
        public CameraInfoCache(ICameraInfo cameraInfo)
        {
            // raw

            // world space -> camera space
            MatrixView        = MatrixEx.LookAtRH(cameraInfo.Position.ToVector3D(), cameraInfo.Target.ToVector3D(), cameraInfo.UpVector);
            MatrixViewInverse = MatrixView.Inverse();

            // camera space -> clip space
            MatrixProjection        = cameraInfo.Projection.GetMatrixProjection();
            MatrixProjectionInverse = MatrixProjection.Inverse();

            // clip space -> screen space
            MatrixViewport        = MatrixEx.Viewport(cameraInfo.Viewport);
            MatrixViewportInverse = MatrixViewport.Inverse();

            // multiplicatives

            // world space -> camera space -> clip space
            MatrixViewProjection        = MatrixView * MatrixProjection;
            MatrixViewProjectionInverse = MatrixViewProjection.Inverse();

            // world space -> camera space -> clip space -> screen space
            MatrixViewProjectionViewport        = MatrixViewProjection * MatrixViewport;
            MatrixViewProjectionViewportInverse = MatrixViewProjectionViewport.Inverse();
        }
        private void LerpPerspective(Camera a, Camera b, float t)
        {
            Matrix4x4 matA = a.projectionMatrix;
            Matrix4x4 matB = b.projectionMatrix;

            this.camera.projectionMatrix = MatrixEx.Lerp(matA, matB, t);
        }
        public void perceptron_should_learn_all_except_xor_nor(
            [ValueSource("Backends")] string backend,
            [ValueSource("Targets")] float[] y,
            [Values(false, true)] bool useBias)
        {
            KerasSharp.Backends.Current.Switch(backend);

            var model = new Sequential();

            model.Add(new Dense(1, input_dim: 2,
                                kernel_initializer: new GlorotUniform(),
                                bias_initializer: new GlorotUniform(),
                                use_bias: useBias,
                                activation: new Sigmoid()));

            model.Compile(loss: new MeanSquareError(), optimizer: new SGD(lr: 1), metrics: new[] { new Accuracy() });

            model.fit(x, y, epochs: 1000, batch_size: y.Length);

            Array yy = model.predict(x, batch_size: y.Length)[0];

            float[] pred = MatrixEx.Round(yy.To <float[, ]>()).GetColumn(0);

            if ((useBias && (y == xor)) ||
                (!useBias && (y == xor || y == nor || y == and)))
            {
                Assert.AreNotEqual(y, pred);
            }
            else
            {
                Assert.AreEqual(y, pred);
            }
        }
        private void DrawGeometry()
        {
            // bigger cube
            var angle       = GetDeltaTime(new TimeSpan(0, 0, 0, 5)) * Math.PI * 2;
            var matrixModel =
                MatrixEx.Scale(0.5) *
                MatrixEx.Rotate(new UnitVector3D(1, 0, 0), angle) *
                MatrixEx.Translate(1, 0, 0);

            foreach (var cubePolyline in CubePolylines)
            {
                DrawPolyline(matrixModel.Transform(cubePolyline), Space.World, Pens.White);
            }

            // smaller cube
            angle       = GetDeltaTime(new TimeSpan(0, 0, 0, 1)) * Math.PI * 2;
            matrixModel =
                MatrixEx.Scale(0.5) *
                MatrixEx.Rotate(new UnitVector3D(0, 1, 0), angle) *
                MatrixEx.Translate(0, 1, 0) *
                matrixModel;

            foreach (var cubePolyline in CubePolylines)
            {
                DrawPolyline(matrixModel.Transform(cubePolyline), Space.World, Pens.Yellow);
            }
        }
Exemple #6
0
        static void Main(string[] args)
        {
            var model = new Sequential();
            var dense = new Dense(units: 5, input_dim: 5,
                                  kernel_initializer: new Constant(Matrix.Identity(5)),
                                  bias_initializer: new Constant(0));

            model.Add(dense);

            float[,] input  = Vector.Range(25).Reshape(5, 5).ToSingle();
            float[,] output = MatrixEx.To <float[, ]>(model.predict(input)[0]);
        }
Exemple #7
0
        /// <summary>
        /// Reconstruct series by providing indices of list of elementary matrices
        /// </summary>
        /// <param name="signalIndex">list of indices of elementary matrices</param>
        /// <returns></returns>
        public double[] Reconstruct(params int[] group)
        {
            //reconstructed ts
            var rts = MatrixEx.Zeros(_ts.Count());

            for (int i = 0; i < group.Length; i++)
            {
                var sm     = EM[group[i]];
                var retVal = diagonalAveraging(sm);
                rts = rts.Add(retVal);
            }

            return(rts);
        }
        private void DrawPolyline(IEnumerable <Point3D> points, Space space, Pen pen)
        {
            switch (space)
            {
            case Space.World:
                var t      = GetDeltaTime(new TimeSpan(0, 0, 0, 10));
                var angle  = t * Math.PI * 2;
                var radius = 2;

                // view matrix
                var cameraPosition = new Vector3D(Math.Sin(angle) * radius, Math.Cos(angle) * radius, 1);
                var cameraTarget   = new Vector3D(0, 0, 0);
                var cameraUpVector = new UnitVector3D(0, 0, 1);
                var matrixView     = MatrixEx.LookAtRH(cameraPosition, cameraTarget, cameraUpVector);

                // projection matrix
                var fovY        = Math.PI * 0.5;
                var aspectRatio = (double)BufferSize.Width / BufferSize.Height;
                var nearPlane   = 0.001;
                var farPlane    = 1000;
                // ReSharper disable once UnusedVariable
                var matrixPerspective = MatrixEx.PerspectiveFovRH(fovY, aspectRatio, nearPlane, farPlane);

                var fieldHeight = 3;
                var fieldWidth  = fieldHeight * aspectRatio;
                // ReSharper disable once UnusedVariable
                var matrixOrthographic = MatrixEx.OrthoRH(fieldWidth, fieldHeight, nearPlane, farPlane);

                var matrixProjection = matrixPerspective;

                // view space (NDC) to screen space matrix
                var matrixViewport = MatrixEx.Viewport(Viewport);

                DrawPolylineScreenSpace((matrixView * matrixProjection * matrixViewport).Transform(points), pen);
                break;

            case Space.View:
                DrawPolylineScreenSpace(MatrixEx.Viewport(Viewport).Transform(points), pen);
                break;

            case Space.Screen:
                DrawPolylineScreenSpace(points, pen);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(space), space, null);
            }
        }
Exemple #9
0
        /// <summary>
        /// Calculates the correlation between components
        /// </summary>
        /// <returns>Matrix of Correlation values</returns>
        public double[,] WCorrelation(int[] group = null)
        {
            int[] grp = group;
            if (group != null && group.Length < 2)
            {
                throw new Exception("Group must contain at least two elements.");
            }

            if (grp == null)
            {
                grp = Enumerable.Range(1, EM.Count).ToArray();
            }


            //prepare for forecasting by calculation necessary values
            var wi      = calculateWeights();
            var count   = grp.Length;
            var contrib = new List <double[]>();

            //
            foreach (var g in grp)
            {
                var c = diagonalAveraging(EM[g]);
                contrib.Add(c);
            }

            //
            var Fnorms = new double[count];

            for (int i = 0; i < count; i++)
            {
                Fnorms[i] = wi.Multiply(contrib[i].Multiply(contrib[i])).Sum();
            }

            Fnorms = Fnorms.Pow(-0.5);
            //
            var wCorr = MatrixEx.Identity(count, count);

            for (int i = 0; i < count; i++)
            {
                for (int j = i + 1; j < count; j++)
                {
                    wCorr[i, j] = Math.Round(Math.Abs(wi.Multiply(contrib[i].Multiply(contrib[j])).Sum()) * Fnorms[i] * Fnorms[j], 4);
                    wCorr[j, i] = wCorr[i, j];
                }
            }
            return(wCorr);
        }
Exemple #10
0
        public void conv_bias(string backend)
        {
            KerasSharp.Backends.Current.Switch(backend);

            var model = new Sequential();
            var dense = new Dense(units: 5, input_dim: 5,
                                  kernel_initializer: new Constant(Matrix.Identity(5)),
                                  bias_initializer: new Constant(42));

            model.Add(dense);

            float[,] input  = Vector.Range(25).Reshape(5, 5).ToSingle();
            float[,] output = MatrixEx.To <float[, ]>(model.predict(input)[0]);

            Assert.IsTrue(input.Add(42).IsEqual(output, 1e-8f));
        }
    public static bool IsBoundsInCameraEx(this Bounds bounds, Camera camera, float leftex, float rightex, float downex,
                                          float upex)
    {
        Matrix4x4 matrix = camera.projectionMatrix * camera.worldToCameraMatrix;

        int code =
            MatrixEx.ComputeOutCodeEx(new Vector4(bounds.center.x + bounds.size.x / 2, bounds.center.y + bounds.size.y / 2,
                                                  bounds.center.z + bounds.size.z / 2, 1), matrix, leftex, rightex, downex, upex);


        code &=
            MatrixEx.ComputeOutCodeEx(new Vector4(bounds.center.x - bounds.size.x / 2, bounds.center.y + bounds.size.y / 2,
                                                  bounds.center.z + bounds.size.z / 2, 1), matrix, leftex, rightex, downex, upex);

        code &=
            MatrixEx.ComputeOutCodeEx(new Vector4(bounds.center.x + bounds.size.x / 2, bounds.center.y - bounds.size.y / 2,
                                                  bounds.center.z + bounds.size.z / 2, 1), matrix, leftex, rightex, downex, upex);

        code &=
            MatrixEx.ComputeOutCodeEx(new Vector4(bounds.center.x - bounds.size.x / 2, bounds.center.y - bounds.size.y / 2,
                                                  bounds.center.z + bounds.size.z / 2, 1), matrix, leftex, rightex, downex, upex);

        code &=
            MatrixEx.ComputeOutCodeEx(new Vector4(bounds.center.x + bounds.size.x / 2, bounds.center.y + bounds.size.y / 2,
                                                  bounds.center.z - bounds.size.z / 2, 1), matrix, leftex, rightex, downex, upex);

        code &=
            MatrixEx.ComputeOutCodeEx(new Vector4(bounds.center.x - bounds.size.x / 2, bounds.center.y + bounds.size.y / 2,
                                                  bounds.center.z - bounds.size.z / 2, 1), matrix, leftex, rightex, downex, upex);

        code &=
            MatrixEx.ComputeOutCodeEx(new Vector4(bounds.center.x + bounds.size.x / 2, bounds.center.y - bounds.size.y / 2,
                                                  bounds.center.z - bounds.size.z / 2, 1), matrix, leftex, rightex, downex, upex);

        code &=
            MatrixEx.ComputeOutCodeEx(new Vector4(bounds.center.x - bounds.size.x / 2, bounds.center.y - bounds.size.y / 2,
                                                  bounds.center.z - bounds.size.z / 2, 1), matrix, leftex, rightex, downex, upex);


        if (code != 0)
        {
            return(false);
        }

        return(true);
    }
    /// <summary>
    /// 判断包围盒是否被相机裁剪
    /// </summary>
    /// <param name="bounds"></param>
    /// <param name="camera"></param>
    /// <returns></returns>
    public static bool IsBoundsInCamera(this Bounds bounds, Camera camera)
    {
        Matrix4x4 matrix = camera.projectionMatrix * camera.worldToCameraMatrix;

        int code =
            MatrixEx.ComputeOutCode(new Vector4(bounds.center.x + bounds.size.x / 2, bounds.center.y + bounds.size.y / 2,
                                                bounds.center.z + bounds.size.z / 2, 1), matrix);


        code &=
            MatrixEx.ComputeOutCode(new Vector4(bounds.center.x - bounds.size.x / 2, bounds.center.y + bounds.size.y / 2,
                                                bounds.center.z + bounds.size.z / 2, 1), matrix);

        code &=
            MatrixEx.ComputeOutCode(new Vector4(bounds.center.x + bounds.size.x / 2, bounds.center.y - bounds.size.y / 2,
                                                bounds.center.z + bounds.size.z / 2, 1), matrix);

        code &=
            MatrixEx.ComputeOutCode(new Vector4(bounds.center.x - bounds.size.x / 2, bounds.center.y - bounds.size.y / 2,
                                                bounds.center.z + bounds.size.z / 2, 1), matrix);

        code &=
            MatrixEx.ComputeOutCode(new Vector4(bounds.center.x + bounds.size.x / 2, bounds.center.y + bounds.size.y / 2,
                                                bounds.center.z - bounds.size.z / 2, 1), matrix);

        code &=
            MatrixEx.ComputeOutCode(new Vector4(bounds.center.x - bounds.size.x / 2, bounds.center.y + bounds.size.y / 2,
                                                bounds.center.z - bounds.size.z / 2, 1), matrix);

        code &=
            MatrixEx.ComputeOutCode(new Vector4(bounds.center.x + bounds.size.x / 2, bounds.center.y - bounds.size.y / 2,
                                                bounds.center.z - bounds.size.z / 2, 1), matrix);

        code &=
            MatrixEx.ComputeOutCode(new Vector4(bounds.center.x - bounds.size.x / 2, bounds.center.y - bounds.size.y / 2,
                                                bounds.center.z - bounds.size.z / 2, 1), matrix);


        if (code != 0)
        {
            return(false);
        }

        return(true);
    }
        /// <summary>
        /// Create new <see cref="ICameraInfo"/> based on mouse offset in view space and orbit origin.
        /// </summary>
        public static ICameraInfo Orbit(ICameraInfo cameraInfoStart, Vector3D mouseOffsetView, Point3D orbitOrigin)
        {
            // default input
            var eye    = cameraInfoStart.Position;
            var target = cameraInfoStart.Target;

            // create local coordinate system
            var zAxis              = cameraInfoStart.UpVector;
            var yzPlane            = new Plane(new Point3D(), cameraInfoStart.GetEyeDirection().ToPoint3D(), zAxis.ToPoint3D());
            var xAxis              = yzPlane.Normal;
            var xzPlane            = new Plane(new Point3D(), zAxis.ToPoint3D(), xAxis.ToPoint3D());
            var yAxis              = xzPlane.Normal;
            var matrixWorldToLocal = (Matrix <double>) new CoordinateSystem(new Point3D(), xAxis, yAxis, zAxis);

            // transform to local system
            orbitOrigin = matrixWorldToLocal.Transform(orbitOrigin);
            eye         = matrixWorldToLocal.Transform(eye);
            target      = matrixWorldToLocal.Transform(target);

            // figure out angles (how much to rotate)
            GetSphereAngles(mouseOffsetView, (target - eye).Normalize(), out var thetaDelta, out var phiDelta);

            // rotate horizontally
            var matrixRotationHorizontal = MatrixEx.Rotate(UnitVector3D.ZAxis, thetaDelta.Radians).TransformAround(orbitOrigin);

            eye    = matrixRotationHorizontal.Transform(eye);
            target = matrixRotationHorizontal.Transform(target);

            // rotate vertically
            var phiPlane = new Plane(eye, target, target + UnitVector3D.ZAxis);
            var matrixRotationVertical = MatrixEx.Rotate(phiPlane.Normal, phiDelta.Radians).TransformAround(orbitOrigin);

            eye    = matrixRotationVertical.Transform(eye);
            target = matrixRotationVertical.Transform(target);

            // transform back to world system
            var matrixLocalToWorld = matrixWorldToLocal.Inverse();

            eye    = matrixLocalToWorld.Transform(eye);
            target = matrixLocalToWorld.Transform(target);

            // update camera info
            return(new CameraInfo(eye, target, cameraInfoStart.UpVector, cameraInfoStart.Projection.Cloned(), cameraInfoStart.Viewport));
        }
Exemple #14
0
        void prepareForecast(int singularsValuesCount)
        {
            double vertCoeff = 0;

            double[][] forecastOrthonormalVal;
            var        L         = _xCom.GetLength(0);
            var        K         = _xCom.GetLength(1);
            var        X_com_hat = MatrixEx.Zeros(L, K);

            if (singularsValuesCount >= 0)
            {
                var len = Math.Min(singularsValuesCount, _orthonormalBase.Length);
                forecastOrthonormalVal = new double[len][];
                for (int i = 0; i < len; i++)
                {
                    forecastOrthonormalVal[i] = _orthonormalBase[i];
                }
            }
            else
            {
                forecastOrthonormalVal = _orthonormalBase;
            }

            var valR = MatrixEx.Zeros(forecastOrthonormalVal[0].Length, 1);
            var tmp  = valR.GetColumn(valR.GetLength(1) - 1);

            _R = tmp.Take(tmp.Count() - 1).ToArray();
            for (int i = 0; i < forecastOrthonormalVal.Length; i++)
            {
                //
                var PI   = forecastOrthonormalVal[i];
                var prod = PI.ToMatrix(true).Dot(PI.ToMatrix(false));
                var temp = prod.Dot(_xCom);
                X_com_hat = X_com_hat.Add(temp);
                //
                var pi = PI.Last();
                vertCoeff += pi * pi;
                var rr = PI.Take(PI.Length - 1).ToArray().Multiply(pi);
                _R = _R.Add(rr);
            }
            _R          = _R.Divide((1.0 - vertCoeff));
            X_com_tilde = diagonalAveraging(X_com_hat);
        }
Exemple #15
0
        /// <summary>
        /// Reconstruct time series component from the signal matrix
        /// </summary>
        /// <param name="xs">number of signal matrix</param>
        /// <returns></returns>
        public double[] Reconstruct(int signalCounts = -1)
        {
            double[] tsCumulative = null;
            IEnumerable <KeyValuePair <int, double[, ]> > sM = _Xs;

            if (signalCounts > 0)
            {
                sM = _Xs.Take(signalCounts);
            }
            //initi ts
            tsCumulative = MatrixEx.Zeros(_ts.Count());
            foreach (var sMat in sM)
            {
                var retVal = diagonalAveraging(sMat.Value);
                tsCumulative = tsCumulative.Add(retVal);
            }

            return(tsCumulative);
        }
Exemple #16
0
        /// <summary>
        /// Get some primitives to demonstrate hierarchical matrix multiplication.
        /// </summary>
        private static IEnumerable <IPrimitive> GetPrimitivesCubes()
        {
            var duration = new TimeSpan(DateTime.UtcNow.Ticks);

            // world space bigger cube
            var angle       = GetTimeSpanPeriodRatio(duration, new TimeSpan(0, 0, 0, 5)) * Math.PI * 2;
            var matrixModel =
                MatrixEx.Scale(0.5) *
                MatrixEx.Rotate(new UnitVector3D(1, 0, 0), angle) *
                MatrixEx.Translate(1, 0, 0);

            foreach (var cubePolyline in CubePolylines)
            {
                yield return(new Materials.Position.Primitive
                             (
                                 new PrimitiveBehaviour(Space.World),
                                 PrimitiveTopology.LineStrip,
                                 matrixModel.Transform(cubePolyline).Select(position => new Materials.Position.Vertex(position)).ToArray(),
                                 Color.White
                             ));
            }

            // world space smaller cube
            angle       = GetTimeSpanPeriodRatio(duration, new TimeSpan(0, 0, 0, 1)) * Math.PI * 2;
            matrixModel =
                MatrixEx.Scale(0.5) *
                MatrixEx.Rotate(new UnitVector3D(0, 1, 0), angle) *
                MatrixEx.Translate(0, 1, 0) *
                matrixModel;

            foreach (var cubePolyline in CubePolylines)
            {
                yield return(new Materials.Position.Primitive
                             (
                                 new PrimitiveBehaviour(Space.World),
                                 PrimitiveTopology.LineStrip,
                                 matrixModel.Transform(cubePolyline).Select(position => new Materials.Position.Vertex(position)).ToArray(),
                                 Color.Yellow
                             ));
            }
        }
Exemple #17
0
        private Constant _constant <T>(T value, int?[] shape, DataType?dtype, string name)
        {
            if (value is Array)
            {
                NDArrayView x = In((value as Array).Convert(dtype.ToType()));
                if (name != null)
                {
                    return(new Constant(x, name));
                }
                else
                {
                    return(new Constant(x));
                }
            }

            if (value is double)
            {
                return(Constant.Scalar <double>(MatrixEx.To <double>(value), device: DeviceDescriptor.CPUDevice));
            }
            if (value is float)
            {
                return(Constant.Scalar <double>(MatrixEx.To <float>(value), device: DeviceDescriptor.CPUDevice));
            }

            if (name == null)
            {
                return(new Constant(shape: InShape(shape),
                                    dataType: In(dtype.Value),
                                    initValue: (dynamic)value,
                                    device: DeviceDescriptor.CPUDevice));
            }

            return(new Constant(shape: InShape(shape),
                                dataType: In(dtype.Value),
                                initValue: (dynamic)value,
                                device: DeviceDescriptor.CPUDevice,
                                name: name));
        }
Exemple #18
0
        /// <summary>
        /// transform each matrix XIj of the grouped decomposition into a new series of length N
        /// </summary>
        /// <returns>elementary reconstructed series</returns>
        private double[] diagonalAveraging(double[,] signalMatrix)
        {
            var L = signalMatrix.GetLength(0);
            var K = signalMatrix.GetLength(1);
            var Y = signalMatrix;

            int lStar = Math.Min(L, K);
            int kStar = Math.Max(L, K);
            int N     = L + K - 1;
            //
            var newM = MatrixEx.Zeros(L, K);

            //
            if (L >= K)
            {
                Y = Y.Transpose();
            }

            //reconstructed series
            var y = new double[N];

            for (int k = 1; k <= N; k++)
            {
                double yk = 0;
                if (k >= 1 && k < lStar)
                {
                    for (int m = 1; m <= k; m++)
                    {
                        int i = m;
                        int j = k - m + 1;
                        yk += Y[i - 1, j - 1];//zero based index
                    }
                    //
                    y[k - 1] = yk / k;
                }
                else if (k >= lStar && k <= kStar)
                {
                    for (int m = 1; m <= lStar; m++)
                    {
                        int i = m;
                        int j = k - m + 1;
                        yk += Y[i - 1, j - 1];//zero based index
                    }
                    //
                    y[k - 1] = yk / lStar;
                }
                else if (k > kStar && k <= N)
                {
                    for (int m = k - kStar + 1; m <= N - kStar + 1; m++)
                    {
                        int i = m;
                        int j = k - m + 1;
                        yk += Y[i - 1, j - 1];//zero based index
                    }
                    //
                    y[k - 1] = yk / (N - k + 1);
                }
                else
                {
                    throw new Exception("This should not be happen!");
                }
            }
            return(y);
        }
        public override List <Tensor> Call(List <Array> inputs)
        {
            var feed_dict = new Dictionary <Variable, Array>();

            foreach (var(tensor, value) in Enumerable.Zip(this.placeholders, inputs, (a, b) => (a, b)))
            {
                Type  t = value.GetInnerMostType();
                Array v = value;

                // cntk only support calculate on float, do auto cast here
                if (t != typeof(float) && t != typeof(double))
                {
                    v = MatrixEx.Convert <double>(value);
                }
                feed_dict[tensor] = v;
            }

            var updated = new List <Tensor>();

            if (this.trainer != null)
            {
                var input_dict = new UnorderedMapVariableValuePtr();
                foreach (Variable argument in this.loss.Arguments)
                {
                    if (feed_dict.ContainsKey(argument))
                    {
                        input_dict[argument] = new Value(CNTKBackend.In(feed_dict[argument]));
                    }
                    else
                    {
                        throw new Exception($"CNTK backend: argument {argument.Name} is not found in inputs. Please double check the model and inputs in 'train_function'.");
                    }
                }

                var result = this.trainer.TrainMinibatch(input_dict, this.trainer_output);

                foreach (Variable o in this.trainer_output.Keys)
                {
                    updated.Add(c.Out(this.trainer_output[o]));
                }
            }

            if (this.metrics_func != null)
            {
                var input_dict = new Dictionary <Variable, Value>();
                foreach (Variable argument in this.metrics_func.Arguments)
                {
                    if (feed_dict.ContainsKey(argument))
                    {
                        input_dict[argument] = new Value(CNTKBackend.In(feed_dict[argument]));
                    }
                    else
                    {
                        throw new Exception($"CNTK backend: metrics argument {argument.Name} is not found in inputs. Please double check the model and inputs.");
                    }
                }

                var output_values = new Dictionary <Variable, Value>();
                foreach (Variable variable in this.metrics_outputs)
                {
                    output_values[variable] = null;
                }

                this.metrics_func.Evaluate(input_dict, output_values, DeviceDescriptor.CPUDevice);

                foreach (Variable o in this.metrics_outputs)
                {
                    Value value = output_values[o];
                    var   v     = c.Out(value);
                    updated.Add(v);
                }
            }

            if (this.unrelated_updates != null)
            {
                var input_dict = new Dictionary <Variable, Value>();
                foreach (Variable argument in this.unrelated_updates.Arguments)
                {
                    if (feed_dict.ContainsKey(argument))
                    {
                        input_dict[argument] = new Value(CNTKBackend.In(feed_dict[argument]));
                    }
                    else
                    {
                        throw new Exception($"CNTK backend: assign ops argument {argument.Name} is not found in inputs. Please double check the model and inputs.");
                    }
                }

                var output_values = new Dictionary <Variable, Value>();
                this.unrelated_updates.Evaluate(input_dict, output_values, DeviceDescriptor.CPUDevice);
            }

            return(updated);
        }
Exemple #20
0
 protected virtual int CalculateCullCode(Vector4 position, Matrix4x4 matrix)
 {
     return(MatrixEx.ComputeOutCode(position, matrix));
 }
 protected override int CalculateCullCode(Vector4 position, Matrix4x4 matrix)
 {
     return(MatrixEx.ComputeOutCodeEx(position, matrix, m_LeftEx, m_RightEx, m_DownEx, m_UpEx));
 }
Exemple #22
0
        /// <summary>
        /// transform each matrix Xij of the grouped decomposition into a new series of length N
        /// </summary>
        /// <returns>elementary reconstructed series</returns>
        private double[] diagonalAveraging(double[,] eMatrix)
        {
            //calculate number of cols, rows and
            var LL = eMatrix.GetLength(0);
            var KK = eMatrix.GetLength(1);
            var Y  = eMatrix;

            int lStar = Math.Min(LL, KK);
            int kStar = Math.Max(LL, KK);
            int N     = LL + KK - 1;
            //
            var newM = MatrixEx.Zeros(L, K);

            //
            if (LL >= KK)
            {
                Y = Y.Transpose();
            }

            //reconstructed series
            var y = new double[N];

            for (int k = 1; k <= N; k++)
            {
                double yk = 0;
                if (k >= 1 && k < lStar)
                {
                    for (int m = 1; m <= k; m++)
                    {
                        int i = m;
                        int j = k - m + 1;
                        yk += Y[i - 1, j - 1];
                    }
                    //
                    y[k - 1] = yk / k;
                }
                else if (k >= lStar && k <= kStar)
                {
                    for (int m = 1; m <= lStar; m++)
                    {
                        int i = m;
                        int j = k - m + 1;
                        yk += Y[i - 1, j - 1];
                    }
                    //
                    y[k - 1] = yk / lStar;
                }
                else if (k > kStar && k <= N)
                {
                    for (int m = k - kStar + 1; m <= N - kStar + 1; m++)
                    {
                        int i = m;
                        int j = k - m + 1;
                        yk += Y[i - 1, j - 1];
                    }
                    //
                    y[k - 1] = yk / (N - k + 1);
                }
                else
                {
                    throw new Exception("This should not be happened!");
                }
            }
            return(y);
        }
 /// <inheritdoc />
 public override Matrix <double> GetMatrixProjection()
 {
     return(MatrixEx.OrthoRH(FieldWidth, FieldHeight, NearPlane, FarPlane));
 }
 /// <inheritdoc />
 public override Matrix <double> GetMatrixProjection()
 {
     return(MatrixEx.PerspectiveFovRH(FieldOfViewY, AspectRatio, NearPlane, FarPlane));
 }