public override double Forward(Matrix Actual, Matrix Expected, MatrixData data, int layerCount)
        {
            double error = 0.0;

            if (Actual.rows != Expected.rows || Actual.cols != Expected.cols)
            {
                throw new MatrixException("Actual does not have the same size as Expected");
            }

            double regularizationValue = 0.0;

            for (int i = 0; i < layerCount; i++)
            {
                regularizationValue = RegularizationFunction.CalculateNorm(data.Data["W" + i.ToString()]);
            }

            for (int i = 0; i < Actual.rows; i++)
            {
                for (int j = 0; j < Actual.cols; j++)
                {
                    error += Expected[i, j] * Math.Log(Expected[i, j] / Actual[i, j]);
                }
            }

            error += regularizationValue;

            BatchCost += error;
            return(error);
        }
        private void zcSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs <double> e)
        {
            zc = Math.Round(e.NewValue) * 10;
            MatrixData md = new MatrixData(0, zc);

            shape.ProjectReal3D(md.Zc);
        }
Example #3
0
        public override void Forward(ref MatrixData input)
        {
            // First layer will be a-1
            // Get previous a
            Matrix prev_A = input.Data["a" + (Index - 1).ToString()];

            // Get previous W
            Matrix W = input.Data["W" + (Index).ToString()];

            // Get previous b
            Matrix b = input.Data["b" + (Index).ToString()];

            // Calculate Z and store it
            Matrix Z = Matrix.Transpose(W).Dot((prev_A)) + b;

            input.Data["Z" + (Index).ToString()] = Z;

            // Calculate a and store it
            Matrix A = Activation.Forward(Z);

            input.Data["a" + (Index).ToString()] = Z;

            // Formula For a[i]: g[i]((W_Transpose[i] . z[i-1]) + B[i])

            // Update the global data
            GlobalData = input;
        }
Example #4
0
        public override void Backward(ref MatrixData input)
        {
            // The only thing we need to put into the Input Matrix is the last calculated da
            // Calculate dz and store it
            Matrix dz = input.Data["da" + (Index).ToString()].ElementMul(Activation.Backward(input.Data["Z" + (Index).ToString()]));

            input.Data["dZ" + (Index).ToString()] = dz;

            // Calculate dw and store it
            Matrix dw = input.Data["dZ" + (Index).ToString()].Dot(Matrix.Transpose(input.Data["a" + (Index - 1).ToString()]));

            input.Data["dW" + (Index).ToString()] = dw;

            // Calculate db and store it
            Matrix db = dz;

            input.Data["db" + (Index).ToString()] = db;

            // Calculate previous da and store it
            Matrix prev_da = input.Data["W" + (Index).ToString()].Dot(input.Data["dZ" + (Index).ToString()]);

            input.Data["da" + (Index - 1).ToString()] = prev_da;

            // Formula dZ[i]: ((W_Transpose[i+1] . dZ[i+1]) * g'[i](z[i]))

            // Update the global data
            GlobalData = input;
        }
Example #5
0
        public JsonResult AddQuestions(long GroupTypeVal, string GroupTypeText)
        {
            bool isResult     = false;
            int  returnResult = 0;

            try
            {
                QuestionsModel question = new QuestionsModel();
                question.AssessmentGroupId = GroupTypeVal;
                question.QuestionText      = GroupTypeText.Trim();
                question.AgencyId          = (Session["AgencyId"] != null) ? new Guid(Session["AgencyId"].ToString()) : (Guid?)null;
                question.UserId            = new Guid(Session["UserID"].ToString());
                question.AssessmentGroupId = GroupTypeVal;
                string command = "CHECKQUESTION";
                isResult = new MatrixData().CheckQuestions(question, command);
                if (isResult)
                {
                    returnResult = 2;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
                isResult = new MatrixData().InsertQuestionType(question);
                if (isResult)
                {
                    returnResult = 1;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception Ex)
            {
                clsError.WriteException(Ex);
                //return Json("Error occured please try again.");
            }
            return(Json(isResult, JsonRequestBehavior.AllowGet));
        }
Example #6
0
        public JsonResult DeleteAssessmentGroup(long groupId)
        {
            bool isResult     = false;
            int  returnResult = 0;

            try
            {
                AssessmentGroup group = new FingerprintsModel.AssessmentGroup();
                group.AssessmentGroupId = groupId;
                group.UserId            = new Guid(Session["UserID"].ToString());
                group.AgencyId          = (Session["AgencyId"] != null) ? new Guid(Session["AgencyId"].ToString()) : (Guid?)null;
                const string command = "CHECKGROUPREF";
                isResult = new MatrixData().CheckAssessmentGroup(group, command);
                if (isResult)
                {
                    returnResult = 2;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
                isResult = new MatrixData().DeleteAssessmentGroup(group);
                if (isResult)
                {
                    returnResult = 1;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                clsError.WriteException(ex);
            }
            return(Json(returnResult, JsonRequestBehavior.AllowGet));
        }
Example #7
0
        public JsonResult DeleteMatrixType(long ID)
        {
            bool isResult     = false;
            int  returnResult = 0;

            try
            {
                Guid?agencyid = (Session["AgencyId"] != null) ? new Guid(Session["AgencyId"].ToString()) : (Guid?)null;
                Guid userId   = new Guid(Session["UserID"].ToString());
                isResult = new MatrixData().CheckMatrixRef(ID, agencyid);
                if (isResult)
                {
                    returnResult = 2;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
                isResult = new MatrixData().DeleteMatrixType(ID, agencyid, userId);
                if (isResult)
                {
                    returnResult = 1;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                clsError.WriteException(ex);
                //return Json("Error occured please try again.");
            }
            return(Json(isResult, JsonRequestBehavior.AllowGet));
        }
Example #8
0
        public JsonResult UpdateAssessmentCategory(string categoryName, long categoryId, long position)
        {
            bool               isResult           = false;
            int                returnResult       = 0;
            string             queryCommand       = "CHECKUPDATE";
            AssessmentCategory assessmentCategory = new FingerprintsModel.AssessmentCategory();

            try
            {
                assessmentCategory.UserId               = new Guid(Session["UserID"].ToString());
                assessmentCategory.AgencyId             = (Session["AgencyId"] != null) ? new Guid(Session["AgencyId"].ToString()) : (Guid?)null;
                assessmentCategory.Category             = categoryName.Trim();
                assessmentCategory.AssessmentCategoryId = categoryId;
                assessmentCategory.CategoryPosition     = position;
                isResult = new MatrixData().CheckAssessmentCategory(assessmentCategory, queryCommand);
                if (isResult)
                {
                    returnResult = 2;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
                isResult = new MatrixData().UpdateAssessmentCategory(assessmentCategory);
                if (isResult)
                {
                    returnResult = 1;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                clsError.WriteException(ex);
            }
            return(Json(returnResult, JsonRequestBehavior.AllowGet));
        }
Example #9
0
        public virtual void FillRectangle(Rectangle <float> rectangle, Color <float> color)
        {
            //fill rectangle
            //color.alpha means the opacity of rectangle

            MatrixData   matrixData   = new MatrixData();
            RenderConfig renderConfig = new RenderConfig()
            {
                Color = color
            };

            //1.scale the rectangle
            matrixData.World = Matrix4x4.CreateScale(rectangle.Right - rectangle.Left, rectangle.Bottom - rectangle.Top, 1.0f);
            //2.translate it
            matrixData.World *= Matrix4x4.CreateTranslation(rectangle.Left, rectangle.Top, 0.0f);
            //3.keep transform matrix data
            matrixData.World *= Transform;

            //set projection matrix
            matrixData.Project = mProject;

            mMatrixDataBuffer.Update(matrixData);
            mRenderConfigBuffer.Update(renderConfig);

            mDevice.SetPixelShader(mColorPixelShader);
            mDevice.SetVertexBuffer(mSquareVertexBuffer);
            mDevice.SetIndexBuffer(mSquareIndexBuffer);

            mDevice.SetBuffer(mMatrixDataBuffer, mMatrixDataBufferSlot, GpuShaderType.VertexShader);
            mDevice.SetBuffer(mRenderConfigBuffer, mRenderConfigBufferSlot, GpuShaderType.PixelShader);

            mDevice.DrawIndexed(6, 0, 0);
        }
Example #10
0
        public JsonResult DeleteAssessmentCategory(long categoryId)
        {
            bool isResult     = false;
            int  returnResult = 0;

            try
            {
                AssessmentCategory assessmentCategory = new FingerprintsModel.AssessmentCategory();
                assessmentCategory.UserId               = new Guid(Session["UserID"].ToString());
                assessmentCategory.AgencyId             = (Session["AgencyId"] != null) ? new Guid(Session["AgencyId"].ToString()) : (Guid?)null;
                assessmentCategory.AssessmentCategoryId = categoryId;
                const string command = "CHECKCATREF";
                isResult = new MatrixData().CheckAssessmentCategory(assessmentCategory, command);
                if (isResult)
                {
                    returnResult = 2;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
                isResult = new MatrixData().DeleteAssessmentCategory(assessmentCategory);
                {
                    returnResult = 1;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                clsError.WriteException(ex);
            }
            return(Json(returnResult, JsonRequestBehavior.AllowGet));
        }
Example #11
0
        public void Run(string fileName)
        {
            MatrixData m = new MatrixData(fileName, false, true, ',');

            for (int i = 0; i < 2; i++)
            {
                OutputSteps(m[i].GetReShapedMatrix(19), i.ToString());
            }

            void OutputSteps(MatrixData input, string dir)
            {
                string _dir = "Data\\" + dir + "";

                MatrixData pixelMatrix = input;

                pixelMatrix.Clamp(0, 255).UpScale(16).ToImage(_dir + "0.bmp");

                pixelMatrix = pixelMatrix.ReduceDimensionByOne(0).ReduceDimensionByOne(1);
                pixelMatrix.UpScale(16).Clamp(0, 255).ToImage(_dir + "1.bmp");

                pixelMatrix = pixelMatrix.Convert18To6Px(false);
                pixelMatrix.Clamp(0, 255);
                pixelMatrix.UpScale(16).ToImage(_dir + "3.bmp");
            }
        }
Example #12
0
        public void GrayTo255(string fileName)
        {
            MatrixData m = new MatrixData(fileName, true, true, ',') * 255;

            m = m.RoundAll();
            m.WriteCSV(fileName.Replace(".csv", "") + "255" + ".csv", false);
        }
Example #13
0
        public dynamic[] ProcessImage2(dynamic[] input)
        {
            //Turn the input vector into a matrix
            //This matrix represents the image
            MatrixData pixelMatrix = input.GetReShapedMatrix(19);

            //Get the emboss edge
            pixelMatrix = pixelMatrix.GetEmbossEdge();

            //Apply with hist EQ function
            pixelMatrix = pixelMatrix.HistEQ();

            //Crop 1 pixel off the edge of the image
            //this results in a 17x17 image
            pixelMatrix = pixelMatrix.CropEdges(1);

            //reduce the size of the image to 16x16 by removing
            // a random pixel from each row and column
            pixelMatrix = pixelMatrix.ReduceDimensionByOne(0).ReduceDimensionByOne(1);

            //Blur the image
            pixelMatrix = pixelMatrix.ApplyConvolutionFilter(blurFilter);

            //Reduce the 16x16 image to 8x8 using a custom downsampling algorithm
            pixelMatrix = pixelMatrix.DownScale(2);

            //Clamp the output matrix values between 0 and 255
            pixelMatrix = pixelMatrix.Clamp(0, 255);

            //return the pixel matrix as a vector
            // the size of this vector will be 36 (6x6)
            return(pixelMatrix.GetVectorizedMatrix());
        }
Example #14
0
        public dynamic[] ProcessImage1(dynamic[] input)
        {
            //Turn the input vector into a matrix
            //This matrix represents the image
            MatrixData pixelMatrix = input.GetReShapedMatrix(19);

            //Sharpen the image
            pixelMatrix = pixelMatrix.ApplyConvolutionFilter(sharpenFilter);

            //Apply the SobelEdge filter
            pixelMatrix = pixelMatrix.GetSobelEdge();

            //reduce the size of the image to 18x18 by removing
            // a random pixel from each row and column
            pixelMatrix = pixelMatrix.ReduceDimensionByOne(0).ReduceDimensionByOne(1);

            //Blur the image
            pixelMatrix = pixelMatrix.ApplyConvolutionFilter(blurFilter);

            //Reduce the 18x18 image to 6x6 using a custom downsampling algorithm
            pixelMatrix = pixelMatrix.Convert18To6Px();

            //Clamp the output matrix values between 0 and 255
            pixelMatrix = pixelMatrix.Clamp(0, 255);

            //return the pixel matrix as a vector
            // the size of this vector will be 36 (6x6)
            return(pixelMatrix.GetVectorizedMatrix());
        }
Example #15
0
        private static double[][,] GetMatrix(string file)
        {
            var traindata = new MatrixData();

            traindata.LoadData(file);
            return(traindata.ToDoubleMatrix(new Size(16, 16)));
        }
Example #16
0
        public JsonResult UpdateAssessmentGroup(string groupType, long categoryId, int status, long groupId)
        {
            bool isResult     = false;
            int  returnResult = 0;

            try
            {
                string          queryCommand    = "UPDATECHECK";
                AssessmentGroup assessmentGroup = new FingerprintsModel.AssessmentGroup();
                assessmentGroup.UserId               = new Guid(Session["UserID"].ToString());
                assessmentGroup.AgencyId             = (Session["AgencyId"] != null) ? new Guid(Session["AgencyId"].ToString()) : (Guid?)null;
                assessmentGroup.AssessmentCategoryId = categoryId;
                assessmentGroup.IsActive             = Convert.ToBoolean(status);
                assessmentGroup.AssessmentGroupType  = groupType;
                assessmentGroup.AssessmentGroupId    = groupId;
                isResult = new MatrixData().CheckAssessmentGroup(assessmentGroup, queryCommand);
                if (isResult)
                {
                    returnResult = 2;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
                isResult     = new MatrixData().UpdateAssessmentGroup(assessmentGroup);
                returnResult = 1;
                return(Json(returnResult, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                clsError.WriteException(ex);
                return(Json(returnResult, JsonRequestBehavior.AllowGet));
            }
        }
Example #17
0
        public string ResetData()
        {
            string output = "";

            output         += "Setting \"" + nameof(_rawData) + "\" to null" + Environment.NewLine;
            _rawData        = null;
            output         += "Setting \"" + nameof(_exemplarData) + "\" to null" + Environment.NewLine;
            _exemplarData   = null;
            output         += "Setting \"" + nameof(_trainingData) + "\" to null" + Environment.NewLine;
            _trainingData   = null;
            output         += "Setting \"" + nameof(_testingData) + "\" to null" + Environment.NewLine;
            _testingData    = null;
            output         += "Setting \"" + nameof(_validationData) + "\" to null" + Environment.NewLine;
            _validationData = null;

            output += "Setting \"" + nameof(_confusionMatrixTrain) + "\" to null" + Environment.NewLine;
            _confusionMatrixTrain = null;
            output += "Setting \"" + nameof(_confusionMatrixTest) + "\" to null" + Environment.NewLine;
            _confusionMatrixTest = null;
            output += "Setting \"" + nameof(_confusionMatrixVal) + "\" to null" + Environment.NewLine;
            _confusionMatrixVal = null;
            output            += "Setting \"" + nameof(_outputMatrixTrain) + "\" to null" + Environment.NewLine;
            _outputMatrixTrain = null;


            output           += "Setting \"" + nameof(_outputMatrixTest) + "\" to null" + Environment.NewLine;
            _outputMatrixTest = null;
            output           += "Setting \"" + nameof(_outputMatrixVal) + "\" to null" + Environment.NewLine;
            _outputMatrixVal  = null;

            output    += "Setting \"" + nameof(_graphData) + "\" to null" + Environment.NewLine;
            _graphData = null;

            return(output);
        }
Example #18
0
        public JsonResult AddMatrxiType(long matrixvalue, string matrixtype)
        {
            bool isResult     = false;
            int  returnResult = 0;

            try
            {
                string querycommand = "CHECKMATRIX";
                Matrix matrix       = new FingerprintsModel.Matrix();
                matrix.MatrixValue = matrixvalue;
                matrix.MatrixType  = matrixtype.Trim();
                matrix.AgencyId    = (Session["AgencyId"] != null) ? new Guid(Session["AgencyId"].ToString()) : (Guid?)null;
                matrix.UserId      = new Guid(Session["UserID"].ToString());

                isResult = new MatrixData().CheckMatrixType(matrix, querycommand);
                if (isResult)
                {
                    returnResult = 2;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
                isResult = new MatrixData().InsertMatrixType(matrix);
                if (isResult)
                {
                    returnResult = 1;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception Ex)
            {
                clsError.WriteException(Ex);
                //return Json("Error occured please try again.");
            }
            return(Json(returnResult));
        }
Example #19
0
        private string trainNN(string nnRef, string matrixTrainRef, string matrixTestRef, int epochs, double eta, string outputFileName)
        {
            var nn = Value(nnRef);

            if (nn.GetType() == typeof(string))
            {
                return(nn.ToString());
            }
            var matrixTrain = Value(matrixTrainRef);

            if (matrixTrain.GetType() == typeof(string))
            {
                return(matrixTrain.ToString());
            }
            var matrixTest = Value(matrixTestRef);

            if (matrixTest.GetType() == typeof(string))
            {
                return(matrixTest.ToString());
            }

            MatrixData      train = (MatrixData)matrixTrain;
            MatrixData      test  = (MatrixData)matrixTest;
            W4NeuralNetwork m     = (W4NeuralNetwork)nn;

            m.train(train.Data.ToJagged().ToDoubleArray(), test.Data.ToJagged().ToDoubleArray(), epochs, eta, outputFileName + ".nnlog.txt");
            return("Trained neural network \"" + nnRef + "\" with " + epochs + " epochs, " + eta.ToString() + " eta");
        }
Example #20
0
        public JsonResult UpdateAcronym(long AcronymId, string AcronymName)
        {
            bool isResult     = false;
            int  returnResult = 0;

            try
            {
                string  queryCommand = "UPDATECHECK";
                Acronym acronym      = new FingerprintsModel.Acronym();
                acronym.AcronymId   = AcronymId;
                acronym.AcronymName = AcronymName;
                acronym.UserId      = new Guid(Session["UserID"].ToString());
                acronym.AgencyId    = (Session["AgencyId"] != null) ? new Guid(Session["AgencyId"].ToString()) : (Guid?)null;
                isResult            = new MatrixData().CheckUpdateAcronym(acronym, queryCommand);
                if (isResult)
                {
                    returnResult = 2;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
                isResult     = new MatrixData().UpdateAcronym(acronym);
                returnResult = 1;
                return(Json(returnResult, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                clsError.WriteException(ex);
                return(Json("Error occured please try again."));
            }
        }
Example #21
0
        public JsonResult UpdateQuestions(long GroupType, string Questiontype, long QuestionId)
        {
            bool isResult     = false;
            int  returnResult = 0;

            try
            {
                QuestionsModel question = new QuestionsModel();
                question.AssessmentQuestion   = Questiontype;
                question.AssessmentGroupId    = GroupType;
                question.AssessmentQuestionId = QuestionId;
                question.UserId   = new Guid(Session["UserID"].ToString());
                question.AgencyId = (Session["AgencyId"] != null) ? new Guid(Session["AgencyId"].ToString()) : (Guid?)null;
                const string command = "CHECKQUESTIONUPDATE";
                isResult = new MatrixData().CheckQuestions(question, command);
                if (isResult)
                {
                    returnResult = 2;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
                isResult = new MatrixData().UpdateQuestionType(question);
                if (isResult)
                {
                    returnResult = 1;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                clsError.WriteException(ex);
                //return Json("Error occured please try again.");
            }
            return(Json(returnResult, JsonRequestBehavior.AllowGet));
        }
Example #22
0
        public JsonResult UpdateMatrixType(long matrixId, string matrixType, long matrixValue)
        {
            bool isResult     = false;
            int  returnResult = 0;

            try
            {
                string queryCommand = "CHECKUPDATE";
                Matrix matrix       = new FingerprintsModel.Matrix();
                matrix.MatrixId    = matrixId;
                matrix.MatrixType  = matrixType;
                matrix.MatrixValue = matrixValue;
                matrix.UserId      = new Guid(Session["UserID"].ToString());
                matrix.AgencyId    = (Session["AgencyId"] != null) ? new Guid(Session["AgencyId"].ToString()) : (Guid?)null;

                isResult = new MatrixData().CheckMatrixType(matrix, queryCommand);
                if (isResult)
                {
                    returnResult = 2;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
                isResult = new MatrixData().UpdateMatrixType(matrix);
                if (isResult)
                {
                    returnResult = 1;
                    return(Json(returnResult, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception ex)
            {
                clsError.WriteException(ex);
                //return Json("Error occured please try again.");
            }
            return(Json(returnResult, JsonRequestBehavior.AllowGet));
        }
Example #23
0
        public static MatrixData SaveMatrix(MetaTileMap MetaTileMap, bool SingleSave = true,
                                            Vector3?Localboundarie1 = null, Vector3?Localboundarie2 = null, bool UseInstance = false)
        {
            if (SingleSave)
            {
                UnserialisedObjectReferences.Clear();
                MonoToID.Clear();
                FieldsToRefresh.Clear();
                IDStatic       = 0;
                IDmatrixStatic = 0;
            }

            MatrixData matrixData = new MatrixData();

            matrixData.ObjectMapData = SaveObjects(MetaTileMap, Localboundarie1, Localboundarie2, UseInstance);
            matrixData.TileMapData   = SaveTileMap(MetaTileMap, Localboundarie1, Localboundarie2);
            matrixData.MatrixName    = MetaTileMap.matrix.NetworkedMatrix.gameObject.name;
            matrixData.MatrixID      = IDmatrixStatic;
            matrixData.Location      = Math.Round(MetaTileMap.matrix.NetworkedMatrix.transform.localPosition.x, 2) + "┼" +
                                       Math.Round(MetaTileMap.matrix.NetworkedMatrix.transform.localPosition.y, 2) + "┼" +
                                       Math.Round(MetaTileMap.matrix.NetworkedMatrix.transform.localPosition.z, 2) + "┼";


            var Angles = MetaTileMap.matrix.NetworkedMatrix.transform.eulerAngles;

            matrixData.Location = matrixData.Location +
                                  Math.Round(Angles.x, 2) + "ø" +
                                  Math.Round(Angles.y, 2) + "ø" +
                                  Math.Round(Angles.z, 2) + "ø";


            IDmatrixStatic++;

            if (SingleSave)
            {
                foreach (var MFD in UnserialisedObjectReferences)
                {
                    if (MonoToID.ContainsKey(MFD.Item1))
                    {
                        MFD.Item2.AddID(MonoToID[MFD.Item1]);
                    }
                    else
                    {
                        Logger.LogError("Missing money behaviour in MonoToID");
                    }
                }

                UnserialisedObjectReferences.Clear();
                MonoToID.Clear();

                foreach (var FD in FieldsToRefresh)
                {
                    FD.Serialise();
                }

                FieldsToRefresh.Clear();
            }

            return(matrixData);
        }
Example #24
0
        public double rightOrWrong(MatrixData input, string OutFileName)
        {
            double[][] dataSet = input.Data.ToJagged().ToDoubleArray();
            // percentage correct using winner-takes all
            bool         result;
            StreamWriter writer = null;

            if (OutFileName.Trim() != "")
            {
                writer = new StreamWriter(OutFileName);
            }
            int numCorrect = 0;
            int numWrong   = 0;

            double[] xValues = new double[numInput];  // inputs
            double[] tValues = new double[numOutput]; // targets
            double[] yValues;                         // computed Y
            confusionMatrix = new int[numOutput, numOutput];
            //confusionMatrixCnt = 0;
            for (int i = 0; i < dataSet.Length; ++i)
            {
                Array.Copy(dataSet[i], xValues, numInput); // parse test data into x-values and t-values
                Array.Copy(dataSet[i], numInput, tValues, 0, numOutput);
                yValues = this.ComputeOutputs(xValues);
                int maxIndexOut      = MaxIndex(yValues); // which cell in yValues has largest value?
                int maxIndexExpected = MaxIndex(tValues); // which cell in yValues has largest value?
                if (maxIndexOut == maxIndexExpected)
                {
                    numCorrect++; result = true;
                }
                else
                {
                    numWrong++; result = false;
                }
                if (OutFileName.Trim() != "")
                {
                    string linez = "";
                    for (int j = 0; j < dataSet[i].Length; j++)
                    {
                        linez = linez + dataSet[i][j].ToString("F6") + " ";
                    }
                    linez = linez + "(" + maxIndexOut + " , " + maxIndexExpected + ") ";
                    if (result)
                    {
                        linez = linez + " Correct\r\n";
                    }
                    else
                    {
                        linez = linez + " Wrong \r\n";
                    }
                    writer.Write(linez);
                }
            }
            if (OutFileName.Trim() != "")
            {
                writer.Close();
            }
            return((numCorrect * 1.0) / (numCorrect + numWrong)); // ugly 2 - check for divide by zero note *100 for percent
        }
Example #25
0
        /// <summary>
        /// Execute
        /// </summary>
        /// <returns></returns>
        protected override bool Execute()
        {
            var           signature        = Utility.GetMD5(Utility.GetCustomConfig("APP_SALSA") + Utility.JsonSerialize_IgnoreLoopingReference(DTO.GetSignatureDTO()));
            dynamic       validationResult = new ExpandoObject();
            List <string> FrqValues        = new List <string>();

            PxStat.RequestLanguage.LngIsoCode = DTO.LngIsoCode;

            bool isValid = false;


            isValid = Validate();

            // }


            if (isValid)
            {
                validationResult.Signature         = signature;
                validationResult.FrqValueCandidate = FrqValues;
                Response.data = validationResult;



                return(true);
            }
            if (!isValid)
            {
                if (MatrixData != null)
                {
                    if (MatrixData.MainSpec.requiresResponse)
                    {
                        //cancel any validation errors and return an object to enable the user to choose which should be the time dimension
                        Matrix.Specification langSpec = MatrixData.GetSpecFromLanguage(DTO.LngIsoCode);
                        if (langSpec == null)
                        {
                            langSpec = MatrixData.MainSpec;
                        }

                        foreach (var v in langSpec.MainValues)
                        {
                            FrqValues.Add(v.Key);
                        }

                        validationResult.Signature         = null;
                        validationResult.FrqValueCandidate = FrqValues;
                        Response.data = validationResult;
                        return(true);
                    }
                }
                Response.data = validationResult;
                return(false);
            }


            //Response.error = Label.Get("error.validation");
            return(false);
        }
Example #26
0
        public void OnLoad(int x, int z)
        {
            MatrixData data = tile_matrix[x, z];

            if (data != null)
            {
                AddToMatrixList(data.data);
            }
        }
Example #27
0
        public SNeuralNetwork(int numberOfInputNodes, int numberOfHiddenNodes, int numberOfOutputNodes, double learningRate)
        {
            _learningRate = learningRate;

            _weightInputHidden  = new MatrixData(numberOfHiddenNodes, numberOfInputNodes);
            _weightHiddenOutput = new MatrixData(numberOfOutputNodes, numberOfHiddenNodes);

            RandomizeWeights();
        }
Example #28
0
        public override Matrix Backward(Matrix Actual, Matrix Expected, MatrixData data, int layerCount)
        {
            if (Actual.rows != Expected.rows || Actual.cols != Expected.cols)
            {
                throw new MatrixException("Actual Matrix does not have the same size as The Expected Matrix");
            }

            return(Actual - Expected);
        }
Example #29
0
        static void PI(int img)
        {
            System.Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            Image <Rgba32> image = Image.Load("data\\" + img + ".bmp");

            image.Mutate(ctx => ctx.Resize(image.Width / 8, image.Height / 8));

            double     ConversionFactor = 255 / (5 - 1);
            double     AverageValue;
            MatrixData m = new MatrixData(image.Width, image.Height);

            for (int r = 0; r < image.Width; r++)
            {
                for (int c = 0; c < image.Height; c++)
                {
                    AverageValue = (image[r, c].R + image[r, c].B + image[r, c].G) / 3;
                    double pv = ((AverageValue / ConversionFactor) + 0.5) * ConversionFactor;
                    if (pv < 200)
                    {
                        pv = 0;
                    }
                    m[r, c] = pv;
                }
            }

            m = m.HistEQ();
            int mp = (int)m.MeanIfPixel((s) => { return(s > 0); });

            for (int r = 0; r < image.Width; r++)
            {
                for (int c = 0; c < image.Height; c++)
                {
                    if (m[r, c] < mp)
                    {
                        m[r, c] = 0;
                    }
                }
            }
            m  = m.HistEQ();
            mp = (int)m.MeanIfPixel((s) => { return(s > 0); });
            m  = m.NormalizeAllBetween(mp, 255) * 255;

            m = m - vm;

            Tuple <int, int> centerBlob = new Tuple <int, int>(0, 0);
            Tuple <int, int> center     = new Tuple <int, int>(image.Width / 2, image.Height / 2);

            m = m.ToBinary(m.MeanIfPixel((s) => { return(s > 0); })).GetLargestBlob(ref centerBlob);
            System.Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));

            double         angle  = Math.Atan2(centerBlob.Item1 - center.Item2, centerBlob.Item1 - center.Item1) * (180 / Math.PI);
            double         dist   = Math.Abs(Math.Pow(centerBlob.Item1 - centerBlob.Item2, 2) + Math.Pow(center.Item1 - center.Item2, 2));
            List <dynamic> output = m.GetVectorizedMatrix().ToList();

            output.Add(angle);
            System.Console.WriteLine("image loaded");
        }
Example #30
0
        public string SetVal()
        {
            string output = "";

            _validationData = _exemplarData.CopyData(NumTrain + NumTest, 0, NumVal);
            output         += "Validation data:" + Environment.NewLine;
            output         += _validationData.Head().ToString(5, 16, 300, true);
            output         += Environment.NewLine + Environment.NewLine;
            return(output);
        }
Example #31
0
 public abstract void VisitMatrixData(MatrixData element);
Example #32
0
 public override void VisitMatrixData(MatrixData element)
 {
     String MatrixValues = element.getText();
       int rowsize = 0, colsize = 0;
       for (int i = 1; i < MatrixValues.LastIndexOf(']'); i++)
       {
       if (MatrixValues[i] == ',')
       {   colsize++;      continue; }
       if (MatrixValues[i] == '[')
        continue;
       if (MatrixValues[i] == ']')
       { rowsize++; continue; }
       int element_value = int.Parse(MatrixValues[i].ToString());
       mStack.Push(element_value);
       }
       colsize = (colsize / rowsize) + 1;
       int[,] mat = new int[rowsize, colsize];
       for (int i = rowsize - 1; i >= 0; i--)
       for (int j = colsize - 1; j >= 0; j--)
       {
           int result = mStack.Pop();
           mat[i, j] = result;
       }
       matStack.Push(mat);
 }
        private IMatrixData ProcessAplFiles(ProcessInfo processInfo, int nThreads, IList<MsRunImpl> aplfiles)
        {
            string tempFile = Path.Combine(FileUtils.GetTempFolder(), "spectraref.txt");
            if (File.Exists(tempFile)){
                File.Delete(tempFile);
            }
            IMatrixData matrix;
            StreamWriter writer = null;

            try{
                Enum[] enums = new Enum[]{spectraRef.raw_file, spectraRef.charge, spectraRef.scan_number, spectraRef.location, spectraRef.format, spectraRef.id_format, spectraRef.fragmentation, spectraRef.mz, spectraRef.index};
                IList<string> header = enums.Select(Constants.GetPattern).ToList();

                if (aplfiles == null || aplfiles.Count == 0){
                    return null;
                }

                int nTasks = aplfiles.Count;

                processInfo.Progress(0);
                processInfo.Status(string.Format("Read Andromeda peaklist files [{0}|{1}]", 0, nTasks));

                writer = new StreamWriter(tempFile);
                writer.WriteLine(StringUtils.Concat("\t", header));
                writer.WriteLine("#!{Type}" + StringUtils.Concat("\t", header.Select(x => "T")));

                ThreadDistributor distr = new ThreadDistributor(nThreads, nTasks,
                                                                x =>
                                                                ParseAplFile(aplfiles[x], writer,
                                                                             string.Format(
                                                                                 "Read Andromeda peaklist files [{0}|{1}]",
                                                                                 x + 1, nTasks), (x + 1)*100/nTasks,
                                                                             processInfo));
                distr.Start();

                processInfo.Status("Close all files");

                writer.Close();
                writer.Dispose();
                writer = null;

                processInfo.Progress(0);
                processInfo.Status("Create SpectraRef matrix");

                matrix = new MatrixData();
                LoadData(matrix, tempFile, processInfo);
            }
            catch (Exception ex){
                throw ex;
            }
            finally{
                if (writer != null){
                    writer.Close();
                }

                if (File.Exists(tempFile)){
                    File.Delete(tempFile);
                }
            }

            return matrix;
        }
        private IMatrixData ProcessDbFiles(ProcessInfo processInfo, int nThreads, IList<Database> databases)
        {
            string tempFile = Path.Combine(FileUtils.GetTempFolder(), "databaseref.txt");
            IMatrixData matrix;
            StreamWriter writer = null;

            try{
                processInfo.Progress(0);
                processInfo.Status(string.Format("Read database files [{0}|{1}]", 0, "?"));

                Enum[] enums = new Enum[] { databaseRef.file, databaseRef.source, databaseRef.specie, databaseRef.taxid, databaseRef.version, databaseRef.identifier };
                IList<string> header = enums.Select(Constants.GetPattern).ToList();

                if (databases == null || databases.Count == 0){
                    return null;
                }

                writer = new StreamWriter(tempFile);

                int nTasks = databases.Count;
                writer.WriteLine(StringUtils.Concat("\t", header));
                writer.WriteLine("#!{Type}" + StringUtils.Concat("\t", header.Select(x => "T")));

                ThreadDistributor distr = new ThreadDistributor(nThreads, nTasks,
                                                                x =>
                                                                ParseDatabase(writer, databases[x],
                                                                              string.Format(
                                                                                  "Read database files [{0}|{1}]",
                                                                                  x + 1, nTasks), (x + 1)*100/nTasks,
                                                                              processInfo));
                distr.Start();

                processInfo.Status("Close all files");

                writer.Close();
                writer.Dispose();
                writer = null;

                processInfo.Progress(0);
                processInfo.Status("Create DatabaseRef Matrix");

                matrix = new MatrixData();
                LoadData(matrix, tempFile, processInfo);
            }
            catch (Exception ex){
                throw ex;
            }
            finally{
                if (writer != null){
                    writer.Close();
                }

                if (File.Exists(tempFile)){
                    File.Delete(tempFile);
                }
            }

            return matrix;
        }