Exemplo n.º 1
0
        public FeatureSet(List <IntensityPoint> intensityPointList)
        {
            var pointList = WaterShedMapUtil.BuildWatershedMap(intensityPointList);

            Smoother.Smooth(ref pointList);
            FindFeatures(pointList);
        }
Exemplo n.º 2
0
            public void UpdateLerp(System.Action onRecoilEnd, float deltaTime)
            {
                float targ = towardsRecoil ? 1.0f : 0.0f;

                if (curLerp != targ)
                {
                    smoother.speed = towardsRecoil ? speeds.x : speeds.y;
                    curLerp        = smoother.Smooth(curLerp, targ, deltaTime);
                }

                if (towardsRecoil)
                {
                    if (curLerp > .99f)
                    {
                        curLerp       = 1.0f;
                        towardsRecoil = false;
                    }
                }
                else
                {
                    if (curLerp < .01f)
                    {
                        curLerp  = 0.0f;
                        inRecoil = false;
                        onRecoilEnd();
                    }
                }
            }
Exemplo n.º 3
0
        public override void UpdateLoop(float deltaTime)
        {
            if (!active)
            {
                return;
            }
            if (debugTransform != null)
            {
                SetTargetPosition(debugTransform.position);
            }

            //rotate turret
            Vector3    targetPointTurret    = (targetPosition - swivelTransform.position).normalized;                         //get normalized vector toward target
            Quaternion targetRotationTurret = Quaternion.LookRotation(targetPointTurret, swivelTransform.up);                 //get a rotation for the turret that looks toward the target

            swivelTransform.rotation      = swivelSmoother.Smooth(swivelTransform.rotation, targetRotationTurret, deltaTime); //gradually turn towards the target at the specified turnSpeed
            swivelTransform.localRotation = Quaternion.Euler(0, swivelTransform.localRotation.eulerAngles.y, 0);

            //rotate barrels
            Vector3    targetPointBarrels    = (targetPosition - gun.transform.position).normalized;               //get a normalized vector towards the target
            Quaternion targetRotationBarrels = Quaternion.LookRotation(targetPointBarrels, gun.transform.up);      //get a rotation that looks at the target

            gun.transform.rotation = gunSmoother.Smooth(gun.transform.rotation, targetRotationBarrels, deltaTime); //gradually turn towards the target as the specified turnSpeed

            float x = gun.transform.localRotation.eulerAngles.x;

            if (x >= 180)
            {
                x -= 360;
            }

            gun.transform.localRotation = Quaternion.Euler(Mathf.Clamp(x, -maxLookAngle, maxLookAngle), 0, 0);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Creates a bitmap from this raster using the specified rasterSymbolizer.
        /// </summary>
        /// <param name="raster">The raster to draw to a bitmap.</param>
        /// <param name="rasterSymbolizer">The raster symbolizer to use for assigning colors.</param>
        /// <param name="rgbData">Byte values representing the ARGB image bytes.</param>
        /// <param name="stride">The stride</param>
        /// <param name="pm">The progress meter to use.</param>
        public static void DrawToBitmap(this IRaster raster, IRasterSymbolizer rasterSymbolizer, byte[] rgbData, int stride, ProgressMeter pm)
        {
            if (raster.DataType == typeof(int))
            {
                DrawToBitmapT(raster.ToRaster <int>(), rasterSymbolizer, rgbData, stride, pm);
            }
            else if (raster.DataType == typeof(float))
            {
                DrawToBitmapT(raster.ToRaster <float>(), rasterSymbolizer, rgbData, stride, pm);
            }
            else if (raster.DataType == typeof(short))
            {
                DrawToBitmapT(raster.ToRaster <short>(), rasterSymbolizer, rgbData, stride, pm);
            }
            else if (raster.DataType == typeof(byte))
            {
                DrawToBitmapT(raster.ToRaster <byte>(), rasterSymbolizer, rgbData, stride, pm);
            }
            else if (raster.DataType == typeof(double))
            {
                DrawToBitmapT(raster.ToRaster <double>(), rasterSymbolizer, rgbData, stride, pm);
            }
            else
            {
                DrawToBitmapT(raster, raster.NoDataValue, (row, col) => raster.Value[row, col], i => rgbData[i], (i, b) => rgbData[i] = b, rasterSymbolizer, stride, pm);

                if (rasterSymbolizer.IsSmoothed)
                {
                    var mySmoother = new Smoother(stride, raster.NumColumns, raster.NumRows, rgbData, pm.ProgressHandler);
                    mySmoother.Smooth();
                }
            }
        }
Exemplo n.º 5
0
        private static void DrawToBitmap(IRaster raster, IRasterSymbolizer rasterSymbolizer, IntPtr rgbData, int stride, ProgressMeter pm)
        {
            if (raster.DataType == typeof(int))
            {
                DrawToBitmapT(raster.ToRaster <int>(), rasterSymbolizer, rgbData, stride, pm);
            }
            else if (raster.DataType == typeof(float))
            {
                DrawToBitmapT(raster.ToRaster <float>(), rasterSymbolizer, rgbData, stride, pm);
            }
            else if (raster.DataType == typeof(short))
            {
                DrawToBitmapT(raster.ToRaster <short>(), rasterSymbolizer, rgbData, stride, pm);
            }
            else if (raster.DataType == typeof(byte))
            {
                DrawToBitmapT(raster.ToRaster <byte>(), rasterSymbolizer, rgbData, stride, pm);
            }
            else if (raster.DataType == typeof(double))
            {
                DrawToBitmapT(raster.ToRaster <double>(), rasterSymbolizer, rgbData, stride, pm);
            }
            else
            {
                DrawToBitmapT(raster, raster.NoDataValue, (row, col) => raster.Value[row, col], i => Marshal.ReadByte(rgbData, i), (i, b) => Marshal.WriteByte(rgbData, i, b), rasterSymbolizer, stride, pm);

                if (rasterSymbolizer.IsSmoothed)
                {
                    var mySmoother = new Smoother(stride, raster.NumColumns, raster.NumRows, rgbData, pm.ProgressHandler);
                    mySmoother.Smooth();
                }
            }
        }
 public void SmoothChromatograms(Dictionary <MSPeak, XYData> chromatograms, Smoother smoother)
 {
     foreach (var peak in chromatograms.Keys.ToList())
     {
         chromatograms[peak] = smoother.Smooth(chromatograms[peak]);
     }
 }
Exemplo n.º 7
0
    public Vector3 GetCurrentPosition()
    {
        var sourcePosition = XRNetworkClient.GetPosition(label);

        if (isTracked)
        {
            if (lastTracked && smoother != null)
            {
                return(smoother.Smooth(sourcePosition, ref lastPosition, Time.deltaTime));
            }
            else
            {
                return(sourcePosition);
            }
        }
        else
        {
            return(lastPosition);// + Vector3.Lerp(lastPosition, lastPosition + lastVelocity, Time.time - lastTrackedTime);
        }
    }
Exemplo n.º 8
0
        /// <summary>
        /// Creates a bitmap from this raster using the specified rasterSymbolizer.
        /// </summary>
        /// <param name="raster">The raster to draw to a bitmap</param>
        /// <typeparam name="T">Type of the raster.</typeparam>
        /// <param name="rasterSymbolizer">The raster symbolizer to use for assigning colors</param>
        /// <param name="rgbData">Byte values representing the ARGB image bytes</param>
        /// <param name="stride">The stride</param>
        /// <param name="pm">The progress meter to use.</param>
        /// <exception cref="ArgumentNullException">rasterSymbolizer cannot be null</exception>
        public static void DrawToBitmapT <T>(Raster <T> raster, IRasterSymbolizer rasterSymbolizer, byte[] rgbData, int stride, ProgressMeter pm)
            where T : struct, IEquatable <T>, IComparable <T>
        {
            DrawToBitmapT(raster, GetNoData(raster), (row, col) => raster.Data[row][col], i => rgbData[i], (i, b) => rgbData[i] = b, rasterSymbolizer, stride, pm);

            if (rasterSymbolizer.IsSmoothed)
            {
                var mySmoother = new Smoother(stride, raster.NumColumns, raster.NumRows, rgbData, pm.ProgressHandler);
                mySmoother.Smooth();
            }
        }
Exemplo n.º 9
0
        private static void DrawToBitmapT <T>(Raster <T> raster, IRasterSymbolizer rasterSymbolizer, IntPtr rgbData, int stride, ProgressMeter pm)
            where T : struct, IEquatable <T>, IComparable <T>
        {
            DrawToBitmapT(raster, GetNoData(raster), (row, col) => raster.Data[row][col], i => Marshal.ReadByte(rgbData, i), (i, b) => Marshal.WriteByte(rgbData, i, b), rasterSymbolizer, stride, pm);

            if (rasterSymbolizer.IsSmoothed)
            {
                var mySmoother = new Smoother(stride, raster.NumColumns, raster.NumRows, rgbData, pm.ProgressHandler);
                mySmoother.Smooth();
            }
        }
        private static void CreateMouthRiverChunkForNode(List <Vector2Int> nodes, Vector2Int riverMouth, List <Vector2Int> riverMouthChunks, Side edge, Vector2Int closestNode)
        {
            var previousNodeOfClosestNode = nodes[nodes.IndexOf(closestNode) - 1];
            var externalNodeOf            = GetExternalNodeOf(edge, riverMouth);
            var riverChunk = new List <Vector2Int> {
                previousNodeOfClosestNode, closestNode, riverMouth, externalNodeOf
            };
            var smoothedChunk = Smoother.Smooth(riverChunk);

            riverMouthChunks.AddRange(smoothedChunk);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Pulls all XICs needed to perform charge correlation
        /// </summary>
        /// <param name="peaksToCorrelate"></param>
        /// <param name="MZList"></param>
        /// <param name="run"></param>
        /// <param name="startScan"></param>
        /// <param name="stopScan"></param>
        /// <returns></returns>
        private XYData[] GetCorrelationXICs(int peaksToCorrelate, IEnumerable <double> MZList, Run run, int startScan, int stopScan)
        {
            var XICArray = new XYData[peaksToCorrelate];
            var index    = 0;

            foreach (var mz in MZList)
            {
                XICArray[index] = Smoother.Smooth(_chromGen.GenerateChromatogram(run, startScan, stopScan, mz, 20));
                index++;
            }
            return(XICArray);
        }
Exemplo n.º 12
0
        public void ErodeMap()
        {
            var eroder = new Eroder(heights, eroderSettings);

            foreach (int i in Enumerable.Range(0, 5000))
            {
                eroder.Erode();
            }

            var smoother = new Smoother(heights);

            heights = smoother.Smooth(4, 1.0f);
            GetComponent <Terrain>().terrainData.SetHeights(0, 0, heights);
        }
Exemplo n.º 13
0
    public override void UpdateLoop(float deltaTime)
    {
        if (m_Target == null)
        {
            return;
        }

        /*
         *  Move the rig towards target position.
         *
         *  maybe if enough distance in target transform
         */
        transform.position = followSmooth.Smooth(transform.position, m_Target.position, deltaTime);
    }
        void UpdateAimLerp(float deltaTime)
        {
            float target = isAiming ? 1.0f : 0.0f;

            if (aimPercent != target)
            {
                aimPercent = aimSmoother.Smooth(aimPercent, target, deltaTime);

                if (isAiming && aimPercent > (1.0f - aimEndThreshold))
                {
                    aimPercent = 1.0f;
                }
                else if (!isAiming && aimPercent < aimEndThreshold)
                {
                    aimPercent = 0.0f;
                }
            }
        }
        private void CanvasAnimatedControl_Draw(Microsoft.Graphics.Canvas.UI.Xaml.ICanvasAnimatedControl sender, Microsoft.Graphics.Canvas.UI.Xaml.CanvasAnimatedDrawEventArgs args)
        {
            using (var cpb = new CanvasPathBuilder(args.DrawingSession))
            {
                cpb.BeginFigure(0, height);
                average = averageSmoother.Smooth(AudioManager.AudioAverage);
                Vector2 p0 = new Vector2(Point0, height - Adjust(smoother1.Smooth(AudioManager.AudioSpec1)) * height);
                Vector2 p1 = new Vector2(Point1, height - Adjust(smoother2.Smooth(AudioManager.AudioSpec2)) * height);
                Vector2 p2 = new Vector2(Point2, height - Adjust(smoother3.Smooth(AudioManager.AudioSpec3)) * height);
                Vector2 p3 = new Vector2(Point3, height - Adjust(smoother4.Smooth(AudioManager.AudioSpec4)) * height);
                Vector2 p4 = new Vector2(Point4, height - Adjust(smoother5.Smooth(AudioManager.AudioSpec5)) * height);
                Vector2 p5 = new Vector2(Point5, height - Adjust(smoother6.Smooth(AudioManager.AudioSpec6)) * height);
                Vector2 p6 = new Vector2(Point6, height - Adjust(smoother7.Smooth(AudioManager.AudioSpec7)) * height);
                Vector2 p7 = new Vector2(Point7, height - Adjust(smoother8.Smooth(AudioManager.AudioSpec8)) * height);
                Vector2 p8 = new Vector2(Point8, height - Adjust(smoother9.Smooth(AudioManager.AudioSpec9)) * height);



                cpb.AddLine(p0);
                cpb.AddCubicBezier(GetC1(p0), GetC2(p1), p1);
                cpb.AddCubicBezier(GetC1(p1), GetC2(p2), p2);
                cpb.AddCubicBezier(GetC1(p2), GetC2(p3), p3);
                cpb.AddCubicBezier(GetC1(p3), GetC2(p4), p4);
                cpb.AddCubicBezier(GetC1(p4), GetC2(p5), p5);
                cpb.AddCubicBezier(GetC1(p5), GetC2(p6), p6);
                cpb.AddCubicBezier(GetC1(p6), GetC2(p7), p7);
                cpb.AddCubicBezier(GetC1(p7), GetC2(p8), p8);
                cpb.AddLine(new Vector2(p8.X, height));


                cpb.EndFigure(CanvasFigureLoop.Closed);
                CanvasLinearGradientBrush gradient = new CanvasLinearGradientBrush(sender, TransparentBlurple, Blurple)
                {
                    EndPoint   = new Vector2(0, height + 48),
                    StartPoint = new Vector2(0, -12)
                };
                var path = CanvasGeometry.CreatePath(cpb);
                //args.DrawingSession.DrawGeometry(path, Blurple, 1);
                args.DrawingSession.FillGeometry(path, gradient);
            }
        }
Exemplo n.º 16
0
 public FeatureSet(double[,] intensityBlock)
 {
     Smoother.Smooth(ref intensityBlock);
     FindFeatures(intensityBlock);
 }
Exemplo n.º 17
0
        public Point Detect(FaceRect face, Mat frame)
        {
            var model      = CurrentModel;
            var properties = ScreenProperties;

            if (face == null)
            {
                throw new ArgumentNullException("face");
            }
            if (frame == null || frame.IsEmpty)
            {
                throw new ArgumentNullException("frame");
            }
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }

            if (model.LeftRequired && (face.LeftEye == null || face.RightEye == null))
            {
                return(null);
            }
            if (model.RightRequired && face.RightEye == null)
            {
                return(null);
            }

            Profiler.Start("GazeDetect");

            if (!model.IsLoaded)
            {
                var timer = new System.Diagnostics.Stopwatch();
                timer.Start();
                model.Load();
                timer.Stop();
                Logger.Log($"Model[{model.Name}] load time: {timer.ElapsedMilliseconds} ms");
            }

            Point vecPt  = null;
            Point result = new Point(0, 0);
            Point pt     = new Point(0, 0);

            Profiler.Start("Gaze.Face.Cvt");
            Mat    leftRoi = null, rightRoi = null, faceRoi = null;
            Tensor leftTensor = null, rightTensor = null, faceTensor = null;

            if (model.LeftRequired)
            {
                leftRoi = face.LeftEye.RoiCropByPercent(frame, model.EyeCropPercent);
                leftRoi.Resize(new Size(model.EyeSize));
                var bufLen = (int)Math.Pow(model.EyeSize, 2) * 3;
                if (imgBufferLeft == null || imgBufferLeft.Length != bufLen)
                {
                    imgBufferLeft = new float[bufLen];
                }
                leftTensor = Tools.MatBgr2Tensor(leftRoi, model.ImageNormMode, -1, -1, new long[] { 1, model.EyeSize, model.EyeSize, 3 }, imgBufferLeft);
            }
            if (model.RightRequired)
            {
                rightRoi = face.RightEye.RoiCropByPercent(frame, model.EyeCropPercent);
                rightRoi.Resize(new Size(model.EyeSize));
                var bufLen = (int)Math.Pow(model.EyeSize, 2) * 3;
                if (imgBufferRight == null || imgBufferRight.Length != bufLen)
                {
                    imgBufferRight = new float[bufLen];
                }
                rightTensor = Tools.MatBgr2Tensor(rightRoi, model.ImageNormMode, -1, -1, new long[] { 1, model.EyeSize, model.EyeSize, 3 }, imgBufferRight);
            }
            if (model.FaceRequired)
            {
                faceRoi = face.ROI(frame);
                faceRoi.Resize(new Size(model.FaceSize));
                var bufLen = (int)Math.Pow(model.FaceSize, 2) * 3;
                if (imgBufferFace == null || imgBufferFace.Length != bufLen)
                {
                    imgBufferFace = new float[bufLen];
                }
                faceTensor = Tools.MatBgr2Tensor(faceRoi, model.ImageNormMode, -1, -1, new long[] { 1, model.FaceSize, model.FaceSize, 3 }, imgBufferFace);
            }
            Profiler.End("Gaze.Face.Cvt");

            Profiler.Start("Gaze.Face.Sess");
            Dictionary <string, Tensor> feedDict = new Dictionary <string, Tensor>();

            if (model.LeftRequired)
            {
                feedDict.Add(model.LeftOpName, leftTensor);
            }
            if (model.RightRequired)
            {
                feedDict.Add(model.RightOpName, rightTensor);
            }
            if (model.FaceRequired)
            {
                feedDict.Add(model.FaceOpName, faceTensor);
            }
            if (!string.IsNullOrEmpty(model.PhaseTrainOpName))
            {
                feedDict.Add(model.PhaseTrainOpName, new Tensor(false));
            }
            if (!string.IsNullOrEmpty(model.KeepProbOpName))
            {
                feedDict.Add(model.KeepProbOpName, new Tensor(model.KeepProb));
            }

            var fetch = model.Session.Run(new[] { model.OutputOpName }, feedDict);

            Profiler.End("Gaze.Face.Sess");

            var resultTensor = fetch[0];

            float[,] output = (float[, ])resultTensor.GetValue();

            result = new Point(output[0, 0], output[0, 1]);

            Profiler.Start("Gaze.Face.Dispose");
            leftTensor?.Dispose();
            rightTensor?.Dispose();
            faceTensor?.Dispose();
            leftRoi?.Dispose();
            rightRoi?.Dispose();
            faceRoi?.Dispose();
            Profiler.End("Gaze.Face.Dispose");

            var x = result.X * -1;
            var y = result.Y * -1;

            if (UseModification)
            {
                x = (x + OffsetX) * SensitiveX;
                y = (y + OffsetY) * SensitiveY;
            }

            vecPt = new Point(x, y);
            if (UseSmoothing && !Calibrator.IsCalibrating)
            {
                vecPt = Smoother.Smooth(vecPt);
            }

            Vector <double> vec = CreateVector.Dense(new double[] { vecPt.X, vecPt.Y, -1 });

            pt = face.SolveRayScreenVector(new Point3D(vec.ToArray()), properties);

            if (ClipToBound)
            {
                pt.X = Util.Clamp(pt.X, 0, ScreenProperties.PixelSize.Width);
                pt.Y = Util.Clamp(pt.Y, 0, ScreenProperties.PixelSize.Height);
            }

            face.GazeInfo = new EyeGazeInfo()
            {
                ScreenPoint = pt,
                Vector      = new Point3D(vecPt.X, vecPt.Y, -1),
                ClipToBound = ClipToBound,
            };

            Calibrator.Push(new CalibratingPushData(face));
            if (UseCalibrator)
            {
                Calibrator.Apply(face, ScreenProperties);
            }

            Profiler.End("GazeDetect");
            return(face.GazeInfo.ScreenPoint);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Draws each frame of the Canvas
        /// </summary>
        private void CanvasAnimatedControl_Draw(Microsoft.Graphics.Canvas.UI.Xaml.ICanvasAnimatedControl sender, Microsoft.Graphics.Canvas.UI.Xaml.CanvasAnimatedDrawEventArgs args)
        {
            if (Storage.Settings.ExpensiveRender)
            {
                if (!initailized)
                {
                    // If not initialized take one from to initialize
                    fftInitialize();
                }
                else
                {
                    using (var cpb = new CanvasPathBuilder(args.DrawingSession))
                    {
                        // Start curve at 0
                        cpb.BeginFigure(0, height);

                        // Initialize render points
                        Vector2 p0;
                        Vector2 p1;
                        Vector2 p2;
                        Vector2 p3;
                        Vector2 p4;
                        Vector2 p5;
                        Vector2 p6;
                        Vector2 p7;
                        Vector2 p8;

                        // Set render points
                        if (_audioIn)
                        {
                            average = averageSmoother.Smooth(AudioManager.AudioInAverage);
                            p0      = new Vector2(Point0, height - Adjust(smoother1.Smooth(AudioManager.AudioInSpec1)) * height);
                            p1      = new Vector2(Point1, height - Adjust(smoother2.Smooth(AudioManager.AudioInSpec2)) * height);
                            p2      = new Vector2(Point2, height - Adjust(smoother3.Smooth(AudioManager.AudioInSpec3)) * height);
                            p3      = new Vector2(Point3, height - Adjust(smoother4.Smooth(AudioManager.AudioInSpec4)) * height);
                            p4      = new Vector2(Point4, height - Adjust(smoother5.Smooth(AudioManager.AudioInSpec5)) * height);
                            p5      = new Vector2(Point5, height - Adjust(smoother6.Smooth(AudioManager.AudioInSpec6)) * height);
                            p6      = new Vector2(Point6, height - Adjust(smoother7.Smooth(AudioManager.AudioInSpec7)) * height);
                            p7      = new Vector2(Point7, height - Adjust(smoother8.Smooth(AudioManager.AudioInSpec8)) * height);
                            p8      = new Vector2(Point8, height - Adjust(smoother9.Smooth(AudioManager.AudioInSpec9)) * height);
                        }
                        else
                        {
                            average = averageSmoother.Smooth(AudioManager.AudioOutAverage);
                            p0      = new Vector2(Point0, height - Adjust(smoother1.Smooth(AudioManager.AudioOutSpec1)) * height);
                            p1      = new Vector2(Point1, height - Adjust(smoother2.Smooth(AudioManager.AudioOutSpec2)) * height);
                            p2      = new Vector2(Point2, height - Adjust(smoother3.Smooth(AudioManager.AudioOutSpec3)) * height);
                            p3      = new Vector2(Point3, height - Adjust(smoother4.Smooth(AudioManager.AudioOutSpec4)) * height);
                            p4      = new Vector2(Point4, height - Adjust(smoother5.Smooth(AudioManager.AudioOutSpec5)) * height);
                            p5      = new Vector2(Point5, height - Adjust(smoother6.Smooth(AudioManager.AudioOutSpec6)) * height);
                            p6      = new Vector2(Point6, height - Adjust(smoother7.Smooth(AudioManager.AudioOutSpec7)) * height);
                            p7      = new Vector2(Point7, height - Adjust(smoother8.Smooth(AudioManager.AudioOutSpec8)) * height);
                            p8      = new Vector2(Point8, height - Adjust(smoother9.Smooth(AudioManager.AudioOutSpec9)) * height);
                        }

                        // Render points
                        cpb.AddLine(p0);
                        cpb.AddCubicBezier(GetC1(p0), GetC2(p1), p1);
                        cpb.AddCubicBezier(GetC1(p1), GetC2(p2), p2);
                        cpb.AddCubicBezier(GetC1(p2), GetC2(p3), p3);
                        cpb.AddCubicBezier(GetC1(p3), GetC2(p4), p4);
                        cpb.AddCubicBezier(GetC1(p4), GetC2(p5), p5);
                        cpb.AddCubicBezier(GetC1(p5), GetC2(p6), p6);
                        cpb.AddCubicBezier(GetC1(p6), GetC2(p7), p7);
                        cpb.AddCubicBezier(GetC1(p7), GetC2(p8), p8);
                        cpb.AddLine(new Vector2(p8.X, height));
                        cpb.EndFigure(CanvasFigureLoop.Closed);

                        // Render
                        CanvasLinearGradientBrush gradient = new CanvasLinearGradientBrush(sender, TransparentBlurple, Blurple)
                        {
                            EndPoint   = new Vector2(0, height + 48),
                            StartPoint = new Vector2(0, -12)
                        };
                        var path = CanvasGeometry.CreatePath(cpb);
                        //args.DrawingSession.DrawGeometry(path, Blurple, 1);
                        args.DrawingSession.FillGeometry(path, gradient);
                    }
                }
            }
        }
Exemplo n.º 19
0
        private static void PaintColorSchemeToBitmapT <T>(this IRaster raster, T noData, Func <int, int, T> getValue, IRasterSymbolizer rasterSymbolizer, Bitmap bitmap, IProgressHandler progressHandler)
            where T : struct, IEquatable <T>, IComparable <T>
        {
            if (raster == null)
            {
                throw new ArgumentNullException(nameof(raster));
            }
            if (rasterSymbolizer == null)
            {
                throw new ArgumentNullException(nameof(rasterSymbolizer));
            }
            if (bitmap == null)
            {
                throw new ArgumentNullException(nameof(bitmap));
            }

            if (rasterSymbolizer.Scheme.Categories == null || rasterSymbolizer.Scheme.Categories.Count == 0)
            {
                return;
            }

            BitmapData bmpData;
            var        numRows    = raster.NumRows;
            var        numColumns = raster.NumColumns;
            var        rect       = new Rectangle(0, 0, numColumns, numRows);

            try
            {
                bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            }
            catch
            {
                var ms = new MemoryStream();
                bitmap.Save(ms, ImageFormat.MemoryBmp);
                ms.Position = 0;
                bmpData     = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            }

            // Prepare progress meter
            var pm = new ProgressMeter(progressHandler, SymbologyMessageStrings.DesktopRasterExt_PaintingColorScheme, numRows);

            if (numRows * numColumns < 100000)
            {
                pm.StepPercent = 50;
            }
            if (numRows * numColumns < 500000)
            {
                pm.StepPercent = 10;
            }
            if (numRows * numColumns < 1000000)
            {
                pm.StepPercent = 5;
            }

            var sets        = GetColorSets <T>(rasterSymbolizer.Scheme.Categories);
            var noDataColor = Argb.FromColor(rasterSymbolizer.NoDataColor);
            var alpha       = Argb.ByteRange(Convert.ToInt32(rasterSymbolizer.Opacity * 255));
            var ptr         = bmpData.Scan0;

            for (var row = 0; row < numRows; row++)
            {
                for (var col = 0; col < numColumns; col++)
                {
                    var  val = getValue(row, col);
                    Argb argb;
                    if (val.Equals(noData))
                    {
                        argb = noDataColor;
                    }
                    else
                    {
                        // Usually values are not random, so check neighboring previous cells for same color
                        int?srcOffset = null;
                        if (col > 0)
                        {
                            if (val.Equals(getValue(row, col - 1)))
                            {
                                srcOffset = Offset(row, col - 1, bmpData.Stride);
                            }
                        }

                        if (srcOffset == null && row > 0)
                        {
                            if (val.Equals(getValue(row - 1, col)))
                            {
                                srcOffset = Offset(row - 1, col, bmpData.Stride);
                            }
                        }

                        if (srcOffset != null)
                        {
                            argb = new Argb(Marshal.ReadByte(ptr, (int)srcOffset + 3), Marshal.ReadByte(ptr, (int)srcOffset + 2), Marshal.ReadByte(ptr, (int)srcOffset + 1), Marshal.ReadByte(ptr, (int)srcOffset));
                        }
                        else
                        {
                            var color = GetColor(sets, val);
                            argb = new Argb(alpha, color.R, color.G, color.B);
                        }
                    }

                    var offset = Offset(row, col, bmpData.Stride);
                    Marshal.WriteByte(ptr, offset, argb.B);
                    Marshal.WriteByte(ptr, offset + 1, argb.G);
                    Marshal.WriteByte(ptr, offset + 2, argb.R);
                    Marshal.WriteByte(ptr, offset + 3, argb.A);
                }

                pm.CurrentValue = row;
            }

            pm.Reset();
            if (rasterSymbolizer.IsSmoothed)
            {
                var mySmoother = new Smoother(bmpData.Stride, bmpData.Width, bmpData.Height, bmpData.Scan0, progressHandler);
                mySmoother.Smooth();
            }

            bitmap.UnlockBits(bmpData);
            rasterSymbolizer.ColorSchemeHasUpdated = true;
        }
Exemplo n.º 20
0
        /// <summary>
        /// The <see cref="PublishFrame"/> method for the <see cref="PhasorSignalConditioner"/> adapter.
        /// </summary>
        /// <param name="frame">The frame of incoming measurements</param>
        /// <param name="index">An integer</param>
        protected override void PublishFrame(IFrame frame, int index)
        {
            // Hang on to the timestamps so we can reattach them to their original outgoing frames
            if (m_timestampQueue.Count < MAX_BUFFER_SIZE)
            {
                m_timestampQueue.Add(frame.Timestamp);
            }
            else if (m_timestampQueue.Count == MAX_BUFFER_SIZE)
            {
                m_timestampQueue.RemoveAt(BUFFER_TOP_POSITION);
                m_timestampQueue.Add(frame.Timestamp);
            }

            // Map the input measurments to the phasor
            foreach (IMeasurement measurement in frame.Measurements.Values)
            {
                if (measurement.Key.ToString().Equals(m_inputPhasor.MagnitudeKey))
                {
                    m_inputPhasor.Magnitude = measurement.Value;
                }
                else if (measurement.Key.ToString().Equals(m_inputPhasor.AngleKey))
                {
                    m_inputPhasor.AngleInDegrees = measurement.Value;
                }
            }

            // Smooth the phasor measurement
            m_signalSmoother.Smooth(m_inputPhasor);

            // Prepare to clone the output measurements
            IMeasurement[] outputMeasurements = OutputMeasurements;

            // Create a list of IMeasurement objects for the output;
            List <IMeasurement> output = new List <IMeasurement>();

            // Clone the measurements for output
            foreach (IMeasurement measurement in outputMeasurements)
            {
                if (measurement.Key.ToString().Equals(m_magnitudeOutputKey))
                {
                    if (m_allowTimestampReassignment)
                    {
                        output.Add(Measurement.Clone(measurement, m_signalSmoother.Output.Magnitude, frame.Timestamp));
                    }
                    else
                    {
                        output.Add(Measurement.Clone(measurement, m_signalSmoother.Output.Magnitude, m_timestampQueue[BUFFER_TOP_POSITION]));
                    }
                }
                else if (measurement.Key.ToString().Equals(m_angleOutputKey))
                {
                    if (m_allowTimestampReassignment)
                    {
                        output.Add(Measurement.Clone(measurement, m_signalSmoother.Output.AngleInDegrees, frame.Timestamp));
                    }
                    else
                    {
                        output.Add(Measurement.Clone(measurement, m_signalSmoother.Output.AngleInDegrees, m_timestampQueue[BUFFER_TOP_POSITION]));
                    }
                }
            }

            OnNewMeasurements(output);
        }
        public void BuildRiver()
        {
            var        river         = new List <Vector2Int>();
            var        sourceEdge    = EnumRangdomValueGetter.Get <Side>();
            var        source        = GetRandomPointOnEdge(sourceEdge);
            Vector2Int preSourceNode = GetExternalNodeOf(sourceEdge, source);

            var riverNodesCount = _random.Next(4, 6);

            _riverNodes = new List <Vector2Int> {
                preSourceNode, source
            };

            _riverMouths = new Dictionary <Vector2Int, Side>();
            for (int i = 1; i < riverNodesCount + 2; i++)
            {
                AddNode(sourceEdge, i, riverNodesCount);
            }

            switch (sourceEdge)
            {
            case Side.Top:
                _riverNodes = _riverNodes.OrderByDescending(a => a.y).ToList();
                break;

            case Side.Right:
                _riverNodes = _riverNodes.OrderByDescending(a => a.x).ToList();
                break;

            case Side.Bottom:
                _riverNodes = _riverNodes.OrderBy(a => a.y).ToList();
                break;

            case Side.Left:
                _riverNodes = _riverNodes.OrderBy(a => a.x).ToList();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var riverMouthsCount = _random.Next(1, 4);
            var riverMouthChunks = new List <Vector2Int>();


            var mainRiverMouth = _riverMouths.First().Key;

            _riverNodes.Add(mainRiverMouth);
            _riverNodes.Add(GetExternalNodeOf(_riverMouths[mainRiverMouth], mainRiverMouth));

            for (int i = 0; i < riverMouthsCount; i++)
            {
                if (i == 0)
                {
                }
                else
                {
                    float      distanceToClosestMouth = 0f;
                    Vector2Int mouth = new Vector2Int(0, 0);
                    Side       edge  = Side.Bottom;

                    int counter = 0;
                    while (distanceToClosestMouth < _mapChanger.XResolution / 8f)
                    {
                        while (edge == sourceEdge)
                        {
                            edge = EnumRangdomValueGetter.Get <Side>();
                        }
                        mouth = GetRandomPointOnEdge(edge);
                        var closestMouth = GetClosestNode(mouth, _riverMouths.Select(a => a.Key).ToList());
                        distanceToClosestMouth = Vector2Int.Distance(closestMouth, mouth);
                        ++counter;
                        if (counter == 25)
                        {
                            break;
                        }
                    }

                    _riverMouths[new Vector2Int(mouth.x, mouth.y)] = edge;
                }
            }


            var rivewrMouthsToBeProcessed = _riverMouths.Select(a => a.Key).Where(n => n != mainRiverMouth).ToList();

            foreach (var riverMouth in rivewrMouthsToBeProcessed)
            {
                CreateMouthRiverChunk(_riverNodes, riverMouth, riverMouthChunks);
            }


            river.AddRange(_riverNodes);
            river = Smoother.Smooth(river);
            river.AddRange(riverMouthChunks);

            foreach (var vector2Int in _riverNodes)
            {
                _mapChanger.ColorTile(vector2Int.x, vector2Int.y, Color.red);
            }

            foreach (var vector2Int in _riverMouths.Select(a => a.Key))
            {
                _mapChanger.ColorTile(vector2Int.x, vector2Int.y, Color.green);
            }

            foreach (var tile in river)
            {
                _mapChanger.ColorTileExact(tile.x, tile.y, Color.blue);
            }
        }
Exemplo n.º 22
0
        protected override void Initialize()
        {
            graphics.PreferMultiSampling       = true;
            graphics.PreferredBackBufferWidth  = WINDOWED_WIDTH;
            graphics.PreferredBackBufferHeight = WINDOWED_HEIGHT;
            graphics.IsFullScreen = false;
            graphics.ApplyChanges();

            spriteBatch = new SpriteBatch(GraphicsDevice);
            console     = new GameConsole(this, spriteBatch, new GameConsoleOptions()
            {
                OpenOnWrite = false,
                Prompt      = ">",
                Height      = 500,
                ToggleKey   = Keys.Escape
            });

            console.AddCommand("load",
                               args =>
            {
                missionFile = "../../../../../missions/" + args[0] + ".json";
                ClearWorld();
                InitSim(false);
                return("Mission loaded.");
            }, "Load a mission file");

            console.AddCommand("experiment",
                               args =>
            {
                if (args[0] == "random")
                {
                    new SmootherExperiment(this, expFile, 100);
                }
                else if (args[0] == "parking")
                {
                    new ParkingExperiment(this, world, expFile);
                }
                else
                {
                    return("Experiment not found.");
                }

                return("Experiment started.");
            }, "Run an experiment");

            console.AddCommand("antialias",
                               args =>
            {
                graphics.PreferMultiSampling = !graphics.PreferMultiSampling;
                graphics.ApplyChanges();
                return("Antialias " + (graphics.PreferMultiSampling ? "on" : "off"));
            }, "Toggles antialias");

            console.AddCommand("debug",
                               args =>
            {
                showDebugInfo = !showDebugInfo;
                return("Debug " + (showDebugInfo ? "on" : "off"));
            }, "Toggles the debug info");

            console.AddCommand("dashboard",
                               args =>
            {
                showDashboard = !showDashboard;
                return("Dashboard " + (showDashboard ? "on" : "off"));
            }, "Toggles the dashboard");

            console.AddCommand("param",
                               args =>
            {
                if (args.Length < 1)
                {
                    return("");
                }

                switch (args[0].ToLower())
                {
                case "smoother":
                    return(Smoother.HandleParamCommand(args));

                default:
                    return("");
                }
            }, "Prints or updates parameters");

            console.AddCommand("smooth",
                               args =>
            {
                if (pathSmoothDone)
                {
                    bg = new Thread(() =>
                    {
                        DateTime now  = DateTime.Now;
                        smoothedPath  = Smoother.Smooth(astar.Path, grid);
                        int numUnsafe = Smoother.UnsafeIndices != null ? Smoother.UnsafeIndices.Count : 0;
                        console.WriteLine("Smoothing Time: " + Math.Round((DateTime.Now - now).TotalMilliseconds) + " ms (" + Smoother.NumIterations + " iterations, " + Smoother.Change + "m, " + numUnsafe + " unsafe points)");
                        controller = new StanleyFSMController(smoothedPath, goalPose);
                    });
                    bg.IsBackground = true;
                    bg.Priority     = ThreadPriority.Lowest;
                    bg.Start();
                }

                return("");
            }, "Smooths the path using the current parameters");

            console.AddCommand("smoothing",
                               args =>
            {
                smoothing = !smoothing;
                return("Smoothing " + (smoothing ? "on" : "off"));
            }, "Toggles smoothing"
                               );

            dashboard       = new Dashboard(this);
            world           = new World(Vector2.Zero);
            car             = new Car(world, new Pose());
            camera          = new Camera(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 1000f);
            camera.Position = new Vector3(75f, 75f, 180f);

            base.Initialize();
        }
Exemplo n.º 23
0
        public void InitSim(bool autoStart, bool smoothingOn, Mission mission)
        {
            gridDone          = false;
            pathDone          = false;
            pathSmoothDone    = false;
            pathSearching     = false;
            pathSearchingDone = false;
            autoDrive         = true;
            run             = false;
            isCollided      = false;
            currentControls = new CarControls(0f, 0f, 0f);

            if (camera == null)
            {
                camera          = new Camera(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 1000f);
                camera.Position = new Vector3(75f, 75f, 180f);
            }

            startPose                  = mission.Start;
            goalPose                   = mission.Goal;
            HybridAStar.Epsilon        = mission.AStarEpsilon;
            HybridAStar.GridResolution = mission.AStarGridResolution;
            HybridAStar.SafetyFactor   = 1.5f;
            HybridAStar.Reset();

            car  = new Car(world, startPose);
            grid = new ObstacleGrid(world, mission.Environment);

            car.Body.OnCollision += new OnCollisionEventHandler(OnCollision);

            gridDone          = false;
            pathDone          = false;
            pathSearchingDone = false;
            bg = new Thread(() =>
            {
                DateTime now = DateTime.Now;
                grid.BuildGVD();
                console.WriteLine("GVD Generation Time: " + Math.Round((DateTime.Now - now).TotalMilliseconds) + " ms");
                gridDone = true;

                now                = DateTime.Now;
                pathSearching      = true;
                astar              = HybridAStar.FindPath(grid, startPose, goalPose);
                TimeSpan astarTime = DateTime.Now - now;
                poses              = astar.Path;

                pathSearching     = false;
                pathSearchingDone = true;

                if (astar.Path.Count > 0)
                {
                    pathDone = true;
                }

                now = DateTime.Now;
                if (smoothingOn)
                {
                    smoothedPath = Smoother.Smooth(astar.Path, grid);
                }
                else
                {
                    smoothedPath = astar.Path;
                }
                TimeSpan smoothingTime = DateTime.Now - now;

                int numUnsafe = Smoother.UnsafeIndices != null ? Smoother.UnsafeIndices.Count : 0;

                console.WriteLine("A*: Total Planning Time: " + Math.Round((astarTime + smoothingTime).TotalMilliseconds) + " ms");
                console.WriteLine("         Heuristic Time: " + Math.Round(astar.HeuristicInitTime.TotalMilliseconds) + " ms");
                console.WriteLine("         Searching Time: " + Math.Round((astarTime - astar.HeuristicInitTime).TotalMilliseconds) + " ms");
                console.WriteLine("         Smoothing Time: " + Math.Round(smoothingTime.TotalMilliseconds) + " ms (" + Smoother.NumIterations + " iterations, " + Smoother.Change + "m, " + numUnsafe + " unsafe points)");
                console.WriteLine("    " + astar.Discovered.Count + " nodes discovered");
                console.WriteLine("    " + astar.Expanded.Count + " nodes expanded");

                controller = new StanleyFSMController(smoothedPath, goalPose);

                pathSmoothDone = true;
                if (autoStart)
                {
                    run = true;
                }
            });
            bg.IsBackground = true;
            bg.Priority     = ThreadPriority.Lowest;
            bg.Start();
        }
Exemplo n.º 24
0
        public Point Detect(FaceRect face, Mat frame)
        {
            mode = DetectMode;
            var properties = ScreenProperties;

            if (face == null)
            {
                throw new ArgumentNullException("face");
            }
            if (frame == null || frame.IsEmpty)
            {
                throw new ArgumentNullException("frame");
            }
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }

            switch (mode)
            {
            case EyeGazeDetectMode.LeftOnly:
                if (face.LeftEye == null)
                {
                    return(null);
                }
                break;

            case EyeGazeDetectMode.FaceV2Mobile:
            case EyeGazeDetectMode.FaceV2:
            case EyeGazeDetectMode.FaceMobile:
            case EyeGazeDetectMode.Face:
            case EyeGazeDetectMode.Both:
                if (face.LeftEye == null || face.RightEye == null)
                {
                    return(null);
                }
                break;

            default:
                throw new NotImplementedException();
            }

            Profiler.Start("GazeDetect");

            Point vecPt  = null;
            Point result = new Point(0, 0);
            Point pt     = new Point(0, 0);

            switch (mode)
            {
            case EyeGazeDetectMode.LeftOnly:
                using (Mat left = face.LeftEye.RoiCropByPercent(frame, .33))
                    result = DetectLeftEyes(left);
                break;

            case EyeGazeDetectMode.Both:
                using (Mat left = face.LeftEye.RoiCropByPercent(frame, .33))
                    using (Mat right = face.RightEye.RoiCropByPercent(frame, .33))
                        result = DetectBothEyes(left, right);
                break;

            case EyeGazeDetectMode.FaceV2Mobile:
            case EyeGazeDetectMode.FaceV2:
            case EyeGazeDetectMode.FaceMobile:
            case EyeGazeDetectMode.Face:
                using (Mat left = face.LeftEye.RoiCropByPercent(frame, .25))
                    using (Mat right = face.RightEye.RoiCropByPercent(frame, .25))
                        using (Mat faceRoi = face.ROI(frame))
                            result = DetectFace(faceRoi, left, right);
                break;

            default:
                throw new NotImplementedException();
            }

            var x = result.X * -1;
            var y = result.Y * -1;

            if (UseModification)
            {
                x = (x + OffsetX) * SensitiveX;
                y = (y + OffsetY) * SensitiveY;
            }

            vecPt = new Point(x, y);
            if (UseSmoothing && !Calibrator.IsCalibrating)
            {
                vecPt = Smoother.Smooth(vecPt);
            }

            Vector <double> vec = CreateVector.Dense(new double[] { vecPt.X, vecPt.Y, -1 });

            pt = face.SolveRayScreenVector(new Point3D(vec.ToArray()), properties);

            if (ClipToBound)
            {
                pt.X = Util.Clamp(pt.X, 0, ScreenProperties.PixelSize.Width);
                pt.Y = Util.Clamp(pt.Y, 0, ScreenProperties.PixelSize.Height);
            }

            face.GazeInfo = new EyeGazeInfo()
            {
                ScreenPoint = pt,
                Vector      = new Point3D(vecPt.X, vecPt.Y, -1),
                ClipToBound = ClipToBound,
            };

            Calibrator.Push(new CalibratingPushData(face));
            if (UseCalibrator)
            {
                Calibrator.Apply(face, ScreenProperties);
            }

            Profiler.End("GazeDetect");
            return(face.GazeInfo.ScreenPoint);
        }
Exemplo n.º 25
0
        public void UpdateScore(List <Ms1Spectrum> ms1Spectra, bool pValueCheck = true)
        {
            var nRows             = MaxCharge - MinCharge + 1;
            var ms1ScanNumToIndex = _run.GetMs1ScanNumToIndex();
            var minCol            = ms1ScanNumToIndex[MinScanNum];
            var maxCol            = ms1ScanNumToIndex[MaxScanNum];
            var nCols             = maxCol - minCol + 1;
            var mostAbuIdx        = TheoreticalEnvelope.IndexOrderByRanking[0];

            ClearScore();

            var bestChargeDist = new double[] { 10.0d, 10.0d };
            // sum envelopes at each charge
            var summedIntensity = new double[TheoreticalEnvelope.Size];

            var xicLen      = nCols + 18;
            var xicStartIdx = 9;

            /*
             * if (nCols < 13)
             * {
             *  xicLen = 13;
             *  xicStartIdx = (int) Math.Floor((xicLen - nCols)*0.5);
             * }*/

            var xic2 = new double[2][];

            xic2[0] = new double[xicLen];
            xic2[1] = new double[xicLen];
            var chargeXic = new double[nRows][];

            var tempBestBcDist    = 10.0d;
            var repEnvelopeBcDist = 10.0d;
            ObservedIsotopeEnvelope repEnvelope = null;

            var repEnvelopeBcDist2 = 10.0d;
            ObservedIsotopeEnvelope repEnvelope2 = null;

            var tempBestDistanceScoreAcrossCharge = new double[2] {
                10, 10
            };
            var tempBestIntensityScoreAcrossCharge   = new double[2];
            var tempBestCorrelationScoreAcrossCharge = new double[2];

            for (var i = 0; i < nRows; i++)
            {
                var charge    = i + MinCharge;
                var mostAbuMz = TheoreticalEnvelope.GetIsotopeMz(charge, mostAbuIdx);
                Array.Clear(summedIntensity, 0, summedIntensity.Length);

                chargeXic[i] = new double[xicLen];

                var chargeIdx = (charge % 2 == 0) ? EvenCharge : OddCharge;
                var summedMostAbuIsotopeIntensity = 0d;
                var summedReferenceIntensity      = 0d;

                for (var j = 0; j < nCols; j++)
                {
                    var envelope = Envelopes[i][j];
                    var col      = minCol + j;

                    var localWin = ms1Spectra[col].GetLocalMzWindow(mostAbuMz);

                    if (envelope == null)
                    {
                        continue;
                    }

                    envelope.Peaks.SumEnvelopeTo(summedIntensity);
                    var mostAbuPeak = envelope.Peaks[mostAbuIdx];

                    if (mostAbuPeak != null && mostAbuPeak.Active)
                    {
                        summedMostAbuIsotopeIntensity += mostAbuPeak.Intensity;
                        summedReferenceIntensity      += localWin.HighestIntensity;
                    }
                    AbundanceDistributionAcrossCharge[chargeIdx] += envelope.Abundance;

                    var newBcDist = TheoreticalEnvelope.GetBhattacharyyaDistance(envelope.Peaks);
                    var newCorr   = TheoreticalEnvelope.GetPearsonCorrelation(envelope.Peaks);

                    var goodEnvelope = (newBcDist <0.07 || newCorr> 0.7);

                    if (goodEnvelope)
                    {
                        xic2[chargeIdx][xicStartIdx + j] += envelope.Abundance;
                        chargeXic[i][xicStartIdx + j]     = envelope.Abundance;
                    }

                    var levelOneEnvelope = true;
                    var levelTwoEnvelope = true;

                    if (pValueCheck)
                    {
                        var poissonPvalue = localWin.GetPoissonTestPvalue(envelope.Peaks, TheoreticalEnvelope.Size);
                        var rankSumPvalue = localWin.GetRankSumTestPvalue(envelope.Peaks, TheoreticalEnvelope.Size);
                        levelOneEnvelope = (rankSumPvalue < 0.01 && poissonPvalue < 0.01);
                        //levelTwoEnvelope = (rankSumPvalue < 0.05 || poissonPvalue < 0.05);
                    }

                    if (levelOneEnvelope)
                    {
                        if (newBcDist < BestDistanceScoreAcrossCharge[chargeIdx])
                        {
                            BestDistanceScoreAcrossCharge[chargeIdx] = newBcDist;
                            if (localWin.MedianIntensity > 0)
                            {
                                BestIntensityScoreAcrossCharge[chargeIdx] = envelope.HighestIntensity / localWin.HighestIntensity;
                            }
                            else
                            {
                                BestIntensityScoreAcrossCharge[chargeIdx] = 1.0d;
                            }
                        }

                        BestCorrelationScoreAcrossCharge[chargeIdx] = Math.Max(BestCorrelationScoreAcrossCharge[chargeIdx], newCorr);

                        if (newBcDist < repEnvelopeBcDist)
                        {
                            repEnvelopeBcDist = newBcDist;
                            repEnvelope       = envelope;
                        }

                        // in the initial scoring, classify major and minor envelopes
                        if (!_initScore && goodEnvelope)
                        {
                            envelope.GoodEnough = true;
                        }
                    }

                    if (levelTwoEnvelope)
                    {
                        if (newBcDist < tempBestDistanceScoreAcrossCharge[chargeIdx])
                        {
                            tempBestDistanceScoreAcrossCharge[chargeIdx] = newBcDist;
                            if (localWin.MedianIntensity > 0)
                            {
                                tempBestIntensityScoreAcrossCharge[chargeIdx] = envelope.HighestIntensity / localWin.HighestIntensity;
                            }
                            else
                            {
                                tempBestIntensityScoreAcrossCharge[chargeIdx] = 1.0d;
                            }
                        }
                        tempBestCorrelationScoreAcrossCharge[chargeIdx] = Math.Max(tempBestCorrelationScoreAcrossCharge[chargeIdx], newCorr);

                        if (newBcDist < repEnvelopeBcDist2)
                        {
                            repEnvelopeBcDist2 = newBcDist;
                            repEnvelope2       = envelope;
                        }
                    }
                }

                var bcDist = TheoreticalEnvelope.GetBhattacharyyaDistance(summedIntensity);
                EnvelopeDistanceScoreAcrossCharge[chargeIdx]    = Math.Min(bcDist, EnvelopeDistanceScoreAcrossCharge[chargeIdx]);
                EnvelopeCorrelationScoreAcrossCharge[chargeIdx] = Math.Max(TheoreticalEnvelope.GetPearsonCorrelation(summedIntensity), EnvelopeCorrelationScoreAcrossCharge[chargeIdx]);

                if (BestCharge[chargeIdx] < 1 || bcDist < bestChargeDist[chargeIdx])
                {
                    BestCharge[chargeIdx]     = charge;
                    bestChargeDist[chargeIdx] = bcDist;
                    if (summedReferenceIntensity > 0)
                    {
                        EnvelopeIntensityScoreAcrossCharge[chargeIdx] = summedMostAbuIsotopeIntensity / summedReferenceIntensity;
                    }
                    //if (summedMedianIntensity > 0) EnvelopeIntensityScoreAcrossCharge[chargeIdx] = Math.Min(1.0, 0.1*(summedMostAbuIsotopeIntensity / summedMedianIntensity));
                }

                if (bcDist < tempBestBcDist)
                {
                    tempBestBcDist = bcDist;
                    Array.Copy(summedIntensity, RepresentativeSummedEnvelop, RepresentativeSummedEnvelop.Length);
                }
            }

            // when good envellope is observed at only either even or odd charge...
            if (BestCorrelationScoreAcrossCharge[0] > 0.7 && BestCorrelationScoreAcrossCharge[1] < 0.5)
            {
                const int i = 1;
                BestCorrelationScoreAcrossCharge[i] = tempBestCorrelationScoreAcrossCharge[i];
                BestIntensityScoreAcrossCharge[i]   = tempBestIntensityScoreAcrossCharge[i];
                BestDistanceScoreAcrossCharge[i]    = tempBestDistanceScoreAcrossCharge[i];
            }

            if (BestCorrelationScoreAcrossCharge[1] > 0.7 && BestCorrelationScoreAcrossCharge[0] < 0.5)
            {
                const int i = 0;
                BestCorrelationScoreAcrossCharge[i] = tempBestCorrelationScoreAcrossCharge[i];
                BestIntensityScoreAcrossCharge[i]   = tempBestIntensityScoreAcrossCharge[i];
                BestDistanceScoreAcrossCharge[i]    = tempBestDistanceScoreAcrossCharge[i];
            }

            // normalize abudnace across charges
            var s = AbundanceDistributionAcrossCharge[0] + AbundanceDistributionAcrossCharge[1];

            if (s > 0)
            {
                for (var chargeIdx = 0; chargeIdx < 2; chargeIdx++)
                {
                    AbundanceDistributionAcrossCharge[chargeIdx] = AbundanceDistributionAcrossCharge[chargeIdx] / s;
                }
            }

            if (nCols > 1)
            {
                var evenChargeIdx = BestCharge[EvenCharge] - MinCharge;
                var oddChargeIdx  = BestCharge[OddCharge] - MinCharge;
                XicCorrelationBetweenBestCharges[0] = FitScoreCalculator.GetPearsonCorrelation(Smoother.Smooth(chargeXic[evenChargeIdx]), Smoother.Smooth(chargeXic[oddChargeIdx]));
                XicCorrelationBetweenBestCharges[1] = FitScoreCalculator.GetPearsonCorrelation(Smoother.Smooth(xic2[EvenCharge]), Smoother.Smooth(xic2[OddCharge]));
            }

            if (repEnvelope == null && repEnvelope2 != null)
            {
                repEnvelope = repEnvelope2;
            }

            if (repEnvelope != null)
            {
                // set representative charge, mz and scanNum
                RepresentativeCharge  = repEnvelope.Charge;
                RepresentativeMz      = repEnvelope.RepresentativePeak.Mz;
                RepresentativeScanNum = repEnvelope.ScanNum;
            }

            _initScore = true;
        }