PgScanCorr.xaml.cs 52.7 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
1 2
using CommunityToolkit.Mvvm.Input;
using FLY.Thick.Base.IService;
潘栩锋's avatar
潘栩锋 committed
3 4 5
using LiveCharts;
using LiveCharts.Configurations;
using LiveCharts.Wpf;
6
using MathNet.Numerics.LinearAlgebra.Double;
7
using Microsoft.Win32;
潘栩锋's avatar
潘栩锋 committed
8
using Misc;
9
using OfficeOpenXml;
潘栩锋's avatar
潘栩锋 committed
10 11 12 13
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
14 15
using System.Data;
using System.IO;
潘栩锋's avatar
潘栩锋 committed
16 17
using System.Linq;
using System.Threading.Tasks;
18
using System.Windows;
19 20
using System.Windows.Controls;
using System.Windows.Input;
潘栩锋's avatar
潘栩锋 committed
21
using System.Windows.Media;
22
using Unity;
潘栩锋's avatar
潘栩锋 committed
23 24 25

namespace FLY.Thick.Base.UI
{
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    /// <summary>
    /// Page_ScanCorr.xaml 的交互逻辑
    /// </summary>
    public partial class PgScanCorr : Page
    {
        PgScanCorrVm viewModel;
        public PgScanCorr()
        {
            InitializeComponent();

            if (System.ComponentModel.LicenseManager.UsageMode != System.ComponentModel.LicenseUsageMode.Runtime)
                return;

            this.Loaded += Page_Loaded;
            this.Unloaded += Page_Unloaded;

        }

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            viewModel.DisposeBinding();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            viewModel.SetBinding();
        }

        [InjectionMethod]
        public void Init(IUnityContainer container,
            IScanCorrService scanCorrService,
            IInitParamService initParamService,
            ITDGageService gageService
            )
        {
            viewModel = new PgScanCorrVm();
            viewModel.Init(scanCorrService, initParamService, gageService);
            this.DataContext = viewModel;

            container.BuildUp(mircoGage);
        }


        private void UIElement_OnMouseMove(object sender, MouseEventArgs e)
        {
            if (!isDown)
                return;

            var vm = viewModel;
            var chart = (LiveCharts.Wpf.CartesianChart)sender;


            //lets get where the mouse is at our chart
            var mouseCoordinate = e.GetPosition(chart);

            //now that we know where the mouse is, lets use
            //ConverToChartValues extension
            //it takes a point in pixes and scales it to our chart current scale/values
            var p = chart.ConvertToChartValues(mouseCoordinate);


            //var series = vm.Series[0];

            //var closetsPoint = series.ClosestPointTo(p.X, AxisOrientation.X);
            //if (closetsPoint == null)
            //    return;

            //pEnd = closetsPoint;
            pEnd = p;
            vm.Select(PgScanCorrVm.SelectType.Move, pBegin, pEnd);

        }

        private System.Windows.Point pBegin;
        private System.Windows.Point pEnd;
        private bool isDown = false;
        private void UIElement_MouseDown(object sender, MouseButtonEventArgs e)
        {
            isDown = true;
            var vm = viewModel;
            var chart = (LiveCharts.Wpf.CartesianChart)sender;


            var mouseCoordinate = e.GetPosition(chart);
            var p = chart.ConvertToChartValues(mouseCoordinate);
            pBegin = p;

            //var series = chart.Series[0];
            //ChartPoint closetsPoint = series.ClosestPointTo(p.X, AxisOrientation.X);
            //if (closetsPoint == null)
            //{
            //    isDown = false;
            //    return;
            //}
            //cpBegin = closetsPoint;

            vm.Select(PgScanCorrVm.SelectType.Click, pBegin, pBegin);

        }
        private void UIElement_MouseUp(object sender, MouseButtonEventArgs e)
        {
            isDown = false;
            var vm = viewModel;
            var series = vm.Series[0];
            var chart = (LiveCharts.Wpf.CartesianChart)sender;

            //lets get where the mouse is at our chart
            var mouseCoordinate = e.GetPosition(chart);

            //now that we know where the mouse is, lets use
            //ConverToChartValues extension
            //it takes a point in pixes and scales it to our chart current scale/values
            var p = chart.ConvertToChartValues(mouseCoordinate);

            //for X in this case we will only highlight the closest point.
            //lets use the already defined ClosestPointTo extension
            //it will return the closest ChartPoint to a value according to an axis.
            //here we get the closest point to p.X according to the X axis
            //var series = chart.Series[0];
            //var closetsPoint = series.ClosestPointTo(p.X, AxisOrientation.X);
            //if (closetsPoint == null)
            //    return;
            pEnd = p;
            vm.Select(PgScanCorrVm.SelectType.Cancel, pBegin, pEnd);
        }
    }

潘栩锋's avatar
潘栩锋 committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
    public class PgScanCorrVm : INotifyPropertyChanged
    {

        #region 轴调节
        /// <summary>
        /// Y轴拖拉条 最大值
        /// </summary>
        public double YRangeSliderMax { get; set; } = 65535;

        /// <summary>
        /// Y轴拖拉条 最小值
        /// </summary>
        public double YRangeSliderMin { get; set; } = 0;
        #endregion


        #region 曲线
        public Func<double, string> XFormatter { get; private set; }
        public Func<double, string> YFormatter { get; private set; }

        public double XMin => 0;
潘栩锋's avatar
潘栩锋 committed
174
        public double XMax => PosLength / PosOfGrid;
潘栩锋's avatar
潘栩锋 committed
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

        private double ymax = 65535;
        /// <summary>
        /// Y轴 最大值
        /// </summary>
        public double YMax
        {
            get { return ymax; }
            set
            {
                if (value <= YMin)
                {
                    return;
                }
                if (value != ymax)
                    ymax = value;
            }
        }

        private double ymin = 0;
        /// <summary>
        /// Y轴 最小值
        /// </summary>
        public double YMin
        {
            get { return ymin; }
            set
            {
                if (value >= YMax)
                {
                    return;
                }
                if (value != ymin)
                    ymin = value;
            }
        }

        public SeriesCollection Series { get; } = new SeriesCollection();

        public class SeriesInfo : INotifyPropertyChanged
        {
            public string Name { get; set; }
            public Brush Color { get; set; }

            public ChartValues<double> Datas = new ChartValues<double>();

            public event PropertyChangedEventHandler PropertyChanged;
        }
        public SeriesInfo[] SeriesInfos { get; set; }

225
        ChartValues<XY> KeyPointDatas = new ChartValues<XY>();
潘栩锋's avatar
潘栩锋 committed
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
        CartesianMapper<XY> Mapper { get; set; }

        #endregion

        /// <summary>
        /// 机架总长,脉冲
        /// </summary>
        public int PosLength { get; set; } = 8000;

        /// <summary>
        /// 1个grid = N个pos
        /// </summary>
        public int PosOfGrid { get; set; } = 10;

        /// <summary>
        /// 比例
        /// </summary>
        public double Mmpp { get; set; } = 0.1;




        #region

        /// <summary>
        /// 使能修正
        /// </summary>
        public bool Enable { set; get; }

        /// <summary>
        /// 当前修正的组
        /// </summary>
        public int CurrGroupIndex { get; set; }

        /// <summary>
        /// 当前进度 0 - 100 
        /// </summary>
        public int Progress { get; set; }

        /// <summary>
        /// 数据更新时间
        /// </summary>
        public DateTime[] UpdateTimes { get; set; }

        /// <summary>
        /// 正在机架修正中
        /// </summary>
        public bool IsRunning { get; set; }

        /// <summary>
        /// 来回次数
        /// </summary>
        public int ScanCnt { get; set; }


        #endregion
潘栩锋's avatar
潘栩锋 committed
282

潘栩锋's avatar
潘栩锋 committed
283 284 285 286 287 288 289 290 291 292 293
        /// <summary>
        /// 当前被选择的组序号
        /// </summary>
        public int SelectedGroupIndex { get; set; }


        #region 平滑方式生成修正曲线

        /// <summary>
        /// 平均滤波平滑数,单位grid
        /// </summary>
294
        public int SmoothFactor { get; set; } = 50;
潘栩锋's avatar
潘栩锋 committed
295 296 297 298
        #endregion

        #region 关键点方式生成修正曲线

299 300 301

        public KeyPointsSelectMode KpSelectMode { get; set; } = KeyPointsSelectMode.Null;

潘栩锋's avatar
潘栩锋 committed
302 303 304 305 306 307 308 309
        #endregion

        /// <summary>
        /// 数据好了!!!!
        /// 当 flyad7 的poslen, posOfGrid 发生变化时,DataOK = false, 需要重新记录。
        /// </summary>
        public bool IsDataOK { get; set; } = false;

310
        public double AvgAd { get; set; }
潘栩锋's avatar
潘栩锋 committed
311

312
        #region CMD
313 314 315 316
        public RelayCommand SelectedGroup0Cmd { get; }
        public RelayCommand SelectedGroup1Cmd { get; }

        public RelayCommand StopCmd { get; }
潘栩锋's avatar
潘栩锋 committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
        public RelayCommand StartCmd { get; }

        public RelayCommand ClearCmd { get; }

        public RelayCommand CreateCorrBySmoothCmd { get; }
        public RelayCommand CreateCorrByKeyPointCmd { get; }
        /// <summary>
        /// 添加关键点模式
        /// </summary>
        public RelayCommand AddKeyPointModeCmd { get; }
        public RelayCommand RemoveKeyPointModeCmd { get; }
        public RelayCommand MoveKeyPointModeCmd { get; }
        public RelayCommand CancelKeyPointModeCmd { get; }
        public RelayCommand SetCorrDataCmd { get; }

332 333
        public RelayCommand SaveXlsxCmd { get; }
        public RelayCommand LoadXlsxCmd { get; }
潘栩锋's avatar
潘栩锋 committed
334

335 336
        #endregion

潘栩锋's avatar
潘栩锋 committed
337 338
        IScanCorrService scanCorrService;
        IInitParamService initParamService;
339
        ITDGageService gageService;
340
        KeyPointLine keyPointLine;
潘栩锋's avatar
潘栩锋 committed
341

342 343 344 345 346 347
        Dictionary<object, List<Misc.BindingOperations.PropertyChangedEventContexts>> bindingConexts = new Dictionary<object, List<Misc.BindingOperations.PropertyChangedEventContexts>>();

        /// <summary>
        /// 数据已经绑定了
        /// </summary>
        bool isBinding;
潘栩锋's avatar
潘栩锋 committed
348 349 350 351 352 353 354 355 356 357 358 359 360
        public PgScanCorrVm()
        {
            #region 与数据无关界面参数

            XFormatter = (x) =>
            {
                //x 是 grid
                int pos = (int)(x * PosOfGrid);
                int mm = (int)(pos * Mmpp);
                return $"{pos}\n{mm}mm";
            };
            YFormatter = (y) =>
            {
潘栩锋's avatar
潘栩锋 committed
361
                return $"{y:F0}";
潘栩锋's avatar
潘栩锋 committed
362
            };
363 364 365
            Mapper = Mappers.Xy<XY>()
                .X((value, index) => value.X)
                .Y(value => value.Y);
潘栩锋's avatar
潘栩锋 committed
366

367 368 369 370 371 372 373 374


            string seriesName0 = (string)Application.Current.TryFindResource("str.PgScanCorr.ForwOrigData");
            string seriesName1 = (string)Application.Current.TryFindResource("str.PgScanCorr.BackwOrigData");
            string seriesName2 = (string)Application.Current.TryFindResource("str.PgScanCorr.ForwSmoothData");
            string seriesName3 = (string)Application.Current.TryFindResource("str.PgScanCorr.BackwSmoothData");
            string seriesName4 = (string)Application.Current.TryFindResource("str.PgScanCorr.KeyPoint");

潘栩锋's avatar
潘栩锋 committed
375
            SeriesInfos = new SeriesInfo[] {
376 377 378 379
                new SeriesInfo(){Name = seriesName0, Color = FLY.ControlLibrary.Themes.Styles.GetForeground(0)},
                new SeriesInfo(){Name = seriesName1, Color = FLY.ControlLibrary.Themes.Styles.GetForeground(1)},
                new SeriesInfo(){Name = seriesName2, Color = FLY.ControlLibrary.Themes.Styles.GetForeground(0,true)},
                new SeriesInfo(){Name = seriesName3, Color = FLY.ControlLibrary.Themes.Styles.GetForeground(1,true)},
潘栩锋's avatar
潘栩锋 committed
380 381
            };

382 383 384



潘栩锋's avatar
潘栩锋 committed
385 386 387 388 389 390 391
            for (int i = 0; i < SeriesInfos.Count(); i++)
            {
                var seriesInfo = SeriesInfos[i];
                var lineSeries = new LineSeries
                {
                    Values = seriesInfo.Datas,
                    StrokeThickness = 2,
392
                    Title = seriesInfo.Name,
潘栩锋's avatar
潘栩锋 committed
393 394
                    Fill = new SolidColorBrush(System.Windows.Media.Colors.Transparent),
                    Stroke = seriesInfo.Color,
395
                    PointGeometry = null
潘栩锋's avatar
潘栩锋 committed
396 397 398 399
                };
                Series.Add(lineSeries);
            }

400 401 402 403 404
            keyPointLine = new KeyPointLine();
            Misc.BindingOperations.SetBinding(this, nameof(SmoothFactor), keyPointLine, nameof(keyPointLine.SmoothFactor));
            {
                var lineSeries = new LineSeries
                {
405
                    Title = seriesName4,
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
                    Values = KeyPointDatas,
                    StrokeThickness = 6,
                    Fill = new SolidColorBrush(System.Windows.Media.Colors.Transparent),
                    Stroke = FLY.ControlLibrary.Themes.Styles.GetForeground(2),
                    Configuration = Mapper,
                    //PointGeometry = Geometry.
                    PointGeometrySize = 15,
                    //PointForeground = "#222E31"
                };
                Series.Add(lineSeries);
            }
            keyPointLine.KeyPoints.CollectionChanged += (s, e) =>
            {
                UpdateKeyPointDatas();
            };
潘栩锋's avatar
潘栩锋 committed
421 422
            #endregion

423
            StopCmd = new RelayCommand(Stop);
潘栩锋's avatar
潘栩锋 committed
424 425 426 427 428 429 430 431 432
            StartCmd = new RelayCommand(Start);
            ClearCmd = new RelayCommand(Clear);
            CreateCorrBySmoothCmd = new RelayCommand(CreateCorrBySmooth);
            CreateCorrByKeyPointCmd = new RelayCommand(CreateCorrByKeyPoint);
            AddKeyPointModeCmd = new RelayCommand(AddKeyPointMode);
            RemoveKeyPointModeCmd = new RelayCommand(RemoveKeyPointMode);
            MoveKeyPointModeCmd = new RelayCommand(MoveKeyPointMode);
            CancelKeyPointModeCmd = new RelayCommand(CancelKeyPointMode);
            SetCorrDataCmd = new RelayCommand(SetCorrData);
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452

            SelectedGroup0Cmd = new RelayCommand(SelectedGroup0);
            SelectedGroup1Cmd = new RelayCommand(SelectedGroup1);

            SaveXlsxCmd = new RelayCommand(SaveXlsx);
            LoadXlsxCmd = new RelayCommand(LoadXlsx);

        }



        public void Init(
            IScanCorrService scanCorrService,
            IInitParamService initParamService,
            ITDGageService gageService
            )
        {
            this.scanCorrService = scanCorrService;
            this.initParamService = initParamService;
            this.gageService = gageService;
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
            //参数绑定
            SetBinding();

        }

        /// <summary>
        /// 参数绑定
        /// </summary>
        public void SetBinding()
        {
            if (isBinding)//已经绑定了
                return;
            isBinding = true;
            //下面全部event保存在bindingConexts
            Misc.BindingOperations.StartMarkdownEvents(bindingConexts);
468 469 470 471 472 473 474 475 476 477 478 479

            Misc.BindingOperations.SetBinding(this.scanCorrService, nameof(scanCorrService.Enable), this, nameof(Enable), BindingOperations.BindingMode.TwoWay);
            Misc.BindingOperations.SetBinding(this.scanCorrService, nameof(scanCorrService.ScanCnt), this, nameof(ScanCnt));
            Misc.BindingOperations.SetBinding(this.scanCorrService, nameof(scanCorrService.CurrGroupIndex), this, nameof(CurrGroupIndex));
            Misc.BindingOperations.SetBinding(this.scanCorrService, nameof(scanCorrService.Progress), this, nameof(Progress));
            Misc.BindingOperations.SetBinding(this.scanCorrService, nameof(scanCorrService.IsRunning), this, nameof(IsRunning));
            Misc.BindingOperations.SetBinding(this.scanCorrService, nameof(scanCorrService.SmoothFactor), this, nameof(SmoothFactor));

            Misc.BindingOperations.SetBinding(this.initParamService, nameof(initParamService.Encoder1_mmpp), this, nameof(Mmpp));
            Misc.BindingOperations.SetBinding(this.initParamService, nameof(initParamService.PosLength), this, nameof(PosLength));
            Misc.BindingOperations.SetBinding(this.initParamService, nameof(initParamService.PosOfGrid), this, nameof(PosOfGrid));

480 481 482
            //备份event完毕, 必须关闭记录
            Misc.BindingOperations.StopMarkdownEvents();

483 484 485 486 487 488 489
            UpdateTimes = new DateTime[2];
            downloadAll();

            this.PropertyChanged += PgScanCorrVm_PropertyChanged;

            this.scanCorrService.PropertyChanged += ScanCorrService_PropertyChanged;
        }
490 491 492 493 494 495 496 497 498 499 500
        /// <summary>
        /// 解除绑定
        /// </summary>
        public void DisposeBinding()
        {
            if (!isBinding)//已经解除绑定了
                return;
            isBinding = false;
            Misc.BindingOperations.DisposeEventTargetObject(bindingConexts);

            this.PropertyChanged -= PgScanCorrVm_PropertyChanged;
501

502 503
            this.scanCorrService.PropertyChanged -= ScanCorrService_PropertyChanged;
        }
504 505 506 507 508 509 510 511 512 513
        private void ScanCorrService_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(FObjBase.FObjServiceClient.IsConnected))
            {
                var client = scanCorrService as FObjBase.FObjServiceClient;
                if (client.IsConnected)
                {
                    downloadAll();
                }
            }
潘栩锋's avatar
潘栩锋 committed
514 515 516 517
            else if (e.PropertyName == nameof(scanCorrService.UpdateTimes))
            {
                if (UpdateTimes[SelectedGroupIndex] != scanCorrService.UpdateTimes[SelectedGroupIndex])
                {
518 519 520 521
                    //当前显示的,发生变化了,下载
                    downloadAll();
                }
            }
潘栩锋's avatar
潘栩锋 committed
522 523 524 525 526
        }

        private void Clear()
        {
            scanCorrService.Clear(SelectedGroupIndex);
527 528
            string tit = (string)Application.Current.TryFindResource("str.PgScanCorr.ExecutedSuccessfully");
            FLY.ControlLibrary.Window_Tip.Show(tit,null,TimeSpan.FromSeconds(2));
潘栩锋's avatar
潘栩锋 committed
529 530 531 532
        }

        private void Start()
        {
533
            scanCorrService.Start(SelectedGroupIndex, ScanCnt, SmoothFactor);
534 535
            string tit = (string)Application.Current.TryFindResource("str.PgScanCorr.StartOfExecution");
            FLY.ControlLibrary.Window_Tip.Show(tit, null, TimeSpan.FromSeconds(2));
潘栩锋's avatar
潘栩锋 committed
536 537
        }

538 539 540
        private void Stop()
        {
            gageService.StartP2(Base.Common.STARTP2_MODE.STOP);
541 542
            string tit = (string)Application.Current.TryFindResource("str.PgScanCorr.StopOfExecution");
            FLY.ControlLibrary.Window_Tip.Show(tit, null, TimeSpan.FromSeconds(2));
543 544 545 546 547 548 549 550 551 552 553
        }
        private void SelectedGroup1()
        {
            SelectedGroupIndex = 1;
        }

        private void SelectedGroup0()
        {
            SelectedGroupIndex = 0;
        }

潘栩锋's avatar
潘栩锋 committed
554 555 556 557
        private void SetCorrData()
        {
            //TODO
            //判断是否有数据
潘栩锋's avatar
潘栩锋 committed
558 559 560
            for (int i = 2; i <= 3; i++)
            {

潘栩锋's avatar
潘栩锋 committed
561 562 563
            }

            int[][] corrDatas = new int[2][];
潘栩锋's avatar
潘栩锋 committed
564 565
            for (int i = 0; i < 2; i++)
                corrDatas[i] = SeriesInfos[2 + i].Datas.Select(d => double.IsNaN(d) ? Misc.MyBase.NULL_VALUE : (int)d).ToArray();
潘栩锋's avatar
潘栩锋 committed
566

567 568 569 570
            int[][] orgDatas = new int[2][];
            for (int i = 0; i < 2; i++)
                orgDatas[i] = SeriesInfos[i].Datas.Select(d => double.IsNaN(d) ? Misc.MyBase.NULL_VALUE : (int)d).ToArray();

潘栩锋's avatar
潘栩锋 committed
571
            //发送出去
572
            scanCorrService.SetCorrData(SelectedGroupIndex, corrDatas, (int)AvgAd, orgDatas);
潘栩锋's avatar
潘栩锋 committed
573

574 575
            string tit = (string)Application.Current.TryFindResource("str.PgScanCorr.ApplySuccessfully");
            FLY.ControlLibrary.Window_Tip.Show(tit, null, TimeSpan.FromSeconds(2));
潘栩锋's avatar
潘栩锋 committed
576 577 578 579 580

        }

        private void MoveKeyPointMode()
        {
581
            KpSelectMode = KeyPointsSelectMode.Move;
潘栩锋's avatar
潘栩锋 committed
582 583 584 585
        }

        private void RemoveKeyPointMode()
        {
586
            KpSelectMode = KeyPointsSelectMode.Remove;
潘栩锋's avatar
潘栩锋 committed
587 588 589 590
        }

        private void AddKeyPointMode()
        {
591
            KpSelectMode = KeyPointsSelectMode.Add;
潘栩锋's avatar
潘栩锋 committed
592
        }
潘栩锋's avatar
潘栩锋 committed
593 594
        private void CancelKeyPointMode()
        {
595
            KpSelectMode = KeyPointsSelectMode.Null;
潘栩锋's avatar
潘栩锋 committed
596 597 598 599 600
        }


        private void CreateCorrByKeyPoint()
        {
601
            CancelKeyPointMode();
潘栩锋's avatar
潘栩锋 committed
602

603 604 605
            if (keyPointLine.KeyPoints.Count() < 3)
            {
                //少于3个点
606 607 608
                string tit = (string)Application.Current.TryFindResource("str.PgScanCorr.MakeFailed");
                string msg = (string)Application.Current.TryFindResource("str.PgScanCorr.KeyPointMustMoreThan3");
                FLY.ControlLibrary.Window_WarningTip.Show(tit, msg, TimeSpan.FromSeconds(2));
609 610
                return;
            }
潘栩锋's avatar
潘栩锋 committed
611 612
            for (int i = 0; i < 2; i++)
            {
613 614 615 616
                var filterDatas = keyPointLine.CalFilterDatas(SeriesInfos[i].Datas);
                SeriesInfos[i + 2].Datas.Clear();
                SeriesInfos[i + 2].Datas.AddRange(filterDatas);
            }
潘栩锋's avatar
潘栩锋 committed
617

618 619 620 621
            //计算平均值
            double avg0 = SeriesInfos[2].Datas.AverageNoNull();
            double avg1 = SeriesInfos[3].Datas.AverageNoNull();
            AvgAd = (int)((avg0 + avg1) / 2);
潘栩锋's avatar
潘栩锋 committed
622

623 624 625 626
            {
                string tit = (string)Application.Current.TryFindResource("str.PgScanCorr.MakeSuccessfully");
                FLY.ControlLibrary.Window_Tip.Show(tit,null,TimeSpan.FromSeconds(2));
            }
潘栩锋's avatar
潘栩锋 committed
627 628 629 630
        }



潘栩锋's avatar
潘栩锋 committed
631 632
        void Smooth(ChartValues<double> orgDatas, ChartValues<double> filterDatas)
        {
潘栩锋's avatar
潘栩锋 committed
633 634 635 636 637 638 639 640

            var filters = new double[orgDatas.Count()];
            for (int i = 0; i < orgDatas.Count(); i++)
            {
                double sum = 0;
                int cnt = 0;
                for (int j = 0; j < SmoothFactor; j++)
                {
641
                    int index = i - SmoothFactor / 2 + j;
潘栩锋's avatar
潘栩锋 committed
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
                    if (index < 0)
                        continue;
                    else if (index >= orgDatas.Count())
                        break;

                    if (!double.IsNaN(orgDatas[index]))
                    {
                        sum += orgDatas[index];
                        cnt++;
                    }
                }
                if (cnt > 0)
                    filters[i] = sum / cnt;
                else
                    filters[i] = double.NaN;
            }
            filterDatas.Clear();
            filterDatas.AddRange(filters);
        }
        private void CreateCorrBySmooth()
        {
潘栩锋's avatar
潘栩锋 committed
663 664
            for (int i = 0; i < 2; i++)
                Smooth(SeriesInfos[i].Datas, SeriesInfos[2 + i].Datas);
潘栩锋's avatar
潘栩锋 committed
665 666 667 668 669 670

            //计算平均值
            double avg0 = SeriesInfos[2].Datas.AverageNoNull();
            double avg1 = SeriesInfos[3].Datas.AverageNoNull();
            AvgAd = (int)((avg0 + avg1) / 2);

671 672 673 674
            
            string tit = (string)Application.Current.TryFindResource("str.PgScanCorr.MakeSuccessfully");
            FLY.ControlLibrary.Window_Tip.Show(tit, null, TimeSpan.FromSeconds(2));
            
潘栩锋's avatar
潘栩锋 committed
675 676 677 678 679 680 681 682 683 684 685 686 687 688
        }




        void downloadAll()
        {
            var client = scanCorrService as FObjBase.FObjServiceClient;
            if (!client.IsConnected)
                return;

            //下载数据
            scanCorrService.GetScanCorrGroup(SelectedGroupIndex, scanCorrService_GetScanCorrGroup, null);

689
            keyPointLine.Clear();
潘栩锋's avatar
潘栩锋 committed
690 691 692 693 694 695 696 697
        }

        void scanCorrService_GetScanCorrGroup(object asyncContext, object retData)
        {

            var reponse = retData as GetScanCorrGroupResponse;
            int groupIndex = reponse.GroupIndex;
            UpdateTimes[groupIndex] = reponse.UpdateTime;
698
            AvgAd = Misc.MyBase.ISVALIDATA(reponse.Avg) ? reponse.Avg : double.NaN;
潘栩锋's avatar
潘栩锋 committed
699 700 701 702 703 704 705
            IsDataOK = reponse.IsDataOK;

            SeriesInfos[0].Datas.Clear();
            SeriesInfos[1].Datas.Clear();
            SeriesInfos[2].Datas.Clear();
            SeriesInfos[3].Datas.Clear();

706 707
            if (reponse.OrgDatas == null || reponse.OrgDatas.Count() != 2)
                return;
潘栩锋's avatar
潘栩锋 committed
708

709
            if (reponse.OrgDatas[0] == null)
潘栩锋's avatar
潘栩锋 committed
710
                return;
711 712
            SeriesInfos[0].Datas.AddRange(reponse.OrgDatas[0].Select(ad => Misc.MyBase.ISVALIDATA(ad) ? ad : double.NaN));

713 714 715 716 717 718 719
            var list = SeriesInfos[0].Datas.Where((d) =>
            {
                if (double.IsNaN(d))
                    return false;
                else
                    return true;
            });
720 721 722
            if (list.Count() == 0)
                return;

723
            //设置Y轴范围
724 725
            int max = (int)list.Max();
            int min = (int)list.Min();
726 727 728 729 730
            //扩大3倍显示
            int range = max - min;
            if (range == 0)
            {
                //异常
潘栩锋's avatar
潘栩锋 committed
731
            }
732
            else
潘栩锋's avatar
潘栩锋 committed
733
            {
734 735 736 737
                ymax = max + range / 4;
                ymin = min - range / 4;
                YRangeSliderMin = min - range;
                YRangeSliderMax = max + range;
潘栩锋's avatar
潘栩锋 committed
738 739
            }

740 741 742 743 744 745 746
            NotifyPropertyChanged(nameof(YMax));
            NotifyPropertyChanged(nameof(YMin));


            if (reponse.OrgDatas[1] == null)
                return;

潘栩锋's avatar
潘栩锋 committed
747
            SeriesInfos[1].Datas.AddRange(reponse.OrgDatas[1].Select(ad => Misc.MyBase.ISVALIDATA(ad) ? ad : double.NaN));
748 749 750 751 752 753 754 755 756




            if (reponse.CorrDatas == null || reponse.CorrDatas.Count() != 2 || reponse.CorrDatas[0] == null || reponse.CorrDatas[1] == null)
                return;

            SeriesInfos[2].Datas.AddRange(reponse.CorrDatas[0].Select(ad => Misc.MyBase.ISVALIDATA(ad) ? ad : double.NaN));
            SeriesInfos[3].Datas.AddRange(reponse.CorrDatas[1].Select(ad => Misc.MyBase.ISVALIDATA(ad) ? ad : double.NaN));
潘栩锋's avatar
潘栩锋 committed
757

潘栩锋's avatar
潘栩锋 committed
758 759 760 761 762 763 764 765 766
        }
        private void PgScanCorrVm_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(SelectedGroupIndex))
            {
                downloadAll();
            }
        }

767 768 769 770 771 772 773

        public enum SelectType
        {
            Click,
            Move,
            Cancel
        }
潘栩锋's avatar
潘栩锋 committed
774

775
        public void Select(SelectType selectType, System.Windows.Point cpBegin, System.Windows.Point cpEnd)
潘栩锋's avatar
潘栩锋 committed
776
        {
777
            if (KpSelectMode == KeyPointsSelectMode.Null)
潘栩锋's avatar
潘栩锋 committed
778
                return;
潘栩锋's avatar
潘栩锋 committed
779 780
            switch (KpSelectMode)
            {
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
                case KeyPointsSelectMode.Add:
                    {
                        if (selectType != SelectType.Click)
                            return;
                        keyPointLine.Add(cpBegin.X, SeriesInfos[0].Datas);
                        return;
                    }
                    break;
                case KeyPointsSelectMode.Remove:
                    {
                        if (selectType != SelectType.Click)
                            return;
                        keyPointLine.Remove(cpBegin.X);
                        return;
                    }
                    break;
            }
        }
潘栩锋's avatar
潘栩锋 committed
799

潘栩锋's avatar
潘栩锋 committed
800
        void UpdateKeyPointDatas()
801 802 803
        {
            KeyPointDatas.Clear();
            KeyPointDatas.AddRange(keyPointLine.KeyPoints);
潘栩锋's avatar
潘栩锋 committed
804 805 806
        }


807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
        private async void LoadXlsx()
        {
            //加载数据
            string strDesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            OpenFileDialog sfd = new OpenFileDialog();
            sfd.Filter = "xlsx files (*.xlsx)|*.xlsx";
            sfd.InitialDirectory = strDesktopPath;

            if (sfd.ShowDialog() == true)
            {
                string filename = sfd.FileName;
                Exception error = null;
                var ret = await Task.Factory.StartNew(() =>
                {
                    try
                    {
                        LoadXlsx(filename);
                    }
                    catch (Exception e)
                    {
                        error = e;
                        return false;
                    }
                    return true;
                });
                if (ret)
                {
                    //画图
836 837
                    string tit = (string)Application.Current.TryFindResource("str.PgScanCorr.LoadSuccessfully");
                    FLY.ControlLibrary.Window_Tip.Show(tit, filename, TimeSpan.FromSeconds(2));
838 839 840
                }
                else
                {
841 842
                    string tit = (string)Application.Current.TryFindResource("str.PgScanCorr.LoadFailed");
                    MessageBox.Show($"{error}", tit, MessageBoxButton.OK, MessageBoxImage.Error);
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
                }

            }
        }
        private void LoadXlsx(string filepath)
        {
            //检测标题

            DataTable dataTable = new DataTable("table_scancorr");
            dataTable.Columns.Add(new DataColumn() { ColumnName = "序号", DataType = typeof(double), Caption = "0" });
            dataTable.Columns.Add(new DataColumn() { ColumnName = "脉冲", DataType = typeof(double), Caption = "0" });
            dataTable.Columns.Add(new DataColumn() { ColumnName = "位置mm", DataType = typeof(double), Caption = "0" });
            for (int j = 0; j < SeriesInfos.Count(); j++)
            {
                dataTable.Columns.Add(new DataColumn()
                {
                    ColumnName = SeriesInfos[j].Name,
                    DataType = typeof(double),
                    Caption = "0"
                });

            }

            using (ExcelPackage p = new ExcelPackage(new FileInfo(filepath)))
            {
                ExcelWorksheet sheet = p.Workbook.Worksheets["机架修正"];
                FromSheet(sheet, dataTable);
            }

            App.Current.Dispatcher.Invoke(() =>
            {
潘栩锋's avatar
潘栩锋 committed
874
                for (int j = 0; j < 4; j++)
875 876 877 878 879
                {
                    List<double> datas = new List<double>();
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        var dataRow = dataTable.Rows[i];
潘栩锋's avatar
潘栩锋 committed
880

881 882 883 884 885 886 887 888
                        double ad = System.Convert.ToDouble(dataRow[SeriesInfos[j].Name]);
                        datas.Add(ad);
                    }
                    SeriesInfos[j].Datas.Clear();
                    SeriesInfos[j].Datas.AddRange(datas);
                    datas.AverageNoNull();

                }
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916

                var list = SeriesInfos[0].Datas.Where((d) =>
                {
                    if (double.IsNaN(d))
                        return false;
                    else
                        return true;
                });
                //设置Y轴范围
                int max = (int)list.Max();
                int min = (int)list.Min();
                //扩大3倍显示
                int range = max - min;
                if (range == 0)
                {
                    //异常
                }
                else
                {
                    ymax = max + range / 4;
                    ymin = min - range / 4;
                    YRangeSliderMin = min - range;
                    YRangeSliderMax = max + range;
                }

                NotifyPropertyChanged(nameof(YMax));
                NotifyPropertyChanged(nameof(YMin));

917 918
                double avg0 = SeriesInfos[2].Datas.AverageNoNull();
                double avg1 = SeriesInfos[3].Datas.AverageNoNull();
潘栩锋's avatar
潘栩锋 committed
919 920
                if (!double.IsNaN(avg0) && !double.IsNaN(avg1))
                {
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
                    //异常
                    AvgAd = (avg0 + avg1) / 2;
                }
            });

        }

        void FromSheet(ExcelWorksheet sheet, DataTable dataTable)
        {

            int from_row = 1;
            int row = from_row;


            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                int col = i + 1;
                if ((string)(sheet.Cells[row, col].Value) != dataTable.Columns[i].ColumnName)
                {
                    throw new Exception($"格式出错, 第{i}列 不是{dataTable.Columns[i].ColumnName}");
                }
            }

            row++;
            while (true)
            {
                var newRow = dataTable.NewRow();
                //当一行都是空的,认为没有数据
                int nullCnt = 0;
                for (int j = 0; j < dataTable.Columns.Count; j++)
                {
                    int col = j + 1;
                    object value = sheet.Cells[row, col].Value;

                    if (value is string || value == null)
                    {
                        if (string.IsNullOrEmpty((string)(value)))
                        {
                            //空的
                            nullCnt++;
                            //continue;
                            return;
                        }

                    }
                    try
                    {
                        newRow[j] = sheet.Cells[row, col].Value;
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
                if (nullCnt == dataTable.Columns.Count)
                {
                    //没有数据了
                    break;
                }
                dataTable.Rows.Add(newRow);
                row++;
            }

        }


        private void SaveXlsx()
        {
            //下载数据
            string strDesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            string filename = $"机架修正_组{SelectedGroupIndex}_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "xlsx files (*.xlsx)|*.xlsx";
            sfd.InitialDirectory = strDesktopPath;
            sfd.FileName = filename;
            if (sfd.ShowDialog() == true)
            {
                filename = sfd.FileName;
                Task.Factory.StartNew(() =>
                {
                    SaveToXlsx(filename);

1004
                    Application.Current.Dispatcher.Invoke(() =>
1005
                    {
1006 1007
                        string tit = (string)Application.Current.TryFindResource("str.PgScanCorr.SaveSuccessfully");
                        FLY.ControlLibrary.Window_Tip.Show(tit, filename, TimeSpan.FromSeconds(2));
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
                    });
                });
            }
        }

        private void SaveToXlsx(string filepath)
        {
            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }
            using (ExcelPackage p = new ExcelPackage(new FileInfo(filepath)))
            {
                ExcelWorksheet sheet = p.Workbook.Worksheets.Add("机架修正");
                DataTable dataTable = new DataTable("table_scancorr");
                dataTable.Columns.Add(new DataColumn() { ColumnName = "序号", DataType = typeof(double), Caption = "0" });
                dataTable.Columns.Add(new DataColumn() { ColumnName = "脉冲", DataType = typeof(double), Caption = "0" });
                dataTable.Columns.Add(new DataColumn() { ColumnName = "位置mm", DataType = typeof(double), Caption = "0" });
                for (int j = 0; j < SeriesInfos.Count(); j++)
                {
                    dataTable.Columns.Add(new DataColumn()
                    {
                        ColumnName = SeriesInfos[j].Name,
                        DataType = typeof(double),
                        Caption = "0"
                    });
                }

                int count = SeriesInfos.Max(cv => cv.Datas.Count());
                for (int i = 0; i < count; i++)
                {
                    var dataRow = dataTable.NewRow();
                    dataRow["序号"] = i;
                    dataRow["脉冲"] = i * PosOfGrid;
                    dataRow["位置mm"] = (int)(i * PosOfGrid * Mmpp);
                    for (int j = 0; j < SeriesInfos.Count(); j++)
                    {
                        if (i < SeriesInfos[j].Datas.Count())
                        {
                            //if(!double.IsNaN(SeriesInfos[j].Datas[i]))
潘栩锋's avatar
潘栩锋 committed
1048
                            dataRow[SeriesInfos[j].Name] = SeriesInfos[j].Datas[i];
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
                        }
                    }
                    dataTable.Rows.Add(dataRow);
                }


                ToSheet(sheet, dataTable);

                p.Save();
            }
            void ToSheet(ExcelWorksheet sheet, DataTable dataTable)
            {
                int from_row = 1;
                int row = from_row;
                //添加标题
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    int col = i + 1;
                    sheet.Cells[row, col].Value = dataTable.Columns[i].ColumnName;
                    //格式
                    sheet.Column(col).Style.Numberformat.Format = dataTable.Columns[i].Caption;
                }

                row++;
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    for (int j = 0; j < dataTable.Columns.Count; j++)
                    {
                        int col = j + 1;
                        sheet.Cells[row, col].Value = dataTable.Rows[i][j];
                    }
                    row++;
                }

                int colcnt = dataTable.Columns.Count;
                int rowcnt = dataTable.Rows.Count;
                var range = sheet.Cells[from_row, 1, from_row + rowcnt, colcnt];

                var tbl = sheet.Tables.Add(range, dataTable.TableName);
                sheet.Cells[sheet.Dimension.Address].AutoFitColumns();
            }

        }
潘栩锋's avatar
潘栩锋 committed
1092 1093 1094
        #region INotifyPropertyChanged 成员

        public event PropertyChangedEventHandler PropertyChanged;
潘栩锋's avatar
潘栩锋 committed
1095 1096
        private void NotifyPropertyChanged(string propertyName)
        {
1097 1098
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
潘栩锋's avatar
潘栩锋 committed
1099 1100 1101
        #endregion

    }
1102 1103 1104 1105

    /// <summary>
    /// 生成关键点曲线
    /// </summary>
潘栩锋's avatar
潘栩锋 committed
1106
    public class KeyPointLine : INotifyPropertyChanged
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    {
        public ObservableCollection<XY> KeyPoints { get; } = new ObservableCollection<XY>();
        public int SmoothFactor { get; set; } = 20;



        public event PropertyChangedEventHandler PropertyChanged;



        public void Add(double x, IEnumerable<double> orgDatas)
        {
1119 1120 1121
            if (x < 0 || x >= orgDatas.Count())
                return;//超出范围

1122
            int index = FindIndex(x);
1123 1124
            if (index != -1)
                return;
1125

潘栩锋's avatar
潘栩锋 committed
1126

1127 1128 1129 1130
            double y = CalY(x, orgDatas);

            //没有,可以添加
            Insert(x, y);
潘栩锋's avatar
潘栩锋 committed
1131

1132 1133 1134 1135
        }
        public void Remove(double x)
        {
            int index = FindIndex(x);
1136
            if (index == -1)
1137
                return;
1138

1139 1140 1141
            KeyPoints.RemoveAt(index);
        }

潘栩锋's avatar
潘栩锋 committed
1142 1143
        public void Clear()
        {
1144

1145 1146
            KeyPoints.Clear();
        }
1147

1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
        /// <summary>
        /// 计算 位置为x 在  orgDatas中的y
        /// </summary>
        /// <param name="x"></param>
        /// <param name="orgDatas"></param>
        /// <returns></returns>
        double CalY(double x, IEnumerable<double> orgDatas)
        {

            double sum = 0;
            int cnt = 0;
            for (int j = 0; j < SmoothFactor; j++)
            {
                int index = (int)(x - SmoothFactor / 2 + j);
                if (index < 0)
                    continue;
                else if (index >= orgDatas.Count())
                    break;

                var value = orgDatas.ElementAt(index);
                if (!double.IsNaN(value))
                {
                    sum += value;
                    cnt++;
                }
            }
            if (cnt > 0)
                return sum / cnt;
            else
                return double.NaN;
        }

        int FindIndex(double x)
        {
            for (int i = 0; i < KeyPoints.Count(); i++)
            {

                if (Math.Abs(KeyPoints[i].X - x) < SmoothFactor / 2)
                {
                    return i;
                }
            }
            return -1;
        }
        int Insert(double x, double y)
        {
            for (int i = 0; i < KeyPoints.Count(); i++)
            {
                if (x < KeyPoints[i].X)
                {
                    //就在它前面插入
                    KeyPoints.Insert(i, new XY() { X = x, Y = y });
                    return i;
                }
            }
            //在最后添加
            KeyPoints.Add(new XY() { X = x, Y = y });

            return KeyPoints.Count() - 1;
        }

        List<XY> GetKeyValues(IEnumerable<double> orgDatas)
        {
            List<XY> keyValues = new List<XY>();
            for (int i = 0; i < KeyPoints.Count(); i++)
            {
                int x = (int)KeyPoints[i].X;

                double sum = 0;
                int cnt = 0;
                for (int j = 0; j < SmoothFactor; j++)
                {
                    int index = x - SmoothFactor / 2 + j;

                    if (index < 0)
                        continue;
                    else if (index >= orgDatas.Count())
                        break;
                    var value = orgDatas.ElementAt(index);
                    if (!double.IsNaN(value))
                    {
                        sum += value;
                        cnt++;
                    }
                }
                double y;
                if (cnt > 0)
                    y = sum / cnt;
                else
                    y = double.NaN;
                keyValues.Add(new XY() { X = x, Y = y });
            }
            return keyValues;
        }

潘栩锋's avatar
潘栩锋 committed
1243 1244
        DenseVector Solve(List<XY> keyValues, int i)
        {
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
            DenseMatrix X = new DenseMatrix(3, 3);
            DenseVector Y = new DenseVector(3);
            var kv0 = keyValues[i - 1];
            var kv1 = keyValues[i];
            var kv2 = keyValues[i + 1];
            X.SetRow(0, new double[] { kv0.X * kv0.X, kv0.X, 1 });
            X.SetRow(1, new double[] { kv1.X * kv1.X, kv1.X, 1 });
            X.SetRow(2, new double[] { kv2.X * kv2.X, kv2.X, 1 });

            Y.SetValues(new double[] { kv0.Y, kv1.Y, kv2.Y });
            DenseVector abc = (DenseVector)X.Solve(Y);
            return abc;
        }
        public double[] CalFilterDatas(IEnumerable<double> orgDatas)
        {
            List<XY> keyValues = GetKeyValues(orgDatas);
            //计算每个点的2次方程 a,b,c
            List<DenseVector> abcList = new List<DenseVector>();
            for (int i = 0; i < keyValues.Count(); i++)
            {
                if (i == 0)
                {
                    DenseVector abc = Solve(keyValues, 1);
                    abcList.Add(abc);
                }
                else if (i == 1)
                {
                    abcList.Add(abcList.Last());
                }
                else if (i == keyValues.Count() - 1)
                {
                    abcList.Add(abcList.Last());
                }
潘栩锋's avatar
潘栩锋 committed
1278 1279
                else
                {
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
                    DenseVector abc = Solve(keyValues, i);
                    abcList.Add(abc);
                }
            }


            double[] filterDatas = new double[orgDatas.Count()];
            int begin = -1;
            for (int i = 0; i < keyValues.Count(); i++)
            {
                int j = (int)keyValues[i].X;
                filterDatas[j] = keyValues[i].Y;
潘栩锋's avatar
潘栩锋 committed
1292
                for (j = j - 1; j > begin; j--)
1293 1294
                {
                    double y = abcList[i][0] * j * j + abcList[i][1] * j + abcList[i][2];
潘栩锋's avatar
潘栩锋 committed
1295 1296
                    if (i - 1 >= 0)
                    {
1297 1298 1299
                        double y_pre = abcList[i - 1][0] * j * j + abcList[i - 1][1] * j + abcList[i - 1][2];
                        //权重
                        double t = (j - keyValues[i - 1].X) / (keyValues[i].X - keyValues[i - 1].X);
潘栩锋's avatar
潘栩锋 committed
1300
                        y = t * y + (1 - t) * y_pre;
1301 1302 1303 1304 1305 1306 1307 1308
                    }
                    filterDatas[j] = y;
                }
                begin = (int)keyValues[i].X;
            }
            //计算最后的
            {
                int i = keyValues.Count() - 1;
潘栩锋's avatar
潘栩锋 committed
1309 1310
                for (int j = begin + 1; j < filterDatas.Count(); j++)
                {
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
                    double y = abcList[i][0] * j * j + abcList[i][1] * j + abcList[i][2];
                    filterDatas[j] = y;
                }
            }
            return filterDatas;
        }
    }

    public enum KeyPointsSelectMode
    {
        Null,
        Add,
        Remove,
        Move
    }
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627

    public class PgScanCorrVmUt : INotifyPropertyChanged
    {

        #region 轴调节
        /// <summary>
        /// Y轴拖拉条 最大值
        /// </summary>
        public double YRangeSliderMax { get; set; } = 65535;

        /// <summary>
        /// Y轴拖拉条 最小值
        /// </summary>
        public double YRangeSliderMin { get; set; } = 0;
        #endregion


        #region 曲线
        public Func<double, string> XFormatter { get; private set; }
        public Func<double, string> YFormatter { get; private set; }

        public double XMin => 0;
        public double XMax => PosLength / PosOfGrid;


        /// <summary>
        /// Y轴 最大值
        /// </summary>
        public double YMax { get; set; } = 65535;

        /// <summary>
        /// Y轴 最小值
        /// </summary>
        public double YMin { get; set; }


        public SeriesCollection Series { get; } = new SeriesCollection();

        public class SeriesInfo : INotifyPropertyChanged
        {
            public string Name { get; set; }
            public Brush Color { get; set; }

            public ChartValues<double> Datas = new ChartValues<double>();

            public event PropertyChangedEventHandler PropertyChanged;
        }
        public SeriesInfo[] SeriesInfos { get; set; }

        CartesianMapper<XY> Mapper { get; set; }

        #endregion

        /// <summary>
        /// 机架总长,脉冲
        /// </summary>
        public int PosLength { get; set; } = 8000;

        /// <summary>
        /// 1个grid = N个pos
        /// </summary>
        public int PosOfGrid { get; set; } = 10;

        /// <summary>
        /// 比例
        /// </summary>
        public double Mmpp { get; set; } = 0.1;




        #region

        /// <summary>
        /// 使能修正
        /// </summary>
        public bool Enable { set; get; }

        /// <summary>
        /// 当前修正的组
        /// </summary>
        public int CurrGroupIndex { get; set; }

        /// <summary>
        /// 当前进度 0 - 100 
        /// </summary>
        public int Progress { get; set; }

        /// <summary>
        /// 数据更新时间
        /// </summary>
        public DateTime[] UpdateTimes { get; set; }

        /// <summary>
        /// 正在机架修正中
        /// </summary>
        public bool IsRunning { get; set; }

        /// <summary>
        /// 来回次数
        /// </summary>
        public int ScanCnt { get; set; }


        #endregion

        /// <summary>
        /// 当前被选择的组序号
        /// </summary>
        public int SelectedGroupIndex { get; set; }


        #region 平滑方式生成修正曲线

        /// <summary>
        /// 平均滤波平滑数,单位grid
        /// </summary>
        public int SmoothFactor { get; set; } = 20;
        #endregion

        #region 关键点方式生成修正曲线


        public KeyPointsSelectMode KpSelectMode { get; set; } = KeyPointsSelectMode.Null;

        #endregion

        /// <summary>
        /// 数据好了!!!!
        /// 当 flyad7 的poslen, posOfGrid 发生变化时,DataOK = false, 需要重新记录。
        /// </summary>
        public bool IsDataOK { get; set; } = false;

        public int AvgAd { get; set; }

        public RelayCommand SelectedGroup0Cmd { get; }
        public RelayCommand SelectedGroup1Cmd { get; }

        public RelayCommand StopCmd { get; }
        public RelayCommand StartCmd { get; }

        public RelayCommand ClearCmd { get; }

        public RelayCommand CreateCorrBySmoothCmd { get; }
        public RelayCommand CreateCorrByKeyPointCmd { get; }
        /// <summary>
        /// 添加关键点模式
        /// </summary>
        public RelayCommand AddKeyPointModeCmd { get; }
        public RelayCommand RemoveKeyPointModeCmd { get; }
        public RelayCommand MoveKeyPointModeCmd { get; }
        public RelayCommand CancelKeyPointModeCmd { get; }
        public RelayCommand SetCorrDataCmd { get; }


        public PgScanCorrVmUt()
        {
            #region 与数据无关界面参数

            XFormatter = (x) =>
            {
                //x 是 grid
                int pos = (int)(x * PosOfGrid);
                int mm = (int)(pos * Mmpp);
                return $"{pos}\n{mm}mm";
            };
            YFormatter = (y) =>
            {
                return $"{y:F0}";
            };
            //Mapper = Mappers.Xy<XY>()
            //    .X((value, index) => value.X)
            //    .Y(value => value.Y);

            SeriesInfos = new SeriesInfo[] {
                new SeriesInfo(){Name = "正向原始", Color = FLY.ControlLibrary.Themes.Styles.GetForeground(0)},
                new SeriesInfo(){Name = "反向原始", Color = FLY.ControlLibrary.Themes.Styles.GetForeground(1)},
                new SeriesInfo(){Name = "正向滤波", Color = FLY.ControlLibrary.Themes.Styles.GetForeground(0, true)},
                new SeriesInfo(){Name = "反向滤波", Color = FLY.ControlLibrary.Themes.Styles.GetForeground(1, true)},
            };

            for (int i = 0; i < SeriesInfos.Count(); i++)
            {
                var seriesInfo = SeriesInfos[i];
                var lineSeries = new LineSeries
                {
                    Values = seriesInfo.Datas,
                    StrokeThickness = 2,
                    Title = seriesInfo.Name,
                    Fill = new SolidColorBrush(System.Windows.Media.Colors.Transparent),
                    Stroke = seriesInfo.Color,
                    PointGeometry = null,
                    Configuration = Mapper
                };
                Series.Add(lineSeries);
            }

            #endregion

            PosLength = 24000;
            PosOfGrid = 24;
            Mmpp = 0.1135;
            int gridLen = PosLength / PosOfGrid;
            Random random = new Random();
            int[] orgDatas0 = new int[gridLen];
            int[] orgDatas1 = new int[gridLen];
            int avgAd = 50300;
            int tolerance = 500;
            for (int i = 0; i < gridLen; i++)
            {
                int ad = (int)(Math.Sin(1.0 * i / (gridLen / 3) * Math.PI) * tolerance) + avgAd;
                orgDatas0[i] = ad + (random.Next(10) - 5);
                orgDatas1[i] = ad + (random.Next(10) - 5);
            }

            int[] corrDatas0 = Smooth(orgDatas0);
            int[] corrDatas1 = Smooth(orgDatas1);
            int avg = avgAd;

            GetScanCorrGroupResponse response = new GetScanCorrGroupResponse();
            response.Avg = avg;
            response.OrgDatas = new int[][] { orgDatas0, orgDatas1 };
            response.CorrDatas = new int[][] { corrDatas0, corrDatas1 };

            UpdateTimes = new DateTime[2];
            scanCorrService_GetScanCorrGroup(0, response);

        }
        int[] Smooth(int[] orgDatas, int smoothFactor = 50)
        {

            var filters = new int[orgDatas.Count()];
            for (int i = 0; i < orgDatas.Count(); i++)
            {
                int sum = 0;
                int cnt = 0;
                for (int j = 0; j < smoothFactor; j++)
                {
                    int index = i - smoothFactor / 2;
                    if (index < 0)
                        continue;
                    else if (index >= orgDatas.Count())
                        break;

                    if (Misc.MyBase.ISVALIDATA(orgDatas[index]))
                    {
                        sum += orgDatas[index];
                        cnt++;
                    }
                }
                if (cnt > 0)
                    filters[i] = sum / cnt;
                else
                    filters[i] = Misc.MyBase.NULL_VALUE;
            }
            return filters;
        }

        void scanCorrService_GetScanCorrGroup(object asyncContext, object retData)
        {

            var reponse = retData as GetScanCorrGroupResponse;
            int groupIndex = reponse.GroupIndex;
            UpdateTimes[groupIndex] = reponse.UpdateTime;
            AvgAd = reponse.Avg;
            IsDataOK = reponse.IsDataOK;

            SeriesInfos[0].Datas.Clear();
            SeriesInfos[1].Datas.Clear();
            SeriesInfos[2].Datas.Clear();
            SeriesInfos[3].Datas.Clear();

            if (reponse.OrgDatas == null || reponse.OrgDatas.Count() != 2)
                return;

            SeriesInfos[0].Datas.AddRange(reponse.OrgDatas[0].Select(ad => Misc.MyBase.ISVALIDATA(ad) ? ad : double.NaN));
            SeriesInfos[1].Datas.AddRange(reponse.OrgDatas[1].Select(ad => Misc.MyBase.ISVALIDATA(ad) ? ad : double.NaN));

            int max = (int)SeriesInfos[0].Datas.Max();
            int min = (int)SeriesInfos[0].Datas.Min();
            //设置Y轴范围
            YMax = max;
            YMin = min;

            if (reponse.CorrDatas == null || reponse.CorrDatas.Count() != 2)
                return;

            SeriesInfos[2].Datas.AddRange(reponse.CorrDatas[0].Select(ad => Misc.MyBase.ISVALIDATA(ad) ? ad : double.NaN));
            SeriesInfos[3].Datas.AddRange(reponse.CorrDatas[1].Select(ad => Misc.MyBase.ISVALIDATA(ad) ? ad : double.NaN));

        }




        #region INotifyPropertyChanged 成员

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

    }
潘栩锋's avatar
潘栩锋 committed
1628
}