Beispiel #1
0
            public void RMSETest()
            {
                /*
                 * 5  3  0  1
                 * 4  0  0  1
                 * 1  1  0  5
                 * 1  0  0  4
                 * 0  1  5  4
                 */
                DataMatrix R = GetSampleRatingMatrix();

                /*
                 * 3  3  0  1
                 * 4  0  0  5
                 * 1  2  0  5
                 * 1  0  0  4
                 * 0  1  5  4
                 */
                DataMatrix R_predicted = GetSampleRatingMatrix();

                R_predicted[0, 0] = 3;  // was 5
                R_predicted[2, 1] = 2;  // was 1
                R_predicted[1, 3] = 5;  // was 1

                double debug1 = RMSE.Evaluate(R, R_predicted);
                double debug2 = Math.Sqrt(21.0 / 13.0);

                Debug.Assert(debug1 == debug2);
            }
        // Get the relevant items of each user, i.e. rated no lower than the criteria
        public static Dictionary <int, List <int> > GetRelevantItemsByUser(DataMatrix R, double criteria)
        {
            int userCount = R.UserCount;
            int itemCount = R.ItemCount;
            Dictionary <int, List <int> > relevantItemsByUser = new Dictionary <int, List <int> >(userCount);

            // Select relevant items for each user
            foreach (Tuple <int, Vector <double> > user in R.Users)
            {
                int          userIndex     = user.Item1;
                RatingVector userRatings   = new RatingVector(user.Item2);
                List <int>   relevantItems = new List <int>();

                foreach (Tuple <int, double> element in userRatings.Ratings)
                {
                    int    itemIndex = element.Item1;
                    double rating    = element.Item2;
                    if (rating >= criteria)
                    {
                        // This is a relevant item
                        relevantItems.Add(itemIndex);
                    }
                }
                relevantItemsByUser[userIndex] = relevantItems;
            }

            return(relevantItemsByUser);
        }
Beispiel #3
0
        public FrameworkElement ConstructView(IBioLinkReport report, DataMatrix reportData, IProgressObserver progress)
        {
            TabularDataViewer viewer = new TabularDataViewer(report, reportData, progress);

            viewer.ContextMenuHandler = ContextMenuHandler;
            return(viewer);
        }
Beispiel #4
0
        public TabularDataViewer(IBioLinkReport report, DataMatrix data, IProgressObserver progress)
        {
            InitializeComponent();
            this.Data = data;
            _progress = progress;
            _report   = report;
            var view = new GridView();

            var columns = report.DisplayColumns;

            if (columns == null || columns.Count == 0)
            {
                columns = GenerateDefaultColumns(data);
            }

            var hcs = viewerGrid.Resources["hcs"] as Style;

            foreach (DisplayColumnDefinition c in columns)
            {
                DisplayColumnDefinition coldef = c;
                var column = new GridViewColumn {
                    Header = BuildColumnHeader(coldef), DisplayMemberBinding = new Binding(String.Format("[{0}]", data.IndexOf(coldef.ColumnName))), HeaderContainerStyle = hcs
                };
                view.Columns.Add(column);
            }

            lvw.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(GridViewColumnHeaderClickedHandler));

            lvw.MouseRightButtonUp += new System.Windows.Input.MouseButtonEventHandler(lvw_MouseRightButtonUp);

            lvw.ItemsSource = Data.Rows;
            this.lvw.View   = view;
        }
        private void AddTaxonRow(DataMatrix results, Taxon taxa, MultimediaLink link, string multimediaSource = "Taxon", int?materialId = null)
        {
            // Filter the rows...
            bool addRow = true;

            if (!string.IsNullOrWhiteSpace(_extensionFilter))
            {
                addRow = _extensionFilter.Equals(link.Extension, StringComparison.CurrentCultureIgnoreCase);
            }

            if (addRow && !string.IsNullOrWhiteSpace(_typeFilter))
            {
                addRow = _typeFilter.Equals(link.MultimediaType, StringComparison.CurrentCultureIgnoreCase);
            }

            if (addRow)
            {
                var row = results.AddRow();
                row[0]  = link.MultimediaID;
                row[1]  = taxa.TaxaID.Value;
                row[2]  = link;
                row[3]  = taxa.TaxaFullName;
                row[4]  = taxa.Rank;
                row[5]  = link.Name;
                row[6]  = link.Extension;
                row[7]  = link.MultimediaType;
                row[8]  = link.SizeInBytes;
                row[9]  = multimediaSource;
                row[10] = materialId;
            }
        }
Beispiel #6
0
        public static DataMatrix LoadMovieLens(string path)
        {
            DataMatrix R;

            Dictionary <int, int> userMap = new Dictionary <int, int>();   // Mapping from index in movielens file to index in matrix
            Dictionary <int, int> itemMap = new Dictionary <int, int>();   // Mapping from index in movielens file to index in matrix

            foreach (string line in File.ReadLines(path))
            {
                string[] tokens = line.Split('\t');
                int      t1     = int.Parse(tokens[0]);
                int      t2     = int.Parse(tokens[1]);
                if (!userMap.ContainsKey(t1))    // We update index only for new user
                {
                    userMap[t1] = userMap.Count; // The current size is just the current matrix index
                }
                if (!itemMap.ContainsKey(t2))    // We update index only for new item
                {
                    itemMap[t2] = itemMap.Count; // The current size is just the current matrix index
                }
            }

            R = new DataMatrix(userMap.Count, itemMap.Count);

            foreach (string line in File.ReadLines(path))
            {
                string[] tokens = line.Split('\t');
                int      uid    = userMap[int.Parse(tokens[0])];
                int      iid    = itemMap[int.Parse(tokens[1])];
                double   rating = double.Parse(tokens[2]);
                R[uid, iid] = rating;
            }
            return(R);
        }
Beispiel #7
0
        private static DataMatrix GetSampleRatingMatrix()
        {
            /*
             * 5  3  0  1
             * 4  0  0  1
             * 1  1  0  5
             * 1  0  0  4
             * 0  1  5  4
             */
            DataMatrix R = new DataMatrix(new SparseMatrix(5, 4));

            R[0, 0] = 5;
            R[0, 1] = 3;
            R[0, 3] = 1;
            R[1, 0] = 4;
            R[1, 3] = 1;
            R[2, 0] = 1;
            R[2, 1] = 1;
            R[2, 3] = 5;
            R[3, 0] = 1;
            R[3, 3] = 4;
            R[4, 1] = 1;
            R[4, 2] = 5;
            R[4, 3] = 4;

            return(R);
        }
        public ActionResult MatrixUser(DataMatrix problem)
        {
            if (problem.Dimension != 0)
            {
                problem.Distances = new int[problem.Dimension][];
                for (int i = 0; i < problem.Dimension; i++)
                {
                    problem.Distances[i] = new int[problem.Dimension];
                }
                problem.Flows = new int[problem.Dimension][];
                for (int i = 0; i < problem.Dimension; i++)
                {
                    problem.Flows[i] = new int[problem.Dimension];
                }
            }

            var problemResult = new DataMatrix()
            {
                Dimension = problem.Dimension,
                Distances = problem.Distances,
                Flows     = problem.Flows
            };

            return(View("MatrixUser", problemResult));
        }
Beispiel #9
0
        public static DataMatrix PredictRatings(PrefRelations PR_train, DataMatrix R_unknown,
                                                int maxEpoch, double learnRate, double regularizationOfUser, double regularizationOfItem, int factorCount)
        {
            // Latent features
            List <Vector <double> > P;
            List <Vector <double> > Q;

            LearnLatentFeatures(PR_train, maxEpoch, learnRate, regularizationOfUser, regularizationOfItem, factorCount, out P, out Q);

            List <Tuple <int, int, double> > R_predicted_cache = new List <Tuple <int, int, double> >();

            foreach (var data in R_unknown.Matrix.EnumerateIndexed(Zeros.AllowSkip))
            {
                int indexOfUser = data.Item1;
                int indexOfItem = data.Item2;
                R_predicted_cache.Add(new Tuple <int, int, double>(indexOfUser, indexOfItem, P[indexOfUser].DotProduct(Q[indexOfItem])));
            }

            DataMatrix R_predicted = new DataMatrix(SparseMatrix.OfIndexed(R_unknown.UserCount, R_unknown.ItemCount, R_predicted_cache));

            //new DataMatrix(R_unknown.Matrix.PointwiseMultiply(P.Multiply(Q)));
            // TODO: should we do this? should we put it into [0,1]??? Seems zero entries are also converted into 0.5!Normalize the result
            //R_predicted.Matrix.MapInplace(x => RecSys.Core.SpecialFunctions.InverseLogit(x), Zeros.AllowSkip);
            return(R_predicted);
        }
        private void generateGridData()
        {
            GridData = new DataMatrix();

            var lines         = new List <List <string> >();
            var columnConfigs = new List <ColumnConfig>();

            for (int i = 0; i < RowCount; i++)
            {
                var line = new List <string>();
                for (int j = 0; j < ColumnCount; j++)
                {
                    line.Add($"Line: {i + 1} Column: {j + 1}");

                    if (i == 0)
                    {
                        columnConfigs.Add(new ColumnConfig(EnumUtils.RandomValueOf <ItemType>()));
                    }
                }
                lines.Add(line);
            }

            GridData = new DataMatrix {
                Lines = lines, ColumnConfigurations = columnConfigs
            };
        }
Beispiel #11
0
        public string RunNMFbasedOMF(int maxEpoch, double learnRate, double regularization, int factorCount,
                                     List <double> quantizer, int topN = 0)
        {
            if (!ReadyForNumerical)
            {
                GetReadyForNumerical();
            }
            StringBuilder log = new StringBuilder();

            log.AppendLine(Utils.PrintHeading("NMF based OMF"));

            // NMF Prediction
            // Get ratings from scorer, for both train and test
            // R_all contains indexes of all ratings both train and test
            DataMatrix R_all = new DataMatrix(R_unknown.UserCount, R_unknown.ItemCount);

            R_all.MergeNonOverlap(R_unknown);
            R_all.MergeNonOverlap(R_train.IndexesOfNonZeroElements());
            Utils.StartTimer();
            DataMatrix R_predictedByNMF = NMF.PredictRatings(R_train, R_all, maxEpoch,
                                                             learnRate, regularization, factorCount);

            log.AppendLine(Utils.StopTimer());

            // OMF Prediction
            log.AppendLine(Utils.PrintHeading("Ordinal Matrix Factorization with NMF as scorer"));
            Utils.StartTimer();
            Dictionary <Tuple <int, int>, List <double> > OMFDistributionByUserItem;
            DataMatrix R_predicted;

            log.AppendLine(OMF.PredictRatings(R_train.Matrix, R_unknown.Matrix, R_predictedByNMF.Matrix,
                                              quantizer, out R_predicted, out OMFDistributionByUserItem));
            log.AppendLine(Utils.StopTimer());

            // Numerical Evaluation
            log.AppendLine(Utils.PrintValue("RMSE", RMSE.Evaluate(R_test, R_predicted).ToString("0.0000")));
            log.AppendLine(Utils.PrintValue("MAE", MAE.Evaluate(R_test, R_predicted).ToString("0.0000")));

            // TopN Evaluation
            if (topN != 0)
            {
                var topNItemsByUser = ItemRecommendationCore.GetTopNItemsByUser(R_predicted, topN);
                for (int n = 1; n <= topN; n++)
                {
                    log.AppendLine(Utils.PrintValue("NCDG@" + n, NCDG.Evaluate(RelevantItemsByUser, topNItemsByUser, n).ToString("0.0000")));
                }
                for (int n = 1; n <= topN; n++)
                {
                    log.AppendLine(Utils.PrintValue("MAP@" + n, MAP.Evaluate(RelevantItemsByUser, topNItemsByUser, n).ToString("0.0000")));
                }
            }

            // Save OMFDistribution to file
            if (!File.Exists(GetDataFileName("RatingOMF_")))
            {
                Utils.IO <Dictionary <Tuple <int, int>, List <double> > > .SaveObject(OMFDistributionByUserItem, GetDataFileName("RatingOMF_"));
            }

            return(log.ToString());
        }
Beispiel #12
0
        public string RunPrefKNN(int neighborCount, int topN = 10)
        {
            if (!ReadyForOrdinal)
            {
                GetReadyForOrdinal();
            }
            StringBuilder log = new StringBuilder();

            log.AppendLine(Utils.PrintHeading("PrefKNN"));

            // Prediction
            Utils.StartTimer();
            DataMatrix R_predicted = PrefUserKNN.PredictRatings(PR_train, R_unknown, neighborCount, UserSimilaritiesOfPref);

            log.AppendLine(Utils.StopTimer());

            // TopN Evaluation
            var topNItemsByUser = ItemRecommendationCore.GetTopNItemsByUser(R_predicted, topN);

            for (int n = 1; n <= topN; n++)
            {
                Utils.PrintValue("NCDG@" + n, NCDG.Evaluate(RelevantItemsByUser, topNItemsByUser, n).ToString("0.0000"));
            }
            for (int n = 1; n <= topN; n++)
            {
                log.AppendLine(Utils.PrintValue("MAP@" + n, MAP.Evaluate(RelevantItemsByUser, topNItemsByUser, n).ToString("0.0000")));
            }

            return(log.ToString());
        }
Beispiel #13
0
            public void GetPositionMatrix()
            {
                /*
                 * 5  3  0  1
                 * 4  0  0  1
                 * 1  1  0  5
                 * 1  0  0  4
                 * 0  1  5  4
                 */
                DataMatrix    R  = GetSampleRatingMatrix();
                PrefRelations PR = PrefRelations.CreateDiscrete(R);

                // act
                SparseMatrix positionMatrix = PR.GetPositionMatrix();

                // assert
                // How many ratings we have then how many positions we have
                Debug.Assert(positionMatrix.NonZerosCount == R.AsSparseMatrix.NonZerosCount);

                // Check if each rating has a corresponding position
                // we have check the count so don't need to check the oppsite
                foreach (Tuple <int, int, double> element in R.AsSparseMatrix.EnumerateIndexed(Zeros.AllowSkip))
                {
                    int    indexOfUser = element.Item1;
                    int    indexOfItem = element.Item2;
                    double rating      = element.Item3;

                    Debug.Assert(positionMatrix[indexOfUser, indexOfItem] != SparseMatrix.Zero);
                }
            }
Beispiel #14
0
        public static void GetPearsonOfColumns(DataMatrix R, int maxCountOfNeighbors,
                                               double strongSimilarityThreshold, out SimilarityData neighborsByObject,
                                               out HashSet <Tuple <int, int> > strongSimilarityIndicators)
        {
            ComputeSimilarities(R.Matrix.Transpose(), SimilarityMetric.PearsonRating, maxCountOfNeighbors,
                                strongSimilarityThreshold, out neighborsByObject, out strongSimilarityIndicators);

            // Debug
            for (int i = 0; i < R.ItemCount && i < 100; i++)
            {
                for (int j = 0; j < R.ItemCount && j < 100; j++)
                {
                    if (i == j)
                    {
                        continue;
                    }
                    double corr_ij = Correlation.Pearson((SparseVector)R.Matrix.Column(i), (SparseVector)R.Matrix.Column(j));
                    if (corr_ij > strongSimilarityThreshold)
                    {
                        Debug.Assert(strongSimilarityIndicators.Contains(new Tuple <int, int>(i, j)));
                        Debug.Assert(strongSimilarityIndicators.Contains(new Tuple <int, int>(j, i)));
                    }
                }
            }
        }
 internal void GenerateNewSolution()
 {
     HintsLeft      = Constants.HINTS_NUMBER;
     dataMatrix     = new DataMatrix(Settings.Default.MatrixSize, Settings.Default.MatrixSize);
     solutionMatrix = RandomMatrixGenerator.GetMatrix(Settings.Default.MatrixSize, Settings.Default.MatrixSize);
     //solutionMatrix = TestMatrixGenerator.GetMatrix(Settings.Default.MatrixSize, Settings.Default.MatrixSize);
 }
Beispiel #16
0
        private DataMatrix CreateDataMatrix(IEnumerable <Task> tasks)
        {
            DataMatrix dm = new DataMatrix();

            dm.Columns.Add(new MatrixColumn()
            {
                Name = " ", Width = 30, CellTemplate = CreateCellTemplate()
            });
            dm.Columns.Add(new MatrixColumn()
            {
                Name = " ", Width = 20
            });
            dm.Columns.Add(new MatrixColumn()
            {
                Name = "Description", Width = 300
            });
            dm.Columns.Add(new MatrixColumn()
            {
                Name = "File", Width = 100
            });
            dm.Columns.Add(new MatrixColumn()
            {
                Name = "Line", Width = 30
            });
            dm.Columns.Add(new MatrixColumn()
            {
                Name = "Column", Width = 30
            });

            int i = 1;

            foreach (Task task in tasks)
            {
                switch (task.TaskType)
                {
                case TaskType.Error:
                    if (ErrorTaskVisible)
                    {
                        dm.Rows.Add(CreateRow(task, i++));
                    }
                    break;

                case TaskType.Warning:
                    if (WarningTaskVisible)
                    {
                        dm.Rows.Add(CreateRow(task, i++));
                    }
                    break;

                case TaskType.Message:
                    if (MessageTaskVisible)
                    {
                        dm.Rows.Add(CreateRow(task, i++));
                    }
                    break;
                }
            }

            return(dm);
        }
        private DataMatrix BuildPointSetMatrix(PointSetViewModel vm)
        {
            if (vm == null)
            {
                return(null);
            }
            var result = new DataMatrix();

            result.Columns.Add(new MatrixColumn {
                Name = "Long"
            });
            result.Columns.Add(new MatrixColumn {
                Name = "Lat"
            });


            foreach (MapPoint p in vm.Model)
            {
                var row = result.AddRow();
                row[0] = p.Longitude;
                row[1] = p.Latitude;
            }

            return(result);
        }
 public TabDisplay(string name)
 {
     _locations = new List<string>();
     _types = new List<string>();
     _name = name;
     _checks = new DataMatrix<ICheckDisplay>();
 }
        public void Factorize()
        {
            var matrix = new double[][]
            {
                new double[] { 1, 1, 0, 1, 0, 0 },
                new double[] { 0, 1, 1, 1, 0, 0 },
                new double[] { 1, 0, 1, 0, 0, 0 },
                new double[] { 1, 1, 0, 0, 0, 0 },
                new double[] { 0, 0, 1, 1, 0, 1 },
                new double[] { 0, 1, 0, 0, 0, 1 },
                new double[] { 0, 0, 0, 0, 1, 1 },
            };

            var data = Enumerable.Range(0, 7)
                       .SelectMany(
                o => Enumerable.Range(0, 6),
                (o, p) => new { UserId = o.ToString(), ItemId = p.ToString(), Confidence = matrix[o][p] })
                       .Where(o => o.Confidence > 0)
                       .GroupBy(o => o.UserId)
                       .ToDictionary(o => o.Key, o => o.ToDictionary(p => p.ItemId, p => p.Confidence * 2));

            var parametersScenarios = new[]
            {
                new AlternatingLeastSquaresParameters(factors: 6, regularization: 0, iterations: 15, useConjugateGradient: true),
                new AlternatingLeastSquaresParameters(factors: 6, regularization: 0, iterations: 15, useConjugateGradient: false),
            };

            foreach (var parameters in parametersScenarios)
            {
                var recommender = AlternatingLeastSquares.Fit(DataMatrix.Load(data), parameters);

                Assert.True(recommender.Loss < 0.00001);
            }
        }
        protected override AlternatingLeastSquares CreateRecommender(Dictionary <string, Dictionary <string, double> > data)
        {
            var parameters  = new AlternatingLeastSquaresParameters(factors: 3, regularization: 0, iterations: 15, useConjugateGradient: true);
            var recommender = AlternatingLeastSquares.Fit(DataMatrix.Load(data), parameters);

            return(recommender);
        }
Beispiel #21
0
        public static double Evaluate(DataMatrix correctMatrix, DataMatrix predictedMatrix)
        {
            Debug.Assert(correctMatrix.NonZerosCount == predictedMatrix.NonZerosCount);
            double enumerator = (predictedMatrix.Matrix - correctMatrix.Matrix).FrobeniusNorm();

            return(enumerator / Math.Sqrt(correctMatrix.NonZerosCount));
        }
Beispiel #22
0
        private static void DrawGrid(Graphics g, DataMatrix matrix)
        {
            int  side            = Constants.CELL_SIDE;
            bool horizLinesDrawn = false;

            //draw cells
            for (int i = 0; i < matrix.Width; i++)
            {
                for (int j = 0; j < matrix.Height; j++)
                {
                    g.FillRectangle(GetCellBrush(matrix[i, j]), i * side, j * side, (i + 1) * side, (j + 1) * side);
                }
            }
            //draw grid
            for (int i = 0; i <= matrix.Width; i++)
            {
                for (int j = 0; j <= matrix.Height; j++)
                {
                    if (!horizLinesDrawn)
                    {
                        g.DrawLine(GetGridPen(j), 0, j * side, matrix.Width * side, j * side); //horizontal line
                    }
                }
                horizLinesDrawn = true;
                g.DrawLine(GetGridPen(i), i * side, 0, i * side, matrix.Height * side); //vertical line
            }
        }
Beispiel #23
0
        public void CreateDataMatrixCode(Worksheet clsWorksheet, Range range, string path)
        {
            for (int row = 2; row < range.Rows.Count; row++)
            {
                dynamic cellValue   = ((Range)clsWorksheet.Cells[row, 1]).Value;
                string  orderNumber = Convert.ToString(cellValue);

                DataMatrix datamatrix = new DataMatrix();
                datamatrix.Data        = orderNumber;
                datamatrix.DataMode    = DataMatrixDataMode.ASCII;
                datamatrix.ImageFormat = System.Drawing.Imaging.ImageFormat.Bmp;
                datamatrix.drawBarcode($"{path}\\{orderNumber}.bmp");

                Range       oRange    = range.Cells[row, 1];
                float       Left      = (float)((double)oRange.Left + 35);
                float       Top       = (float)((double)oRange.Top + 3);
                const float ImageSize = 13;
                FileInfo    file      = new FileInfo($"{path}\\{orderNumber}.bmp")
                {
                    IsReadOnly = false
                };
                FileInfo pathFileInfo = new FileInfo(path)
                {
                    IsReadOnly = false
                };

                string bmpPath = file.Name;
                clsWorksheet.Shapes.AddPicture($"{path}\\{bmpPath}",
                                               Microsoft.Office.Core.MsoTriState.msoFalse,
                                               Microsoft.Office.Core.MsoTriState.msoCTrue, Left, Top, ImageSize, ImageSize);
                File.Delete($"{path}\\{orderNumber}.bmp");
            }
        }
Beispiel #24
0
        public string RunPrefNMF(int maxEpoch, double learnRate, double regularizationOfUser,
                                 double regularizationOfItem, int factorCount, int topN = 10)
        {
            if (!ReadyForOrdinal)
            {
                GetReadyForOrdinal();
            }
            StringBuilder log = new StringBuilder();

            log.AppendLine(Utils.PrintHeading("PrefNMF"));

            // Prediction
            Utils.StartTimer();
            DataMatrix R_predicted = PrefNMF.PredictRatings(PR_train, R_unknown,
                                                            maxEpoch, learnRate, regularizationOfUser, regularizationOfItem, factorCount);

            log.AppendLine(Utils.StopTimer());

            // Evaluation
            var topNItemsByUser = ItemRecommendationCore.GetTopNItemsByUser(R_predicted, topN);

            for (int n = 1; n <= topN; n++)
            {
                Utils.PrintValue("NCDG@" + n, NCDG.Evaluate(RelevantItemsByUser, topNItemsByUser, n).ToString("0.0000"));
            }
            for (int n = 1; n <= topN; n++)
            {
                log.AppendLine(Utils.PrintValue("MAP@" + n, MAP.Evaluate(RelevantItemsByUser, topNItemsByUser, n).ToString("0.0000")));
            }

            return(log.ToString());
        }
        public override DataMatrix ExtractReportData(IProgressObserver progress)
        {
            if (progress != null)
            {
                progress.ProgressStart(string.Format("Retrieving Material records for {0}", Taxon.DisplayLabel), true);
            }

            var serviceMessage = new ServiceMessageDelegate((message) => {
                progress.ProgressMessage(message, 0);
            });

            Service.ServiceMessage += serviceMessage;
            DataMatrix matrix = Service.GetMaterialForTaxon(Taxon.TaxaID.Value);

            Service.ServiceMessage -= serviceMessage;

            if (progress != null)
            {
                progress.ProgressEnd(string.Format("{0} rows retreived", matrix.Rows.Count));
            }

            matrix.Columns.Add(new FormattedLatLongVirtualColumn(matrix));
            matrix.Columns.Add(new FormattedDateVirtualColumn(matrix));

            return(matrix);
        }
        private DataMatrix MergeItemMatrices(DataMatrix siteData, DataMatrix siteVisitData, DataMatrix materialData)
        {
            var result = new DataMatrix();

            // Create the final column set (based on the specified criteria)
            foreach (QueryCriteria c in Criteria)
            {
                result.Columns.Add(new MatrixColumn {
                    Name = c.Field.DisplayName
                });
            }

            // Now add the identity columns (as hidden columns, unless they already exist)
            string[] cols = { "Site Identifier", "Visit Identifier", "Material Identifier" };
            foreach (string col in cols)
            {
                if (result.IndexOf(col) < 0)
                {
                    result.Columns.Add(new MatrixColumn {
                        Name = col, IsHidden = true
                    });
                }
            }

            int          currentOrderNum = 1;
            LabelSetItem item            = null;

            while ((item = Items.FirstOrDefault((candidate) => { return(candidate.PrintOrder == currentOrderNum); })) != null)
            {
                if (item.NumCopies > 0)
                {
                    var row = result.AddRow();

                    if (item.SiteID > 0)
                    {
                        AddFieldData(row, item.SiteID, "Site Identifier", siteData);
                    }

                    if (item.VisitID > 0)
                    {
                        AddFieldData(row, item.VisitID, "Visit Identifier", siteVisitData);
                    }

                    if (item.MaterialID > 0)
                    {
                        AddFieldData(row, item.MaterialID, "Material Identifier", materialData);
                    }

                    if (item.NumCopies > 1)
                    {
                        CopyRow(result, row, item.NumCopies - 1);
                    }
                }

                currentOrderNum++;
            }

            return(result);
        }
        public ActionResult MatrixGenerated(DataMatrix problem)
        {
            if (problem.Dimension != 0)
            {
                problem.Distances = new int[problem.Dimension][];
                for (int i = 0; i < problem.Dimension; i++)
                {
                    problem.Distances[i] = new int[problem.Dimension];
                }
                problem.Flows = new int[problem.Dimension][];
                for (int i = 0; i < problem.Dimension; i++)
                {
                    problem.Flows[i] = new int[problem.Dimension];
                }
                for (int i = 0; i < problem.Dimension; i++)
                {
                    for (int j = 0; j < problem.Dimension; j++)
                    {
                        Random random = new Random();
                        int    value  = random.Next(1, 99);
                        if (i == j)
                        {
                            problem.Distances[i][j] = 0;
                        }
                        else
                        {
                            problem.Distances[i][j] = value;
                            problem.Distances[j][i] = value;
                        }
                    }
                }
                for (int i = 0; i < problem.Dimension; i++)
                {
                    for (int j = 0; j < problem.Dimension; j++)
                    {
                        Random random = new Random();
                        int    value  = random.Next(1, 99);
                        if (i == j)
                        {
                            problem.Flows[i][j] = 0;
                        }
                        else
                        {
                            problem.Flows[i][j] = value;
                            problem.Flows[j][i] = value;
                        }
                    }
                }
            }

            var problemResult = new DataMatrix()
            {
                Dimension = problem.Dimension,
                Distances = problem.Distances,
                Flows     = problem.Flows
            };

            return(View("MatrixGenerated", problemResult));
        }
Beispiel #28
0
 public Delta(DataMatrix data, SolutionMatrix solution)
 {
     ActualBestSolution = solution;
     Data        = data;
     SwapCounter = 0;
     ActualBestSolution.Score = Convert.ToInt32(RateSolution(solution.Solution.ToArray(), data));
     CalculateDeltaTable();
 }
        public static List <CellsBlock> CheckForOpenedBlocks(DataMatrix dataMatrix, DataMatrix solutionMatrix, int?row, int?col)
        {
            List <CellsBlock> dataList  = solutionMatrix.GetCountersList(row, col);
            List <CellsBlock> checkList = dataMatrix.GetCountersList(row, col);

            dataList.ForEach(block => CheckBlockOpened(row, col, block, checkList, dataMatrix));
            return(dataList);
        }
Beispiel #30
0
 public static void GetCosineOfColumns(DataMatrix R, int maxCountOfNeighbors,
                                       double strongSimilarityThreshold, out SimilarityData neighborsByObject,
                                       out HashSet <Tuple <int, int> > strongSimilarityIndicators)
 {
     // Just rotate the matrix
     ComputeSimilarities(R.Matrix.Transpose(), SimilarityMetric.CosineRating, maxCountOfNeighbors,
                         strongSimilarityThreshold, out neighborsByObject, out strongSimilarityIndicators);
 }
Beispiel #31
0
        public static void GetCosineOfRows(DataMatrix R, int maxCountOfNeighbors,
                                           double strongSimilarityThreshold, out SimilarityData neighborsByObject)
        {
            HashSet <Tuple <int, int> > foo;

            ComputeSimilarities(R.Matrix, SimilarityMetric.CosineRating, maxCountOfNeighbors,
                                strongSimilarityThreshold, out neighborsByObject, out foo);
        }
Beispiel #32
0
 /// <summary>
 /// Create new FloatMatrix.
 /// </summary>
 /// <remarks>
 /// Data of matrix are not copied, so when we change data in new FloatMatrix, we also change it in source.
 /// </remarks>
 /// <param name="dataMatrix">
 /// dataMatrix source matrix to create FloatMatrix.
 /// </param>
 public FloatMatrix(DataMatrix<float> dataMatrix)
 {
     _matrix = dataMatrix;
 }
Beispiel #33
0
 /// <summary>
 /// Create new FloatMatrix.
 /// </summary>
 /// <remarks>
 /// This constructor create copy of source matrix.
 /// </remarks>
 /// <param name="dataMatrix">
 /// Source matrix to create FloatMatrix.
 /// </param>
 public FloatMatrix(BaseDataMatrix dataMatrix)
 {
     _matrix = dataMatrix.Convert<float>();
 }
Beispiel #34
0
        /// <summary>
        /// Open and read FITS file.
        /// </summary>
        /// <param name="path">
        /// The path to FITS file.
        /// </param>
        public FitsFile(string path)
        {
            Stream stream = File.OpenRead(path);
            BinaryReader reader = new BinaryReader(stream);

            _header = new FitsHeader(reader);

            switch (_header.Bitpix)
            {
            case -64:
                {
                    DataMatrix<double> doubleMap = new DataMatrix<double>(_header.Dimensions);
                    byte[] doubleRaw = reader.ReadBytes(doubleMap.Size * 8);
                    Buffer.BlockCopy(doubleRaw, 0, doubleMap.Data, 0, doubleMap.Size * 8);
                    BaseTypeOperations.ReverseArray<double>(doubleMap.Data);
                    _data = doubleMap;
                    break;
                }
            case -32:
                {
                    DataMatrix<float> floatMap = new DataMatrix<float>(_header.Dimensions);
                    byte[] floatRaw = reader.ReadBytes(floatMap.Size * 4);
                    Buffer.BlockCopy(floatRaw, 0, floatMap.Data, 0, floatMap.Size * 4);
                    BaseTypeOperations.ReverseArray<float>(floatMap.Data);
                    _data = floatMap;
                    break;
                }
            case 8:
                {
                    DataMatrix<byte> byteMap = new DataMatrix<byte>(_header.Dimensions);
                    byte[] byteRaw = reader.ReadBytes(byteMap.Size);
                    Buffer.BlockCopy(byteRaw, 0, byteMap.Data, 0, byteMap.Size);
                    _data = byteMap;
                    break;
                }
            case 16:
                {
                    DataMatrix<short> shortMap = new DataMatrix<short>(_header.Dimensions);
                    byte[] shortRaw = reader.ReadBytes(shortMap.Size * 2);
                    Buffer.BlockCopy(shortRaw, 0, shortMap.Data, 0, shortMap.Size * 2);
                    BaseTypeOperations.ReverseArray<short>(shortMap.Data);
                    _data = shortMap;
                    break;
                }
            case 32:
                {
                    DataMatrix<int> intMap = new DataMatrix<int>(_header.Dimensions);
                    byte[] intRaw = reader.ReadBytes(intMap.Size * 4);
                    Buffer.BlockCopy(intRaw, 0, intMap.Data, 0, intMap.Size * 4);
                    BaseTypeOperations.ReverseArray<int>(intMap.Data);
                    _data = intMap;
                    break;
                }
            case 64:
                {
                    DataMatrix<long> longMap = new DataMatrix<long>(_header.Dimensions);
                    byte[] longRaw = reader.ReadBytes(longMap.Size * 8);
                    Buffer.BlockCopy(longRaw, 0, longMap.Data, 0, longMap.Size * 8);
                    BaseTypeOperations.ReverseArray<long>(longMap.Data);
                    _data = longMap;
                    break;
                }
            }

            reader.Close();
            stream.Close();
        }