PgScanCorrVm.cs 35.5 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
1 2 3 4 5
using FLY.Thick.Base.IService;
using GalaSoft.MvvmLight.Command;
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 10
using OfficeOpenXml;
using OfficeOpenXml.Table;
潘栩锋's avatar
潘栩锋 committed
11 12 13 14
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
15 16
using System.Data;
using System.IO;
潘栩锋's avatar
潘栩锋 committed
17 18 19
using System.Linq;
using System.Text;
using System.Threading.Tasks;
20
using System.Windows;
潘栩锋's avatar
潘栩锋 committed
21 22 23 24 25 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
using System.Windows.Media;

namespace FLY.Thick.Base.UI
{
    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;
        public double XMax => PosLength/PosOfGrid;

        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; }

97
        ChartValues<XY> KeyPointDatas = new ChartValues<XY>();
潘栩锋's avatar
潘栩锋 committed
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 153 154 155 156 157 158 159 160 161 162 163 164 165
        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>
166
        public int SmoothFactor { get; set; } = 50;
潘栩锋's avatar
潘栩锋 committed
167 168 169 170
        #endregion

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

171 172 173

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

潘栩锋's avatar
潘栩锋 committed
174 175 176 177 178 179 180 181
        #endregion

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

182
        public double AvgAd { get; set; }
潘栩锋's avatar
潘栩锋 committed
183

184
        #region CMD
185 186 187 188
        public RelayCommand SelectedGroup0Cmd { get; }
        public RelayCommand SelectedGroup1Cmd { get; }

        public RelayCommand StopCmd { get; }
潘栩锋's avatar
潘栩锋 committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
        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; }

204 205
        public RelayCommand SaveXlsxCmd { get; }
        public RelayCommand LoadXlsxCmd { get; }
潘栩锋's avatar
潘栩锋 committed
206

207 208
        #endregion

潘栩锋's avatar
潘栩锋 committed
209 210
        IScanCorrService scanCorrService;
        IInitParamService initParamService;
211
        ITDGageService gageService;
212
        KeyPointLine keyPointLine;
潘栩锋's avatar
潘栩锋 committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

        public PgScanCorrVm()
        {
            #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}";
            };
229 230 231
            Mapper = Mappers.Xy<XY>()
                .X((value, index) => value.X)
                .Y(value => value.Y);
潘栩锋's avatar
潘栩锋 committed
232 233 234 235

            SeriesInfos = new SeriesInfo[] {
                new SeriesInfo(){Name = "正向原始", Color = FLY.ControlLibrary.Themes.Styles.GetForeground(0)},
                new SeriesInfo(){Name = "反向原始", Color = FLY.ControlLibrary.Themes.Styles.GetForeground(1)},
236 237
                new SeriesInfo(){Name = "正向滤波", Color = FLY.ControlLibrary.Themes.Styles.GetForeground(0,true)},
                new SeriesInfo(){Name = "反向滤波", Color = FLY.ControlLibrary.Themes.Styles.GetForeground(1,true)},
潘栩锋's avatar
潘栩锋 committed
238 239
            };

240 241 242



潘栩锋's avatar
潘栩锋 committed
243 244 245 246 247 248 249 250 251
            for (int i = 0; i < SeriesInfos.Count(); i++)
            {
                var seriesInfo = SeriesInfos[i];
                var lineSeries = new LineSeries
                {
                    Values = seriesInfo.Datas,
                    StrokeThickness = 2,
                    Fill = new SolidColorBrush(System.Windows.Media.Colors.Transparent),
                    Stroke = seriesInfo.Color,
252
                    PointGeometry = null
潘栩锋's avatar
潘栩锋 committed
253 254 255 256
                };
                Series.Add(lineSeries);
            }

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
            keyPointLine = new KeyPointLine();
            Misc.BindingOperations.SetBinding(this, nameof(SmoothFactor), keyPointLine, nameof(keyPointLine.SmoothFactor));
            {
                var lineSeries = new LineSeries
                {
                    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
277 278
            #endregion

279
            StopCmd = new RelayCommand(Stop);
潘栩锋's avatar
潘栩锋 committed
280 281 282 283 284 285 286 287 288
            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);
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

            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;

            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));

            UpdateTimes = new DateTime[2];
            downloadAll();

            this.PropertyChanged += PgScanCorrVm_PropertyChanged;

            this.scanCorrService.PropertyChanged += ScanCorrService_PropertyChanged;
        }

        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();
                }
            }
            else if (e.PropertyName == nameof(scanCorrService.UpdateTimes)) {
                if (UpdateTimes[SelectedGroupIndex] != scanCorrService.UpdateTimes[SelectedGroupIndex]) {
                    //当前显示的,发生变化了,下载
                    downloadAll();
                }
            }
潘栩锋's avatar
潘栩锋 committed
345 346 347 348 349 350 351 352 353 354 355 356
        }

        private void Clear()
        {
            scanCorrService.Clear(SelectedGroupIndex);
            FLY.ControlLibrary.Window_Tip.Show("成功",
                $"清除{SelectedGroupIndex}组数据成功",
                TimeSpan.FromSeconds(2));
        }

        private void Start()
        {
357
            scanCorrService.Start(SelectedGroupIndex, ScanCnt, SmoothFactor);
潘栩锋's avatar
潘栩锋 committed
358 359 360 361 362
            FLY.ControlLibrary.Window_Tip.Show("准备开始",
                null,
                TimeSpan.FromSeconds(2));
        }

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
        private void Stop()
        {
            gageService.StartP2(Base.Common.STARTP2_MODE.STOP);
            FLY.ControlLibrary.Window_Tip.Show("停止",
                null,
                TimeSpan.FromSeconds(2));
        }
        private void SelectedGroup1()
        {
            SelectedGroupIndex = 1;
        }

        private void SelectedGroup0()
        {
            SelectedGroupIndex = 0;
        }

潘栩锋's avatar
潘栩锋 committed
380 381 382 383 384 385 386 387 388 389 390 391 392
        private void SetCorrData()
        {
            //TODO
            //判断是否有数据
            for (int i = 2; i <= 3; i++) { 
                
            }

            int[][] corrDatas = new int[2][];
            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();

            //发送出去
393
            scanCorrService.SetCorrData(SelectedGroupIndex, corrDatas, (int)AvgAd);
潘栩锋's avatar
潘栩锋 committed
394 395 396 397 398 399 400 401 402

            FLY.ControlLibrary.Window_Tip.Show("应用成功",
                null,
                TimeSpan.FromSeconds(2));

        }

        private void MoveKeyPointMode()
        {
403
            KpSelectMode = KeyPointsSelectMode.Move;
潘栩锋's avatar
潘栩锋 committed
404 405 406 407
        }

        private void RemoveKeyPointMode()
        {
408
            KpSelectMode = KeyPointsSelectMode.Remove;
潘栩锋's avatar
潘栩锋 committed
409 410 411 412
        }

        private void AddKeyPointMode()
        {
413
            KpSelectMode = KeyPointsSelectMode.Add;
潘栩锋's avatar
潘栩锋 committed
414 415
        }
        private void CancelKeyPointMode() {
416
            KpSelectMode = KeyPointsSelectMode.Null;
潘栩锋's avatar
潘栩锋 committed
417 418 419 420 421
        }


        private void CreateCorrByKeyPoint()
        {
422
            CancelKeyPointMode();
潘栩锋's avatar
潘栩锋 committed
423

424 425 426 427 428 429 430 431 432 433 434
            if (keyPointLine.KeyPoints.Count() < 3)
            {
                //少于3个点
                FLY.ControlLibrary.Window_WarningTip.Show("异常", $"关键点必须≥3个", TimeSpan.FromSeconds(2));
                return;
            }
            for (int i = 0; i < 2; i++) {
                var filterDatas = keyPointLine.CalFilterDatas(SeriesInfos[i].Datas);
                SeriesInfos[i + 2].Datas.Clear();
                SeriesInfos[i + 2].Datas.AddRange(filterDatas);
            }
潘栩锋's avatar
潘栩锋 committed
435

436 437 438 439
            //计算平均值
            double avg0 = SeriesInfos[2].Datas.AverageNoNull();
            double avg1 = SeriesInfos[3].Datas.AverageNoNull();
            AvgAd = (int)((avg0 + avg1) / 2);
潘栩锋's avatar
潘栩锋 committed
440

441 442 443
            FLY.ControlLibrary.Window_Tip.Show("生成成功",
                null,
                TimeSpan.FromSeconds(2));
潘栩锋's avatar
潘栩锋 committed
444 445 446 447 448 449 450 451 452 453 454 455 456
        }



        void Smooth(ChartValues<double> orgDatas, ChartValues<double> filterDatas) {

            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++)
                {
457
                    int index = i - SmoothFactor / 2 + j;
潘栩锋's avatar
潘栩锋 committed
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
                    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()
        {
            for(int i=0;i<2;i++)
                Smooth(SeriesInfos[i].Datas, SeriesInfos[2+i].Datas);

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

            FLY.ControlLibrary.Window_Tip.Show("生成成功",
                null,
                TimeSpan.FromSeconds(2));
        }




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

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

504
            keyPointLine.Clear();
潘栩锋's avatar
潘栩锋 committed
505 506 507 508 509 510 511 512
        }

        void scanCorrService_GetScanCorrGroup(object asyncContext, object retData)
        {

            var reponse = retData as GetScanCorrGroupResponse;
            int groupIndex = reponse.GroupIndex;
            UpdateTimes[groupIndex] = reponse.UpdateTime;
513
            AvgAd = Misc.MyBase.ISVALIDATA(reponse.Avg) ? reponse.Avg : double.NaN;
潘栩锋's avatar
潘栩锋 committed
514 515 516 517 518 519 520
            IsDataOK = reponse.IsDataOK;

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

521 522
            if (reponse.OrgDatas == null || reponse.OrgDatas.Count() != 2)
                return;
潘栩锋's avatar
潘栩锋 committed
523

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

528 529 530 531 532 533 534
            var list = SeriesInfos[0].Datas.Where((d) =>
            {
                if (double.IsNaN(d))
                    return false;
                else
                    return true;
            });
535
            //设置Y轴范围
536 537
            int max = (int)list.Max();
            int min = (int)list.Min();
538 539 540 541 542
            //扩大3倍显示
            int range = max - min;
            if (range == 0)
            {
                //异常
潘栩锋's avatar
潘栩锋 committed
543
            }
544
            else
潘栩锋's avatar
潘栩锋 committed
545
            {
546 547 548 549
                ymax = max + range / 4;
                ymin = min - range / 4;
                YRangeSliderMin = min - range;
                YRangeSliderMax = max + range;
潘栩锋's avatar
潘栩锋 committed
550 551
            }

552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
            NotifyPropertyChanged(nameof(YMax));
            NotifyPropertyChanged(nameof(YMin));


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

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




            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
570 571 572 573 574 575 576 577 578
        }
        private void PgScanCorrVm_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(SelectedGroupIndex))
            {
                downloadAll();
            }
        }

579 580 581 582 583 584 585 586 587

        public enum SelectType
        {
            Click,
            Move,
            Cancel
        }
        
        public void Select(SelectType selectType, System.Windows.Point cpBegin, System.Windows.Point cpEnd)
潘栩锋's avatar
潘栩锋 committed
588
        {
589
            if (KpSelectMode == KeyPointsSelectMode.Null)
潘栩锋's avatar
潘栩锋 committed
590
                return;
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
            switch (KpSelectMode) {
                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
610

611 612 613 614
        void UpdateKeyPointDatas() 
        {
            KeyPointDatas.Clear();
            KeyPointDatas.AddRange(keyPointLine.KeyPoints);
潘栩锋's avatar
潘栩锋 committed
615 616 617
        }


618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 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 836 837 838 839 840 841 842 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
        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)
                {
                    //画图

                    FLY.ControlLibrary.Window_Tip.Show("成功", $"加载{filename}", TimeSpan.FromSeconds(2));
                }
                else
                {
                    MessageBox.Show($"{error}", $"加载{filename}失败", MessageBoxButton.OK, MessageBoxImage.Error);
                }

            }
        }
        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(() =>
            {
                for (int j = 2; j <= 3; j++)
                {
                    List<double> datas = new List<double>();
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        var dataRow = dataTable.Rows[i];
                        
                        double ad = System.Convert.ToDouble(dataRow[SeriesInfos[j].Name]);
                        datas.Add(ad);
                    }
                    SeriesInfos[j].Datas.Clear();
                    SeriesInfos[j].Datas.AddRange(datas);
                    datas.AverageNoNull();

                }
                double avg0 = SeriesInfos[2].Datas.AverageNoNull();
                double avg1 = SeriesInfos[3].Datas.AverageNoNull();
                if (!double.IsNaN(avg0) && !double.IsNaN(avg1)) {
                    //异常
                    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);

                    App.Current.Dispatcher.Invoke(() =>
                    {
                        FLY.ControlLibrary.Window_Tip.Show("成功", $"导出到{filename}", TimeSpan.FromSeconds(2));
                    });
                });
            }
        }

        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]))
                                dataRow[SeriesInfos[j].Name] = SeriesInfos[j].Datas[i];
                        }
                    }
                    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
872 873 874
        #region INotifyPropertyChanged 成员

        public event PropertyChangedEventHandler PropertyChanged;
875 876 877
        private void NotifyPropertyChanged(string propertyName) {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
潘栩锋's avatar
潘栩锋 committed
878 879 880
        #endregion

    }
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897

    /// <summary>
    /// 生成关键点曲线
    /// </summary>
    public class KeyPointLine:INotifyPropertyChanged
    {
        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)
        {
898 899 900
            if (x < 0 || x >= orgDatas.Count())
                return;//超出范围

901
            int index = FindIndex(x);
902 903
            if (index != -1)
                return;
904

905 906 907 908 909 910
                
            double y = CalY(x, orgDatas);

            //没有,可以添加
            Insert(x, y);
            
911 912 913 914
        }
        public void Remove(double x)
        {
            int index = FindIndex(x);
915
            if (index != -1)
916
                return;
917

918 919 920 921
            KeyPoints.RemoveAt(index);
        }

        public void Clear() {
922

923 924
            KeyPoints.Clear();
        }
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 1004 1005 1006 1007 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 1048 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 1092 1093 1094 1095 1096 1097 1098 1099
        /// <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;
        }

        DenseVector Solve(List<XY> keyValues, int i) {
            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());
                }
                else {
                    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;
                for (j=j-1; j > begin; j--)
                {
                    double y = abcList[i][0] * j * j + abcList[i][1] * j + abcList[i][2];
                    if (i - 1 >= 0) {
                        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);
                        y = t*y +(1 - t) * y_pre;
                    }
                    filterDatas[j] = y;
                }
                begin = (int)keyValues[i].X;
            }
            //计算最后的
            {
                int i = keyValues.Count() - 1;
                for (int j = begin + 1; j < filterDatas.Count(); j++) {
                    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
    }
潘栩锋's avatar
潘栩锋 committed
1100
}