Esempio n. 1
0
        /// <summary>
        /// Determines what needs calculating.
        /// </summary>
        private void Thread_AddFilterToCalculationList([Const] Core core, [Const] ConfigurationMetric metric, [Const] IntensityMatrix vmatrix, [Const] DistanceMatrix dmatrix, [Const] EClustererStatistics statistics, [Const] Cluster[] realClusters, [Const] ObsFilter obsFilter, [MutableUnsafe] List <ForStat> needsCalculating, [MutableSafe] ProgressParallelHandler progP)
        {
            progP.SafeIncrement();

            IntensityMatrix vmatFiltered;
            DistanceMatrix  dmatFiltered;

            int[] filteredIndices;

            if (obsFilter == null)
            {
                vmatFiltered    = vmatrix;
                dmatFiltered    = dmatrix;
                filteredIndices = null;
            }
            else
            {
                filteredIndices = vmatrix.Columns.Which(z => obsFilter.Test(z.Observation)).ToArray();  // TODO: Multuple iteration
                vmatFiltered    = vmatrix.Subset(null, obsFilter, ESubsetFlags.None);
                dmatFiltered    = null;
            }

            Dictionary <Cluster, IReadOnlyList <double> > centreVectors = new Dictionary <Cluster, IReadOnlyList <double> >();

            foreach (Cluster cluster in realClusters)
            {
                /////////////////////
                // ASSIGNMENT STATS
                var centre = cluster.GetCentre(ECentreMode.Average, ECandidateMode.Assignments);
                IReadOnlyList <double> centreVector = centre.Count != 0 ? centre[0] : null;

                if (filteredIndices != null)
                {
                    centreVector = centreVector.Extract(filteredIndices);
                }

                centreVectors.Add(cluster, centreVector);
            }

            foreach (Assignment ass in Assignments)
            {
                ForStat f = new ForStat();
                f.Assignment = ass;
                f.ObsFilter  = obsFilter;

                if (filteredIndices != null)
                {
                    f.AssignmentVector = vmatFiltered.Vectors[ass.Vector.Index];
                }
                else
                {
                    f.AssignmentVector = ass.Vector;
                }

                f.ClusterVector = centreVectors[ass.Cluster];

                if (statistics.HasFlag(EClustererStatistics.SilhouetteWidth))
                {
                    if (dmatFiltered == null)
                    {
                        dmatFiltered = DistanceMatrix.Create(core, vmatrix, metric, ProgressReporter.GetEmpty());
                    }
                }

                f.DistanceMatrix = dmatFiltered;

                lock (needsCalculating)
                {
                    needsCalculating.Add(f);
                }
            }
        }
Esempio n. 2
0
        public ResultClusterer ExecuteAlgorithm(Core core, int isPreview, bool doNotCluster, ArgsClusterer args, ConfigurationClusterer tag, ProgressReporter prog, out IntensityMatrix vmatrixOut, out DistanceMatrix dmatrixOut)
        {
            IReadOnlyList <Peak> peaks;

            if (isPreview > 0 && isPreview < core.Peaks.Count)
            {
                List <Peak> p = core.Peaks.ToList();
                p.Shuffle();

                p = p.GetRange(0, Math.Min(isPreview, p.Count)).ToList();

                // Make sure any seed peaks are in the list
                foreach (Peak peak in tag.Args.Parameters.OfType <WeakReference <Peak> >().Select(par => (par).GetTargetOrThrow()))
                {
                    p.Insert(0, peak);
                    p.RemoveAt(p.Count - 1);
                }

                peaks = p;
            }
            else
            {
                peaks = core.Peaks;
            }

            // FILTER PEAKS
            PeakFilter pfilter = args.PeakFilter ?? PeakFilter.Empty;

            IntensityMatrix src = args.SourceMatrix;

            Filter <Peak> .Results filter = pfilter.Test(peaks);
            Cluster insigs;

            if (filter.Failed.Count == 0)
            {
                insigs = null;
            }
            else
            {
                insigs         = new Cluster("Insig", tag);
                insigs.States |= Session.Main.Cluster.EStates.Insignificants;

                // We still need the vmatrix for plotting later
                IntensityMatrix operational = src.Subset(args.PeakFilter, args.ObsFilter, ESubsetFlags.InvertPeakFilter);

                if (args.SplitGroups)
                {
                    operational = operational.SplitGroups();
                }

                for (int index = 0; index < operational.NumRows; index++)
                {
                    Vector p = new Vector(operational, index);
                    insigs.Assignments.Add(new Assignment(p, insigs, double.NaN));
                }
            }

            // CREATE VMATRIX AND FILTER OBSERVATIONS
            PeakFilter      temp    = new PeakFilter("filtered in", null, new[] { new PeakFilter.ConditionPeak(Filter.ELogicOperator.And, false, filter.Failed, Filter.EElementOperator.IsNot) });
            IntensityMatrix vmatrix = src.Subset(args.PeakFilter, args.ObsFilter, ESubsetFlags.None);

            if (args.SplitGroups)
            {
                vmatrix = vmatrix.SplitGroups();
            }

            prog.Enter("Creating distance matrix");
            DistanceMatrix dmatrix = RequiresDistanceMatrix ? DistanceMatrix.Create(core, vmatrix, args.Distance, prog) : null;

            prog.Leave();
            IEnumerable <Cluster> clusters;

            if (doNotCluster)
            {
                vmatrixOut = vmatrix;
                dmatrixOut = dmatrix;
                return(null);
            }

            // CLUSTER USING VMATRIX OR DMATRIX
            prog.Enter("Clustering");
            clusters = Cluster(vmatrix, dmatrix, args, tag, prog);
            prog.Leave();

            vmatrixOut = vmatrix;
            dmatrixOut = dmatrix;

            List <Cluster> result = new List <Cluster>();

            if (insigs != null)
            {
                result.Add(insigs);
            }

            result.AddRange(clusters);
            return(new ResultClusterer(result));
        }
Esempio n. 3
0
        private void UpdateScores()
        {
            StringBuilder title = new StringBuilder();

            IntensityMatrix sourceMatrix = this._selectedCorrection.Provide;
            IntensityMatrix source       = sourceMatrix.Subset(this._peakFilter, this._obsFilter, ESubsetFlags.None);

            double[] plsrResponseMatrix = null;

            this._lblPcaSource.Text = this._transposeToShowPeaks ? "Peaks" : "Observations";
            this.transposeToShowObservationsToolStripMenuItem.Checked = !this._transposeToShowPeaks;
            this.transposeToShowPeaksToolStripMenuItem.Checked        = this._transposeToShowPeaks;

            this._lblObs.Text         = this._obsFilter.ToString();
            this._lblPeaks.Text       = this._peakFilter.ToString();
            this._lblCorrections.Text = this._selectedCorrection.ToString();

            this._lblMethod.Text   = this._method.ToString().ToUpper();
            this.ctlTitleBar1.Text = this._method.ToUiString();

            this._lblPlsrSource.Visible = this._mnuPlsrSource.Visible = this._method == EMethod.Plsr;

            int corIndex = IVisualisableExtensions.WhereEnabled(this._core.Corrections).IndexOf(this._selectedCorrection);

            Column plsrColumn;

            this.GetSource(this._regressAgainst, out plsrColumn);

            this._lblPlsrSource.Text = plsrColumn.DisplayName;

            double[,] valueMatrix = this._transposeToShowPeaks ? new double[source.NumRows, source.NumCols] : new double[source.NumCols, source.NumRows];

            for (int row = 0; row < source.NumRows; row++)
            {
                Vector vector = source.Vectors[row];

                int obsIndex = 0;

                for (int col = 0; col < source.NumCols; col++)
                {
                    if (this._transposeToShowPeaks)
                    {
                        valueMatrix[row, col] = source.Values[row, col];
                    }
                    else
                    {
                        valueMatrix[col, row] = source.Values[row, col];
                    }

                    ++obsIndex;
                }
            }

            this._pcaPeaks        = source.Rows.Select(z => z.Peak).ToArray();
            this._pcaObservations = source.Columns.Select(z => z.Observation).ToArray();

            if (this._method == EMethod.Plsr)
            {
                plsrResponseMatrix = new double[valueMatrix.GetLength(0)];

                IEnumerable rows;

                if (this._transposeToShowPeaks)
                {
                    rows = this._pcaPeaks;
                }
                else
                {
                    rows = this._pcaObservations;
                }

                IEnumerator en  = rows.GetEnumerator();
                Factoriser  fac = new Factoriser();

                for (int n = 0; n < plsrResponseMatrix.Length; n++)
                {
                    en.MoveNext();
                    object row = plsrColumn.GetRow((Visualisable)en.Current);
                    plsrResponseMatrix[n] = fac.Factor(row);
                }
            }

            try
            {
                switch (this._method)
                {
                case EMethod.Pca:
                    FrmWait.Show(this, "PCA", "Updating scores", () =>
                                 Arr.Instance.Pca(valueMatrix, out this._scores, out this._loadings));
                    break;

                case EMethod.Plsr:
                    FrmWait.Show(this, "PLSR", "Updating scores", () =>
                                 Arr.Instance.Plsr(valueMatrix, plsrResponseMatrix, out this._scores, out this._loadings));
                    break;

                default:
                    throw new SwitchException(this._method);
                }

                this._errorMessage = null;
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("there is no package called 'pls'"))
                {
                    this._errorMessage = "The 'pls' library for R is not installed on your system. Please install that library to use the PLS feature.";
                    FrmMsgBox.ShowError(this, this._errorMessage);
                }
                else
                {
                    this._errorMessage = ex.Message;
                }

                this._scores   = null;
                this._loadings = null;
            }

            this.UpdatePlot();
        }