Пример #1
0
        public static CentroidsContract Create(Centroids centroids)
        {
            List<DataVectorContract> dataVectorContracts = 
                centroids.Points.Select(DataVectorContract.Create).ToList();

            return new CentroidsContract { DataVectorContracts = dataVectorContracts };
        }
Пример #2
0
        public void Start()
        {
            Random rand = new Random();

            // On commence par sélectionner un "point" au hasard pour chaque cluster
            for (int i = 0; i < m_clusters; i++)
            {
                Clusters.Add(new Cluster(
                                 i,
                                 new Vector4(
                                     rand.NextFloat(0.0f, 0.8f),
                                     rand.NextFloat(0.0f, 0.8f),
                                     rand.NextFloat(0.0f, 0.8F),
                                     1.0f),
                                 new Vector3(rand.NextFloat(-1.0f, 1.0f), rand.NextFloat(-1.0f, 1.0f), 0.0f)));

                Centroids.Add(new Entity(Entity));
                MeshRenderer meshrenderer = Centroids[i].AddComponent <MeshRenderer>();
                meshrenderer.material_ = new MaterialDX11();
                meshrenderer.material_.SetMainColor(Clusters[i].Color);
                meshrenderer.model_ = Quad.GetMesh();
                Centroids[i].transform_.SetScale(0.05f, 0.05f, 1.0f);
            }

            m_start = true;
        }
Пример #3
0
 public void UpdateCentroids()  // обновление списка центроидов - запись центроидов из каждого кластера в Centroids
 {
     Centroids.Clear();
     foreach (var c in Clusters)
     {
         Centroids.Add(c.Centroid);
     }
 }
Пример #4
0
 public void setCentroid(double[] cents)
 {
     if (cents.Length != Centroids.Dimension)
     {
         throw new System.IndexOutOfRangeException("[KMEANS]: SET CENTROID HAS INVALID DIMENSION");
     }
     Centroids.Add(cents);
 }
Пример #5
0
        public static CentroidsContract Create(Centroids centroids)
        {
            List <DataVectorContract> dataVectorContracts =
                centroids.Points.Select(DataVectorContract.Create).ToList();

            return(new CentroidsContract {
                DataVectorContracts = dataVectorContracts
            });
        }
Пример #6
0
 public void FillDistanceMatrix()  //заполнение матрицы расстояний - расстояния от элементов до центроидов по (i) - элементы, по (j) - центроиды
 {
     DistanceMatrix = new double[Elements.Count, Centroids.Count];
     for (int i = 0; i < Elements.Count; ++i)
     {
         for (int j = 0; j < Centroids.Count; ++j)
         {
             DistanceMatrix[i, j] = Elements.ElementAt(i).EuclideanDistance(Centroids.ElementAt(j));
         }
     }
 }
Пример #7
0
 private void GenerateCentroids()
 {
     for (int i = 0; i < this.Clusters; i++)
     {
         var randomVector = GetRandomVector();
         if (this.Centroids.FirstOrDefault(q => q.Data == randomVector) == null)
         {
             Centroids.Add(new Centroid(randomVector, i));
         }
     }
 }
Пример #8
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    Centroids.Clear();
                    Centroids = null;
                }
                disposedValue = true;
            }
        }
Пример #9
0
        public void RemoveCentroid()
        {
            if (ClusterCount == 0)
            {
                return;
            }
            GameObject removeRoidObj = Centroids[Centroids.Count - 1].GetGameObject();

            Centroids.RemoveAt(Centroids.Count - 1);
            UnityEngine.Object.Destroy(removeRoidObj);
            ClusterCount--;
        }
Пример #10
0
        private double MeanDistanceToKNearestCentroids(Centroid centroid)
        {
            List <double> distances = new List <double>();

            foreach (var examinedCentorid in Centroids.Where(e => centroid.Id != e.Id))
            {
                distances.Add(Euclides.CalculateDistance(examinedCentorid, centroid));
            }

            distances.Sort();

            return(distances.Where(e => e <= distances[NeighbourNumber]).Sum() / NeighbourNumber);
        }
Пример #11
0
        public ActionResult <KMeansResponse> Post([FromForm(Name = "file")] IFormFile file, [FromQuery] int numberOfClusters = 3)
        {
            var lines  = _getScvRows.GetLines(file);
            var points = lines.Transform();

            var result   = new KMeansResponse();
            var centroid = new Centroids();
            List <List <double> > clusterCenters = AlgorithmsUtils.MakeInitialSeeds(points, numberOfClusters);

            bool stop = false;
            Dictionary <List <double>, List <double> > clusters = null;

            while (!stop)
            {
                _logger.LogInformation($"Iteration = {iteration}");
                iteration++;

                clusters = KMeansAlgorithm.MakeClusters(points, clusterCenters);
                List <List <double> > oldClusterCenters = clusterCenters;
                //recalculete center of clusters
                clusterCenters = KMeansAlgorithm.RecalculateCoordinateOfClusterCenters(clusters, clusterCenters);

                if (ListUtils.IsListEqualsToAnother(clusterCenters, oldClusterCenters))
                {
                    int counter = 1;
                    stop             = true;
                    result.Centroids = new Centroids();
                    var list = new List <PointsAndClusterNumber>();
                    foreach (var center in clusterCenters)
                    {
                        var map = clusters.Where(point => ListUtils.IsListEqualsToAnother(point.Value, center));
                        foreach (var item in map)
                        {
                            var pointAndCluster = new PointsAndClusterNumber()
                            {
                                Point = new List <double>()
                            };
                            pointAndCluster.Point         = item.Key;
                            pointAndCluster.ClusterNumber = counter;
                            list.Add(pointAndCluster);
                        }
                        counter++;
                    }
                    result.PointsAndClusterNumber = list;
                    result.Centroids.Centroid     = clusterCenters;
                }
            }

            return(Ok(result));
        }
Пример #12
0
        // В качестве радиальной функции чаще всего применяется функция Гаусса. При размещении ее центра в точке  она может быть определена в сокращенной форме как:
        public double Gaussian(double[] input)
        {
            Func <int, double> func = j =>
            {
                var numerator = input[j] - Centroids[j];
                numerator *= numerator;
                var denominator = Widths[j] * Widths[j];
                return(numerator / denominator);
            };
            //для каждого центра считаем функцию гаусса, потом суммируем результаты
            var sum = Centroids.Select((c, j) => func(j)).Sum();

            return(Math.Pow(Math.E, -0.5 * sum));
        }
Пример #13
0
        public void AddCentroid()
        {
            GameObject newRoidObj = _graphController.GenerateCentroid();

            if (verbose)
            {
                Debug.Log("add centroid Cluster.Centroid created");
            }
            Centroids.Add(new Centroid(newRoidObj, this, _columnTypes, Centroids));
            if (verbose)
            {
                Debug.Log("add centroid Cluster.Centroid added to list");
            }
            ClusterCount++;
        }
Пример #14
0
        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>
        /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
        /// </returns>
        public override int GetHashCode()
        {
            var hash = 17;

            hash = 23 * hash + AmplitudeThreshold.GetHashCode();
            hash = 23 * hash + VarianceThreshold.GetHashCode();
            hash = 23 * hash + QualityIndex.GetHashCode();
            hash = 23 * hash + AmplitudeFilter.GetHashCode();
            hash = 23 * hash + VarianceFilter.GetHashCode();
            hash = 23 * hash + Centroids.GetHashCode();
            hash = 23 * hash + Partition.GetHashCode();
            hash = 23 * hash + Merged.GetHashCode();
            hash = 23 * hash + Subregions.GetHashCode();

            return(hash);
        }
Пример #15
0
        private int GetTheNearestCentroidsId(SamplePoint samplePoint)
        {
            int    nearestCentroidId = Centroids.First().Id;
            double nearestDistance   = Euclides.CalculateDistance(samplePoint, Centroids.First());

            foreach (var centroid in Centroids)
            {
                double distance = Euclides.CalculateDistance(samplePoint, centroid);
                if (distance < nearestDistance)
                {
                    nearestCentroidId = centroid.Id;
                    nearestDistance   = distance;
                }
            }

            return(nearestCentroidId);
        }
Пример #16
0
        private void RecalculateCentroids()
        {
            AzureHelper.LogPerformance(() =>
            {
                // Initialize the output blob
                CloudBlob writeBlob = AzureHelper.CreateBlob(jobData.JobID.ToString(), Guid.NewGuid().ToString());

                // Do the mapping and write the new blob
                using (ObjectStreamReader <Centroid> stream = new ObjectStreamReader <Centroid>(Centroids, Centroid.FromByteArray, Centroid.Size))
                {
                    var newCentroids = stream.Select(c =>
                    {
                        Point newCentroidPoint;
                        if (totalPointsProcessedDataByCentroid.ContainsKey(c.ID) && totalPointsProcessedDataByCentroid[c.ID].NumPointsProcessed != 0)
                        {
                            newCentroidPoint = totalPointsProcessedDataByCentroid[c.ID].PartialPointSum
                                               / (double)totalPointsProcessedDataByCentroid[c.ID].NumPointsProcessed;
                        }
                        else
                        {
                            newCentroidPoint = new Point();
                        }

                        c.X = newCentroidPoint.X;
                        c.Y = newCentroidPoint.Y;

                        return(c);
                    });

                    using (ObjectStreamWriter <Centroid> writeStream = new ObjectStreamWriter <Centroid>(writeBlob, point => point.ToByteArray(), Centroid.Size))
                    {
                        foreach (Centroid c in newCentroids)
                        {
                            writeStream.Write(c);
                        }
                    }
                }

                // Copy the contents of the new blob back into the old blob
                Centroids.CopyFromBlob(writeBlob);

                System.Diagnostics.Trace.TraceInformation("[ServerRole] Finished RecalculateCentroids(). Total points changed: {0}", TotalNumPointsChanged);

                ResetPointChangedCounts();
            }, jobData.JobID.ToString(), methodName: "RecalculateCentroids", iterationCount: IterationCount, points: Points.Uri.ToString(), centroids: Centroids.Uri.ToString(), machineID: MachineID);
        }
Пример #17
0
        public MultiDimensionalVector FindClosestCentroid(MultiDimensionalVector element)  //нахождение ближайшего центроида для элемента
        {
            int    indexElement         = Elements.IndexOf(element);
            int    indexClosestCentroid = 0;
            double min = double.MaxValue;

            for (int j = 0; j < Centroids.Count; ++j)
            {
                if (DistanceMatrix[indexElement, j] < min)
                {
                    min = DistanceMatrix[indexElement, j];
                    indexClosestCentroid = j;
                }
            }
            MultiDimensionalVector ClosestCentroid = Centroids.ElementAt(indexClosestCentroid);

            return(ClosestCentroid);
        }
Пример #18
0
        public void GenrateCentroids(int _centoridsNumber)
        {
            MaxCentroidShift = 1;
            Centroids.Clear();
            _excludedSampleIndexes.Clear();
            for (int i = 0; i < _centoridsNumber; i++)
            {
                int choosenSampleIndex;

                do
                {
                    choosenSampleIndex = Random.Next(SamplePoints.Count);
                } while (_excludedSampleIndexes.Contains(choosenSampleIndex));

                Centroids.Add(new Centroid(SamplePoints[choosenSampleIndex]));
                _excludedSampleIndexes.Add(choosenSampleIndex);
            }
        }
Пример #19
0
        public bool EqualPrevAndNewCentroids(double epsilon)  //сравнение новых вычисленных центроидов для каждого кластера Cluster.Centroid с имеющимися центроидами (Centroids), вычисление с погрешностью epsilon
        {
            bool equivalent = true;

            for (int i = 0; i < Centroids.Count; ++i)
            {
                //if (Centroids.ElementAt(i) == Clusters.ElementAt(i).Centroid)
                MultiDimensionalVector differentVector = Centroids.ElementAt(i) - Clusters.ElementAt(i).Centroid;
                foreach (var coord in differentVector)
                {
                    if (Math.Abs(coord) > epsilon)
                    {
                        equivalent = false;
                        break;
                    }
                }
            }
            return(equivalent);
        }
Пример #20
0
        public void GenerateCentroids()
        {
            Centroids.Clear();
            List <int> excludedSampleIndexes = new List <int>();

            for (int i = 0; i < HiddenNeuronsNumber; i++)
            {
                int choosenSampleIndex;

                do
                {
                    choosenSampleIndex = Random.Next(SamplePoints.Count);
                } while (excludedSampleIndexes.Contains(choosenSampleIndex));

                Centroids.Add(
                    new Centroid(choosenSampleIndex, SamplePoints[choosenSampleIndex]));
                excludedSampleIndexes.Add(choosenSampleIndex);
            }
        }
Пример #21
0
        private void ComputeNewCentroids()
        {
            int columnCount = Input.ColumnCount;

            for (int c = 0; c < Centroids.Count; c++)
            {
                int[]           clusterIndex = AssignedClusters.FindAllIndexof(c);
                List <double[]> clusterRows  = Input.ToRowArrays().Where((x, i) => clusterIndex.Contains(i)).ToList();

                List <double> newCentroid = new List <double>(Enumerable.Repeat(0.0, Input.ColumnCount));

                int clusterRowCount = clusterRows.Count;
                for (int j = 0; j < clusterRowCount; j++)
                {
                    for (int i = 0; i < columnCount; i++)
                    {
                        newCentroid[i] = (newCentroid[i] + clusterRows[j][i]) / 2; //vectorize this shit
                    }
                }
                Centroids[c] = CreateVector.Dense(newCentroid.ToArray());
            }
            Centroids.RemoveAll(x => x.Count == 0);
        }
Пример #22
0
        private void CalculateCentroids()
        {
            var centroids           = new List <double>();
            var minFq               = 10.0;
            var centroidSlicerBlock = 2048;

            foreach (var frame in Helpers.SplitToFrames(Samples, centroidSlicerBlock))
            {
                var fftFrame = Helpers.ApplyHammingWindow(frame, centroidSlicerBlock).Select(s => new Complex(s, 0)).ToArray();

                Fourier.Forward(fftFrame, FourierOptions.Matlab);

                double centroid = 0;
                double magsum   = 0;

                var ox =
                    fftFrame.Take(fftFrame.Length / 2)
                    .Select((s, i) => new { magnitude = s.Magnitude, idx = i })
                    .OrderByDescending(s => s.magnitude)
                    .ToArray();

                var totalenergy = ox.Sum(s => s.magnitude * s.magnitude);

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

                double energy = 0;
                int    index  = 0;

                while (energy < totalenergy * 0.6)
                {
                    harmonicEnergy.Add(new Tuple <double, int>(ox[index].magnitude, ox[index].idx));
                    energy += ox[index].magnitude * ox[index].magnitude;
                    index++;
                }

                foreach (var item in harmonicEnergy)
                {
                    var mag = item.Item1;

                    var fq = item.Item2 * samplerate / fftFrame.Length;

                    magsum += mag;

                    centroid += fq * mag;
                }

                if (magsum > double.Epsilon)
                {
                    centroid /= magsum;
                }

                centroids.Add(centroid);
            }

            Centroids = centroids.ToArray();

            var cids = Centroids.OrderByDescending(s => s).ToArray();

            var median = cids[cids.Length / 2];

            Console.WriteLine($@"{FileName}: centroid {median} Hz");
        }
Пример #23
0
        public float4[] Match(Image volume, float diameterAngstrom, float threshold, Func <int3, int, string, bool> progressCallback)
        {
            float PixelSizeBN       = PixelSize;
            int3  DimsRegionBN      = CubeNet.BoxDimensionsPredict;
            int3  DimsRegionValidBN = CubeNet.BoxDimensionsValidPredict;
            int   BorderBN          = (DimsRegionBN.X - DimsRegionValidBN.X) / 2;

            int3 DimsBN = volume.Dims;

            GPU.Normalize(volume.GetDevice(Intent.Read),
                          volume.GetDevice(Intent.Write),
                          (uint)volume.ElementsReal,
                          1);

            volume.FreeDevice();

            float[] Predictions = new float[DimsBN.Elements()];
            float[] Mask        = new float[DimsBN.Elements()];


            {
                int3   DimsPositions = (DimsBN + DimsRegionValidBN - 1) / DimsRegionValidBN;
                float3 PositionStep  = new float3(DimsBN - DimsRegionBN) / new float3(Math.Max(DimsPositions.X - 1, 1),
                                                                                      Math.Max(DimsPositions.Y - 1, 1),
                                                                                      Math.Max(DimsPositions.Z - 1, 1));

                int NPositions = (int)DimsPositions.Elements();

                int3[] Positions = new int3[NPositions];
                for (int p = 0; p < NPositions; p++)
                {
                    int Z = p / (DimsPositions.X * DimsPositions.Y);
                    int Y = (p - Z * DimsPositions.X * DimsPositions.Y) / DimsPositions.X;
                    int X = p % DimsPositions.X;
                    Positions[p] = new int3((int)(X * PositionStep.X + DimsRegionBN.X / 2),
                                            (int)(Y * PositionStep.Y + DimsRegionBN.Y / 2),
                                            (int)(Z * PositionStep.Z + DimsRegionBN.Z / 2));
                }

                float[][] PredictionTiles = Helper.ArrayOfFunction(i => new float[DimsRegionBN.Elements()], NPositions);

                int NGPUThreads = MaxThreads;

                Image[] Extracted = new Image[NGPUThreads];
                int     DeviceID  = GPU.GetDevice();

                int BatchesDone = 0;

                Helper.ForCPU(0, NPositions, NGPUThreads,

                              threadID =>
                {
                    GPU.SetDevice(DeviceID);
                    Extracted[threadID] = new Image(IntPtr.Zero, DimsRegionBN);
                },

                              (b, threadID) =>
                {
                    int GPUID       = threadID / NGPUThreads;
                    int GPUThreadID = threadID % NGPUThreads;

                    #region Extract and normalize windows

                    GPU.Extract(volume.GetDevice(Intent.Read),
                                Extracted[threadID].GetDevice(Intent.Write),
                                volume.Dims,
                                DimsRegionBN,
                                new int[] { Positions[b].X - DimsRegionBN.X / 2, Positions[b].Y - DimsRegionBN.Y / 2, Positions[b].Z - DimsRegionBN.Z / 2 },
                                1);

                    //GPU.Normalize(Extracted[threadID].GetDevice(Intent.Read),
                    //              Extracted[threadID].GetDevice(Intent.Write),
                    //              (uint)Extracted[threadID].ElementsReal,
                    //              1);

                    #endregion

                    //Extracted[threadID].WriteMRC("d_extracted.mrc", true);

                    #region Predict

                    long[] BatchArgMax;
                    float[] BatchProbability;
                    Predict(Extracted[threadID].GetDevice(Intent.Read),
                            GPUThreadID,
                            out BatchArgMax,
                            out BatchProbability);

                    //new Image(BatchArgMax.Select(v => (float)v).ToArray(), new int3(DimsRegionBN)).WriteMRC("d_labels.mrc", true);

                    for (int i = 0; i < BatchArgMax.Length; i++)
                    {
                        int Label         = (int)BatchArgMax[i];
                        float Probability = BatchProbability[i * NClasses + Label];

                        PredictionTiles[b][i] = (Label >= 1 && Probability >= threshold ? Probability : 0);
                    }

                    #endregion

                    lock (volume)
                        progressCallback?.Invoke(new int3(NPositions, 1, 1), ++BatchesDone, "");
                },

                              threadID =>
                {
                    int GPUID       = threadID / NGPUThreads;
                    int GPUThreadID = threadID % NGPUThreads;

                    Extracted[threadID].Dispose();
                });

                for (int z = 0; z < DimsBN.Z; z++)
                {
                    for (int y = 0; y < DimsBN.Y; y++)
                    {
                        for (int x = 0; x < DimsBN.X; x++)
                        {
                            int ClosestX  = (int)Math.Max(0, Math.Min(DimsPositions.X - 1, (int)(((float)x - DimsRegionBN.X / 2) / PositionStep.X + 0.5f)));
                            int ClosestY  = (int)Math.Max(0, Math.Min(DimsPositions.Y - 1, (int)(((float)y - DimsRegionBN.Y / 2) / PositionStep.Y + 0.5f)));
                            int ClosestZ  = (int)Math.Max(0, Math.Min(DimsPositions.Z - 1, (int)(((float)z - DimsRegionBN.Z / 2) / PositionStep.Z + 0.5f)));
                            int ClosestID = (ClosestZ * DimsPositions.Y + ClosestY) * DimsPositions.X + ClosestX;

                            int3 Position = Positions[ClosestID];
                            int  LocalX   = Math.Max(0, Math.Min(DimsRegionBN.X - 1, x - Position.X + DimsRegionBN.X / 2));
                            int  LocalY   = Math.Max(0, Math.Min(DimsRegionBN.Y - 1, y - Position.Y + DimsRegionBN.Y / 2));
                            int  LocalZ   = Math.Max(0, Math.Min(DimsRegionBN.Z - 1, z - Position.Z + DimsRegionBN.Z / 2));

                            Predictions[(z * DimsBN.Y + y) * DimsBN.X + x] = PredictionTiles[ClosestID][(LocalZ * DimsRegionBN.Y + LocalY) * DimsRegionBN.X + LocalX];
                        }
                    }
                }

                volume.FreeDevice();
            }

            #region Apply Gaussian and find peaks

            Image PredictionsImage = new Image(Predictions, new int3(DimsBN));
            PredictionsImage.WriteMRC("d_predictions.mrc", true);

            //Image PredictionsConvolved = PredictionsImage.AsConvolvedGaussian((float)options.ExpectedDiameter / PixelSizeBN / 6);
            //PredictionsConvolved.Multiply(PredictionsImage);
            //PredictionsImage.Dispose();

            //PredictionsImage.WriteMRC(MatchingDir + RootName + "_boxnet.mrc", PixelSizeBN, true);

            int3[] Peaks = PredictionsImage.GetLocalPeaks((int)(diameterAngstrom / PixelSizeBN / 4 + 0.5f), 1e-6f);
            PredictionsImage.Dispose();

            int BorderDist = (int)(diameterAngstrom / PixelSizeBN * 0.8f + 0.5f);
            Peaks = Peaks.Where(p => p.X > BorderDist &&
                                p.Y > BorderDist &&
                                p.Z > BorderDist &&
                                p.X < DimsBN.X - BorderDist &&
                                p.Y < DimsBN.Y - BorderDist &&
                                p.Z < DimsBN.Z - BorderDist).ToArray();

            #endregion

            #region Label connected components and get centroids

            List <float3> Centroids;
            List <int>    Extents;
            {
                List <List <int3> > Components = new List <List <int3> >();
                int[] PixelLabels = Helper.ArrayOfConstant(-1, Predictions.Length);

                foreach (var peak in Peaks)
                {
                    if (PixelLabels[DimsBN.ElementFromPosition(peak)] >= 0)
                    {
                        continue;
                    }

                    List <int3> Component = new List <int3>()
                    {
                        peak
                    };
                    int CN = Components.Count;

                    PixelLabels[DimsBN.ElementFromPosition(peak)] = CN;
                    Queue <int3> Expansion = new Queue <int3>(100);
                    Expansion.Enqueue(peak);

                    while (Expansion.Count > 0)
                    {
                        int3 pos        = Expansion.Dequeue();
                        int  PosElement = (int)DimsBN.ElementFromPosition(pos);

                        if (pos.X > 0 && Predictions[PosElement - 1] > 0 && PixelLabels[PosElement - 1] < 0)
                        {
                            PixelLabels[PosElement - 1] = CN;
                            Component.Add(pos + new int3(-1, 0, 0));
                            Expansion.Enqueue(pos + new int3(-1, 0, 0));
                        }
                        if (pos.X < DimsBN.X - 1 && Predictions[PosElement + 1] > 0 && PixelLabels[PosElement + 1] < 0)
                        {
                            PixelLabels[PosElement + 1] = CN;
                            Component.Add(pos + new int3(1, 0, 0));
                            Expansion.Enqueue(pos + new int3(1, 0, 0));
                        }

                        if (pos.Y > 0 && Predictions[PosElement - DimsBN.X] > 0 && PixelLabels[PosElement - DimsBN.X] < 0)
                        {
                            PixelLabels[PosElement - DimsBN.X] = CN;
                            Component.Add(pos + new int3(0, -1, 0));
                            Expansion.Enqueue(pos + new int3(0, -1, 0));
                        }
                        if (pos.Y < DimsBN.Y - 1 && Predictions[PosElement + DimsBN.X] > 0 && PixelLabels[PosElement + DimsBN.X] < 0)
                        {
                            PixelLabels[PosElement + DimsBN.X] = CN;
                            Component.Add(pos + new int3(0, 1, 0));
                            Expansion.Enqueue(pos + new int3(0, 1, 0));
                        }

                        if (pos.Z > 0 && Predictions[PosElement - DimsBN.X * DimsBN.Y] > 0 && PixelLabels[PosElement - DimsBN.X * DimsBN.Y] < 0)
                        {
                            PixelLabels[PosElement - DimsBN.X * DimsBN.Y] = CN;
                            Component.Add(pos + new int3(0, 0, -1));
                            Expansion.Enqueue(pos + new int3(0, 0, -1));
                        }
                        if (pos.Z < DimsBN.Z - 1 && Predictions[PosElement + DimsBN.X * DimsBN.Y] > 0 && PixelLabels[PosElement + DimsBN.X * DimsBN.Y] < 0)
                        {
                            PixelLabels[PosElement + DimsBN.X * DimsBN.Y] = CN;
                            Component.Add(pos + new int3(0, 0, 1));
                            Expansion.Enqueue(pos + new int3(0, 0, 1));
                        }
                    }

                    Components.Add(Component);
                }

                Centroids = Components.Select(c => MathHelper.Mean(c.Select(v => new float3(v)))).ToList();
                Extents   = Components.Select(c => c.Count).ToList();
            }

            List <int> ToDelete = new List <int>();

            // Hit test with crap mask
            //for (int c1 = 0; c1 < Centroids.Count; c1++)
            //{
            //    float2 P1 = Centroids[c1];
            //    if (MaskHitTest[(int)P1.Y * DimsBN.X + (int)P1.X] == 0)
            //    {
            //        ToDelete.Add(c1);
            //        continue;
            //    }
            //}

            for (int c1 = 0; c1 < Centroids.Count - 1; c1++)
            {
                float3 P1 = Centroids[c1];

                for (int c2 = c1 + 1; c2 < Centroids.Count; c2++)
                {
                    if ((P1 - Centroids[c2]).Length() < diameterAngstrom / PixelSizeBN / 1.5f)
                    {
                        int D = Extents[c1] < Extents[c2] ? c1 : c2;

                        if (!ToDelete.Contains(D))
                        {
                            ToDelete.Add(D);
                        }
                    }
                }
            }

            ToDelete.Sort();
            for (int i = ToDelete.Count - 1; i >= 0; i--)
            {
                Centroids.RemoveAt(ToDelete[i]);
                Extents.RemoveAt(ToDelete[i]);
            }

            #endregion

            //new Image(Predictions, DimsBN).WriteMRC("d_predictions.mrc", true);

            #region Write peak positions and angles into table

            return(Centroids.Select((c, i) => new float4(c.X, c.Y, c.Z, Extents[i])).ToArray());

            #endregion
        }
Пример #24
0
        /// <summary>
        /// Determines whether the specified <see cref="object" />, is equal to this instance.
        /// </summary>
        /// <param name="obj">The <see cref="object" /> to compare with this instance.</param>
        /// <returns>
        ///   <c>true</c> if the specified <see cref="object" /> is equal to this instance; otherwise, <c>false</c>.
        /// </returns>
        public override bool Equals(object obj)
        {
            if (!(obj is DivikResult))
            {
                return(false);
            }

            if (object.ReferenceEquals(objA: this, objB: obj))
            {
                return(true);
            }

            var other = (DivikResult)obj;

            if ((double.IsNaN(other.AmplitudeThreshold) != double.IsNaN(AmplitudeThreshold)) ||
                (!double.IsNaN(AmplitudeThreshold) && (other.AmplitudeThreshold != AmplitudeThreshold)))
            {
                return(false);
            }
            if ((double.IsNaN(other.VarianceThreshold) != double.IsNaN(VarianceThreshold)) ||
                (!double.IsNaN(VarianceThreshold) && (other.VarianceThreshold != VarianceThreshold)))
            {
                return(false);
            }
            if (other.QualityIndex != QualityIndex)
            {
                return(false);
            }
            if ((other.AmplitudeFilter != null) != (AmplitudeFilter != null))
            {
                return(false);
            }
            if ((other.AmplitudeFilter != null) &&
                (AmplitudeFilter != null) &&
                (other.AmplitudeFilter.Length != AmplitudeFilter.Length))
            {
                return(false);
            }
            if ((other.VarianceFilter != null) != (VarianceFilter != null))
            {
                return(false);
            }
            if ((other.VarianceFilter != null) &&
                (VarianceFilter != null) &&
                (other.VarianceFilter.Length != VarianceFilter.Length))
            {
                return(false);
            }
            if (other.Centroids.Length != Centroids.Length)
            {
                return(false);
            }
            if (other.Partition.Length != Partition.Length)
            {
                return(false);
            }
            if ((other.AmplitudeFilter != null) &&
                (AmplitudeFilter != null) &&
                !other.AmplitudeFilter.SequenceEqual(AmplitudeFilter))
            {
                return(false);
            }
            if ((other.VarianceFilter != null) &&
                (VarianceFilter != null) &&
                !other.VarianceFilter.SequenceEqual(VarianceFilter))
            {
                return(false);
            }
            if (!other.Partition.SequenceEqual(Partition))
            {
                return(false);
            }
            if ((other.Merged != null) != (Merged != null))
            {
                return(false);
            }
            if ((other.Merged != null) && (Merged != null) && !other.Merged.SequenceEqual(Merged))
            {
                return(false);
            }
            if (!other.Centroids.Cast <double>()
                .SequenceEqual(second: Centroids.Cast <double>()))
            {
                return(false);
            }
            if ((other.Subregions != null) != (Subregions != null))
            {
                return(false);
            }
            if ((other.Subregions != null) && (Subregions != null) && !other.Subregions.SequenceEqual(Subregions))
            {
                return(false);
            }

            return(true);
        }