ningshuxia
2025-04-16 a67da735b33be01b24845ce03ae7551cf55ddbbc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
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
225
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
282
283
284
285
286
287
288
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
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
917
918
919
920
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
using DevExpress.XtraCharts;
using DevExpress.XtraEditors;
using IStation.Epanet;
using IStation.Epanet.Enums;
using IStation.Model;
using IStation.Untity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
 
namespace IStation.WinFrmUI.Monitor
{
    public partial class ModelCorrectionCombinePage : DocumentPage
    {
        public ModelCorrectionCombinePage()
        {
            InitializeComponent();
            PageTitle.Caption = "模型修正组合";
 
            gridView1.SetNormalView();
            gridView2.SetNormalView();
            gridView3.SetNormalView();
 
            colHz.Visible = false;
            colRpm.Visible = false;
            colWaterLevel.Visible = false;
 
 
            repositoryItemDateEdit1.SetOnlyShowYearMonth();
            repositoryItemDateEdit2.SetOnlyShowYearMonth();
            barEditDateStart.EditValue = new DateTime(2024, 1, 1);
            barEditDateEnd.EditValue = new DateTime(2024, 9, 1);
 
            cmbFlag.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            barCekUseFlow.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
 
            stationListCtrl1.FocusedChangedEvent += StationListCtrl1_FocusedChangedEvent;
            monitorDataSourcesTreeList1.FocusedChangedEvent += MonitorDataSourcesListCtrl1_FocusedChangedEvent;
            timeValueSwiftPlotChartView1.SetTimeAxisX(DevExpress.XtraCharts.DateTimeMeasureUnit.Minute);
            InitialDiagarm();
        }
 
 
        private Series _series_default_head; //
        private Series _series_curve_head; //
        private Series _series_correct_curve_head; // 
 
        private double _min_flow = 0;
        private double _max_flow = 100000;
        private double _space_flow = 500;
        private void InitialDiagarm()
        {
            chartControl1.Legend.Visibility = DevExpress.Utils.DefaultBoolean.False;//是否在图表上显示图例 
 
            var diagram = (SwiftPlotDiagram)chartControl1.Diagram;
            diagram.EnableAxisXScrolling = true;//X轴是否允许滚动
            diagram.EnableAxisXZooming = true;//X轴是否允许缩放
            diagram.PaneLayout.Direction = PaneLayoutDirection.Vertical;//窗格的对齐方式 
            diagram.AxisX.DateTimeScaleOptions.MeasureUnit = DateTimeMeasureUnit.Minute;
 
            _series_default_head = chartControl1.GetSeriesByName("SeriesDefaultHead");
            _series_curve_head = chartControl1.GetSeriesByName("SeriesCurveHead");
            _series_correct_curve_head = chartControl1.GetSeriesByName("SeriesCorrectCurveHead");
 
            _series_default_head.CrosshairLabelPattern = "监测压力:{V}";
            _series_curve_head.CrosshairLabelPattern = "模型压力:{V}";
            _series_correct_curve_head.CrosshairLabelPattern = "压力偏差:{V}";
        }
 
 
        #region ViewModel  
 
        public class PumpViewModel
        {
 
            [Display(Name = "时间")]
            public string Time { get; set; }
 
            [Display(Name = "泵")]
            public int Flag { get; set; }
 
            [Display(Name = "转速")]
            public double Rpm { get; set; }
 
            [Display(Name = "频率")]
            public double Hz { get; set; }
 
            [Display(Name = "频率")]
            public double Hz0 { get; set; }
 
            [Display(Name = "水位")]
            public double WaterLevel { get; set; }
 
            [Display(Name = "进口压力")]
            public double InletPressure { get; set; }
 
            [Display(Name = "出口压力")]
            public double OutletPressure { get; set; }
 
            [Display(Name = "模型出口压力")]
            public double ModelOutletPressure { get; set; }
 
            [Display(Name = "瞬时流量")]
            public double Flow { get; set; }
 
            [Display(Name = "模型流量")]
            public double ModelFlow { get; set; }
 
            [Display(Name = "流量差值")]
            public double FlowDiff { get; set; }
 
 
            [Display(Name = "压差")]
            public double PressureDiff { get; set; }
 
            [Display(Name = "曲线压差")]
            public double CurvePressureDiff { get; set; }
 
            [Display(Name = "压差差值")]
            public double PressureDiffDev { get; set; }
 
        }
 
        public class ModelCombineViewModel
        {
            public string Time { get; set; }
            public string RunFlags { get; set; }
            public double ScadaTotalFlow { get; set; }
            public double ModelTotalFlow { get; set; }
            public List<Tuple<int, double, double>> ModelDeviation { get; set; }
        }
 
        public class ModelDiffViewModel
        {
            [Display(Name = "时间")]
            public DateTime Date { get; set; }
 
            [Display(Name = "时间")]
            public string Time { get; set; }
 
            [Display(Name = "名称")]
            public string Name { get; set; }
 
            [Display(Name = "监测压力")]
            public double ScadaPressure { get; set; }
 
            [Display(Name = "监测流量")]
            public double ScadaFlow { get; set; }
 
            [Display(Name = "模型压力")]
            public double MonitorPressure { get; set; }
 
            [Display(Name = "模型流量")]
            public double MonitorFlow { get; set; }
 
            [Display(Name = "压力偏差")]
            public double PressureDiff { get; set; }
 
            [Display(Name = "流量偏差")]
            public double FlowDiff { get; set; }
 
        }
 
 
        /// <summary>
        /// 模型组合偏差
        /// </summary>   
        public class ModelCombineDiffViewModel
        {
 
            [Display(Name = "运行组合")]
            public string RunFlags { get; set; }
 
            [Display(Name = "最小流量")]
            public double MinFlow { get; set; }
 
            [Display(Name = "最大流量")]
            public double MaxFlow { get; set; }
 
            [Display(Name = "模型偏差")]
            public string ModelDeviation { get; set; }
 
            [Display(Name = "数量")]
            public int Count { get; set; }
 
        }
 
        public class PumpFactorViewModel
        {
            [Display(Name = "泵")]
            public int Flag { get; set; }
 
            [Display(Name = "频率")]
            public double Hz { get; set; }
 
            [Display(Name = "总体标准差")]
            public double? STDP { get; set; }
 
            [Display(Name = "扬程(STDP)")]
            public double? STDPHead { get; set; }
 
 
            [Display(Name = "备注")]
            public string Note { get; set; }
 
            public void Round()
            {
                if (STDP.HasValue)
                {
                    STDP = Math.Round(STDP.Value, 5);
                }
                if (STDPHead.HasValue)
                {
                    STDPHead = Math.Round(STDPHead.Value, 5);
                }
 
            }
        }
 
 
        #endregion
 
        private BLL.StationSignalRecordPacket _bll = new BLL.StationSignalRecordPacket();
        private Model.Station _station = null;
        private Model.MonitorDataSources _monitorDataSources = null;
 
        private List<Model.Equipment<Model.Pump>> _pump_list = null;
        private List<ModelDiffViewModel> _model_diff_vm_list = null;
        private List<ModelCombineViewModel> _model_combine_list = null;
        private List<ModelCombineDiffViewModel> _model_combine_diff_vm_list = null;
        private List<PumpViewModel> _pump_vm_list = null;
 
        private string _model_file = System.IO.Path.Combine
            (SettingsD.File.RootDirectory, SettingsD.File.DataFolder, "ch2_v3_20240801(Clear).inp");
 
        /// <summary>
        /// 清空数据
        /// </summary>
        public void Clear()
        {
            _pump_vm_list = new List<PumpViewModel>();
            _model_diff_vm_list = new List<ModelDiffViewModel>();
            _model_combine_list = new List<ModelCombineViewModel>();
            _model_combine_diff_vm_list = new List<ModelCombineDiffViewModel>();
            cmbFlag.SelectedItem = null;
            cmbFlag.Properties.Items.Clear();
            modelTimeViewModelBindingSource.DataSource = new List<ModelDiffViewModel>();
            modelCombineDiffViewModelBindingSource.DataSource = new List<ModelCombineDiffViewModel>();
            pumpViewModelBindingSource.DataSource = new List<PumpViewModel>();
 
            ClearChart();
        }
 
        private void ClearChart()
        {
 
            chartControl1.BeginInit();
            _series_default_head.Points.Clear();
            _series_curve_head.Points.Clear();
            _series_correct_curve_head.Points.Clear();
            chartControl1.EndInit();
        }
 
        /// <summary>
        /// 初始化数据
        /// </summary>
        public override void InitialDataSource()
        {
            stationListCtrl1.SetBindingData();
            monitorDataSourcesTreeList1.SetBindingData();
        }
 
        //泵站变换
        private void StationListCtrl1_FocusedChangedEvent(Model.Station obj)
        {
            _station = obj;
            WaitFrmHelper.ShowWaitForm();
            SetBindingData(_monitorDataSources, _station);
            WaitFrmHelper.HideWaitForm();
 
        }
 
        //来源变换
        private void MonitorDataSourcesListCtrl1_FocusedChangedEvent(Model.MonitorDataSources obj)
        {
            _monitorDataSources = obj;
            WaitFrmHelper.ShowWaitForm();
            SetBindingData(_monitorDataSources, _station);
            WaitFrmHelper.HideWaitForm();
        }
 
 
        /// <summary>
        /// 绑定数据
        /// </summary>
        public void SetBindingData(Model.MonitorDataSources monitorDataSources, Model.Station station)
        {
 
            Clear();
            if (monitorDataSources == null || station == null)
            {
                return;
            }
            if (barCekLoad.Checked)
            {
                return;
            }
 
 
            var station_index = station.SortCode;
            var dt_start = Convert.ToDateTime(barEditDateStart.EditValue);
            var dt_end = Convert.ToDateTime(barEditDateEnd.EditValue);
            var packets = _bll.Get(monitorDataSources.ID, station.ID);
            packets = packets?.Where(x => (x.Year >= dt_start.Year && x.Year <= dt_end.Year) && (x.Month >= dt_start.Month && x.Month <= dt_end.Month)).ToList();
            if (packets == null || !packets.Any())
                return;
 
            _pump_list = new BLL.Equipment().GetPumpListByBelongTypeAndBelongID(IStation.ObjectType.Station, station.ID);
            if (_pump_list == null || !_pump_list.Any())
            {
                return;
            }
            var flag_pump_dict = _pump_list.ToDictionary(x => x.SortCode, x => x.RatedParas);
            var flag_list = _pump_list.Select(x => x.SortCode).OrderBy(x => x).ToList();
            cmbFlag.Properties.Items.AddRange(flag_list);
            var record_list = packets.SelectMany(x => x.StationSignalRecords).ToList();
 
            var root_folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "分析");
            List<AnalysisHelper.AnalysisFactorDto> ana_factor_list = null;
            var fileName = root_folder + "\\" + "AnalysisFactor.json";
            if (File.Exists(fileName))
            {
                var json = File.ReadAllText(fileName);
                ana_factor_list = JsonHelper.Json2Object<List<AnalysisHelper.AnalysisFactorDto>>(json);
            }
 
 
            SetBindingData(_model_file, station.SortCode, flag_pump_dict, record_list, ana_factor_list, barCekUseAnalysisFactor.Checked);
        }
 
 
        /// <summary>
        /// 绑定数据
        /// </summary>
        public void SetBindingData
            (
            string model_inp,
            int station_index,
            Dictionary<int, Model.Pump> flag_pump_dict,
            List<Model.StationSignalRecord> station_record_list,
            List<AnalysisHelper.AnalysisFactorDto> ana_factor_list,
            bool use_ana_factor
            )
        {
            if (!File.Exists(model_inp))
            {
                throw new Exception($"model_inp:is null");
            }
 
            var bll_curve = new BLL.PumpCurve();
            var temp_id_build = new StringBuilder(31);
            var err = EpanetMethods.ENopen(_model_file, "", "");
            if ((int)err > 6)
            {
                throw new Exception($"ENopen:{err}");
            }
 
            err = EpanetMethods.ENopenH();
            if ((int)err > 6)
            {
                throw new Exception($"ENopenH:{err}");
            }
 
            var curve_point_count = 100;
            var flag_qh_curve_dict = GetFlagCurveDict();
            var pipe_flow_id_list = GlobalHelperW.GetPipeFlowIdList(station_index);
            var pipe_pressure_id_list = GlobalHelperW.GetPipePressureIdList(station_index);
 
            var pump_model_mapping_list = AnalysisHelper.GetPumpModelMappingList();
            var model_mapping_list = AnalysisHelper.GetStationMappingList();
 
            foreach (var item in pump_model_mapping_list)
            {
                var flag = item.Flag;
 
                if (EpanetMethods.ENgetlinkindex(item.PumpId, out int pump_index) != ErrorCode.Ok)
                    throw new Exception($"ENgetlinkindex:{err}");
 
                if (!string.IsNullOrEmpty(item.FlowId))
                {
                    if (EpanetMethods.ENgetlinkindex(item.FlowId, out int flow_index) != ErrorCode.Ok)
                        throw new Exception($"ENgetlinkindex:{err}");
                    item.FlowIndex = flow_index;
                }
 
                if (EpanetMethods.ENgetnodeindex(item.PressureId, out int pressure_index) != ErrorCode.Ok)
                    throw new Exception($"ENgetnodeindex:{err}");
 
                if (EpanetMethods.ENgetcurveindex(item.CurveId, out int curve_index) != ErrorCode.Ok)
                    throw new Exception($"ENgetcurveindex:{err}");
 
                item.PumpIndex = pump_index;
                item.PressureIndex = pressure_index;
                item.CurveIndex = curve_index;
 
 
                var qh = flag_qh_curve_dict[flag];
                var fit_point_list = qh.GetFitPoints(curve_point_count);
                var flow_list = fit_point_list.Select(x => (float)x.X).ToArray();
                var head_list = fit_point_list.Select(x => (float)x.Y).ToArray();
 
 
                var cek = CheckFitPointList(fit_point_list, curve_point_count);
                if (!cek)
                {
                    throw new Exception($"CheckFitPointList: false");
                }
                err = EpanetMethods.ENsetcurve(item.CurveIndex, flow_list, head_list, curve_point_count);
                if (err != 0)
                {
                    throw new Exception($"ENsetcurve:{err}");
                }
            }
 
            foreach (var item in model_mapping_list)
            {
 
                if (EpanetMethods.ENgetlinkindex(item.FlowId, out int flow_index) != ErrorCode.Ok)
                    throw new Exception($"ENgetlinkindex:{err}");
 
                if (EpanetMethods.ENgetnodeindex(item.PressureId, out int pressure_index) != ErrorCode.Ok)
                    throw new Exception($"ENgetnodeindex:{err}");
 
                item.PressureIndex = pressure_index;
                item.FlowIndex = flow_index;
 
            }
 
            var pump_model_mapping_dict = pump_model_mapping_list.ToDictionary(x => x.Flag, y => y);
            var pattern_id_list = AnalysisHelper.GetPatternIdList();
            var pattern_id_dict = new Dictionary<string, int>();
            foreach (var id in pattern_id_list)
            {
                if (EpanetMethods.ENgetpatternindex(id, out int index) != ErrorCode.Ok)
                    continue;
                pattern_id_dict.Add(id, index);
            }
             
 
            var vm_list = new List<PumpViewModel>();
            var vm_combine_list = new List<ModelCombineViewModel>();
            var vm_diff_list = new List<ModelDiffViewModel>();
            foreach (var station_record in station_record_list)
            {
                var model_record_dict = station_record.ModelRecordDict;
                var pipe_flow_err = true;
                var pipe_pressure_err = true;
                foreach (var id in pipe_flow_id_list)
                {
                    if (model_record_dict[id] < 1)
                    {
                        pipe_flow_err = false;
                        break;
                    }
                }
                foreach (var id in pipe_pressure_id_list)
                {
                    var value = model_record_dict[id];
                    if (value < 1 || value > 40)
                    {
                        pipe_pressure_err = false;
                        break;
                    }
                }
                if (!pipe_flow_err || !pipe_pressure_err)
                {
                    continue;
                }
 
 
                var time = station_record.Time.ToString("G");
                var pump_record_list = station_record.PumpSignalRecords;
                var total_flow = station_record.TotalFlow;
                var total_pressure = station_record.TotalPressure;
                var pump_total_flow = pump_record_list.Sum(x => x.FlowRate);
                var diff_flow = station_record.DiffFlow;
                //if (total_pressure < 20|| total_pressure>60)
                //{
                //    continue;
                //}
                if (total_pressure < 0)
                {
                    continue;
                }
                if (total_flow <= 0 && pump_total_flow <= 0)
                {
                    continue;
                }
                if (pump_total_flow > 0 && Math.Abs(diff_flow) > 2000)
                {
                    continue;
                }
                //if (station_record.Time.Month==4&& station_record.Time.Day==17)
                //{
                //    continue;
                //}
 
 
                //if (station_record.Time > new DateTime(2024,4,29)&& station_record.Time < new DateTime(2024, 5, 15))
                //{
                //    continue;
                //}
 
                var pump_run_flags = pump_record_list.Select(x => x.Flag).OrderBy(x => x).ToList();
                if (pump_record_list.Exists(x => x.Flag != 15 && x.Flag != 16 && x.Rpm < 1))
                {
                    continue;
                }
 
                //if (pump_record_list.Exists(x => x.FlowRate < 1))
                //{
                //    continue;
                //}
 
                if (pump_record_list.Exists(x => x.OutletPressure > 50))
                {
                    continue;
                }
 
                if (ana_factor_list != null && ana_factor_list.Any() && use_ana_factor)
                {
                    foreach (var pump_record in pump_record_list)
                    {
                        var flag = pump_record.Flag;
                        var pump = flag_pump_dict[flag];
                        var mapping = pump_model_mapping_dict[flag];
                        var rpm_ratio = pump_record.Rpm / pump.Nr;
                        if (!pump.IsBp)
                            rpm_ratio = 1;
                        if (rpm_ratio <= 0.1)
                            continue;
 
                        var hz0 = Math.Round(rpm_ratio * 50, 0);
                        if (hz0 > 50)
                            hz0 = 50;
                        var ana_factor = ana_factor_list.Find(x => x.Hz == hz0 && x.Flag == flag);
                        if (ana_factor == null)
                        {
                            throw new Exception($"ana_factor:is null");
                        }
                        var qh = flag_qh_curve_dict[flag];
                        var head_dev = (float)ana_factor.HeadDeviation;
                        var fit_point_list = new List<Model.CurvePoint>(curve_point_count);
                        if (head_dev == 0)
                        {
                            fit_point_list = qh.GetFitPoints(curve_point_count);
                        }
                        else
                        {
                            var pt_list_ct = qh.DefinePoints.Select(x => new Model.CurvePoint(x.X, x.Y + head_dev)).ToList();
                            var qh_ct = Model.FitCurveHelper.BuildCurveExpress(pt_list_ct, Model.eCurveFitType.CubicCurve);
                            fit_point_list = qh_ct.GetFitPoints(curve_point_count);
                        }
 
                        var x_list = fit_point_list.Select(x => (float)x.X).ToList();
                        var y_list = fit_point_list.Select(x => (float)x.Y).ToList();
 
 
                        err = EpanetMethods.ENsetcurve(mapping.CurveIndex, x_list.ToArray(), y_list.ToArray(), curve_point_count);
                        if ((int)err > 6)
                        {
                            throw new Exception($"ENsetcurve:{err}");
                        }
                    }
                }
 
                foreach (var pattern in pattern_id_dict)
                {
                    var pattern_id = pattern.Key;
                    var pattern_index = pattern.Value;
                    var pattern_value = 0f;
                    if (model_record_dict.ContainsKey(pattern_id))
                    {
                        pattern_value = (float)model_record_dict[pattern_id];
                    }
                    err = EpanetMethods.ENsetpattern(pattern_index, new float[] { pattern_value }, 1);
                    if ((int)err > 6)
                    {
                        throw new Exception($"ENsetpattern:{err}");
                    }
                }
 
                err = EpanetMethods.ENinitH(0);
                if ((int)err > 6)
                {
                    throw new Exception($"ENinitH:{err}");
                }
 
                err = EpanetMethods.ENrunH(out _);
                if ((int)err > 6)
                {
                    throw new Exception($"ENrunH:{err}");
                }
                var flags = pump_record_list.Select(x => x.Flag).OrderBy(x => x).ToList();
 
                var vm_combine = new ModelCombineViewModel();
                vm_combine.Time = time;
                vm_combine.RunFlags = IStation.Untity.IntListHelper.ToString(flags);
                vm_combine.ModelDeviation = new List<Tuple<int, double, double>>();
                vm_combine_list.Add(vm_combine);
 
                foreach (var pump_record in pump_record_list)
                {
                    var flag = pump_record.Flag;
                    var pump = flag_pump_dict[flag];
                    var qh = flag_qh_curve_dict[flag];
                    var mapping = pump_model_mapping_dict[flag];
                    var rpm = pump_record.Rpm;
                    if (!pump.IsBp)
                        rpm = pump.Nr;
                    if (rpm == 0)
                        break;
 
                    var hz = Math.Round(rpm / pump.Nr * 50, 2);
                    if (hz > 50)
                        hz = 50;
                    var hz0 = Math.Round(hz, 0);
                    var wl = pump_record.WaterLevel;
                    var inlet_pressure = Model.CurveCalcuHelper.Mpa2M(pump_record.InletPressure);
                    var outlet_pressure = Model.CurveCalcuHelper.Mpa2M(pump_record.OutletPressure);
                    var pressure_diff = outlet_pressure - inlet_pressure;
                    var flow = pump_record.FlowRate;
                    var curve_head = pump_record.Head;
 
 
                    err = EpanetMethods.ENgetlinkvalue(mapping.PumpIndex, LinkValue.Flow, out float model_flow);
                    if ((int)err > 6)
                    {
                        throw new Exception($"ENgetnodevalue:{err}");
                    }
 
                    err = EpanetMethods.ENgetnodevalue(mapping.PressureIndex, NodeValue.Pressure, out float model_outlet_pressure);
                    if ((int)err > 6)
                    {
                        throw new Exception($"ENgetnodevalue:{err}");
                    }
 
                    model_flow = Math.Abs(model_flow);
                    model_outlet_pressure = Math.Abs(model_outlet_pressure);
                    var model_pressure_diff = model_outlet_pressure - inlet_pressure;
 
                    var flow_diff = flow - model_flow;
                    var pressure_diff_dev = pressure_diff - model_pressure_diff;
 
                    var vm = new PumpViewModel();
                    vm.Time = time;
                    vm.Rpm = rpm;
                    vm.Flag = flag;
                    vm.Hz = hz;
                    vm.Hz0 = hz0;
                    vm.WaterLevel = wl;
                    vm.InletPressure = Math.Round(inlet_pressure, 2);
                    vm.OutletPressure = Math.Round(outlet_pressure, 2);
                    vm.PressureDiff = Math.Round(pressure_diff, 2);
 
                    vm.Flow = Math.Round(flow, 1);
                    vm.ModelFlow = Math.Round(model_flow, 1);
                    vm.ModelOutletPressure = Math.Round(model_outlet_pressure, 2);
                    vm.CurvePressureDiff = Math.Round(model_pressure_diff, 2);
                    vm.PressureDiffDev = Math.Round(pressure_diff_dev, 3);
                    vm.FlowDiff = Math.Round(flow_diff, 1);
                    vm_list.Add(vm);
 
 
                    var calc_flow = flow > 0 ? flow : model_flow;
                    var dif_flow = flow - model_flow;
 
                    vm_combine.ScadaTotalFlow += flow < 1 ? model_flow : flow;
                    vm_combine.ModelTotalFlow += model_flow;
                    vm_combine.ModelDeviation.Add(new Tuple<int, double, double>(flag, calc_flow, pressure_diff_dev));
                }
 
 
                foreach (var mapping in model_mapping_list)
                {
                    if (!model_record_dict.ContainsKey(mapping.ScadaPressureId))
                    {
                        continue;
                    }
                    if (!model_record_dict.ContainsKey(mapping.ScadaFlowId))
                    {
                        continue;
                    }
                    var flow = model_record_dict[mapping.ScadaFlowId];
                    var outlet_pressure = model_record_dict[mapping.ScadaPressureId];
 
                    err = EpanetMethods.ENgetlinkvalue(mapping.FlowIndex, LinkValue.Flow, out float model_flow);
                    if ((int)err > 6)
                    {
                        throw new Exception($"ENgetnodevalue:{err}");
                    }
 
                    err = EpanetMethods.ENgetnodevalue(mapping.PressureIndex, NodeValue.Pressure, out float model_outlet_pressure);
                    if ((int)err > 6)
                    {
                        throw new Exception($"ENgetnodevalue:{err}");
                    }
 
                    var flow_diff = flow - model_flow;
                    var pressure_diff = outlet_pressure - model_outlet_pressure;
 
                    var vm = new ModelDiffViewModel();
                    vm.Date = station_record.Time;
                    vm.Time = time;
                    vm.Name = mapping.Name;
                    vm.ScadaFlow = Math.Round(flow, 1);
                    vm.ScadaPressure = Math.Round(outlet_pressure, 3);
                    vm.MonitorFlow = Math.Round(model_flow, 1);
                    vm.MonitorPressure = Math.Round(model_outlet_pressure, 3);
                    vm.FlowDiff = Math.Round(flow_diff, 1);
                    vm.PressureDiff = Math.Round(pressure_diff, 3);
                    vm_diff_list.Add(vm);
                }
            }
 
            err = EpanetMethods.ENcloseH();
            if ((int)err > 6)
            {
                throw new Exception($"ENcloseH:{err}");
            }
            err = EpanetMethods.ENclose();
            if ((int)err > 6)
            {
                throw new Exception($"ENclose:{err}");
            }
 
            if (!vm_combine_list.Any())
            {
                Clear();
                return;
            }
            var run_flags_flow_pressure_diff_dict = vm_combine_list
             .Select(x => new Tuple<string, double, List<Tuple<int, double, double>>>(x.RunFlags, x.ScadaTotalFlow, x.ModelDeviation))
             .ToList();
 
 
            var ana_dev_list = AnalysisHelper.GetAnalysisDeviationDtoList(flag_pump_dict, run_flags_flow_pressure_diff_dict, _min_flow, _max_flow, _space_flow);
            ////test
            //if (station_index == 2)
            //{
            //    foreach (var item in ana_dev_list)
            //    {
            //        var count = item.PressureDiff.Count;
            //        for (int i = 0; i < count; i++)
            //        {
            //            var src_i = item.PressureDiff.ElementAt(i);
            //            var src_v = item.PressureDiff[src_i.Key];
            //            item.PressureDiff[src_i.Key] = src_v < 0 ? Math.Abs(src_v) : -src_v;
            //        }
            //    }
            //}
            var vm_combine_diff_list = ana_dev_list?.Select(x => new ModelCombineDiffViewModel()
            {
                RunFlags = IStation.Untity.IntListHelper.ToString(x.RunFlags),
                MinFlow = x.MinFlow,
                MaxFlow = x.MaxFlow,
                ModelDeviation = JsonHelper.Object2Json(x.PressureDiff),
                Count = x.Count
            }).ToList();
 
 
            _model_combine_list = vm_combine_list;
            //SetBindingData(vm_diff_list);
 
            _model_diff_vm_list = vm_diff_list;
            modelTimeViewModelBindingSource.DataSource = _model_diff_vm_list;
            modelTimeViewModelBindingSource.ResetBindings(false);
            gridView3.BestFitColumns();
 
            _pump_vm_list = vm_list;
            pumpViewModelBindingSource.DataSource = vm_list;
            pumpViewModelBindingSource.ResetBindings(false);
            gridView1.BestFitColumns();
 
            _model_combine_diff_vm_list = vm_combine_diff_list;
            modelCombineDiffViewModelBindingSource.DataSource = vm_combine_diff_list;
            modelCombineDiffViewModelBindingSource.ResetBindings(false);
            gridView2.BestFitColumns();
 
 
        }
 
        private void SetBindingData(List<ModelDiffViewModel> vm_list)
        {
            timeValueSwiftPlotChartView1.ClearSeries();
            if (vm_list == null || !vm_list.Any())
            {
                return;
            }
 
            var flow_dict = new Dictionary<string, List<TimeValue>>();
            var pressure_dict_dict = new Dictionary<string, List<TimeValue>>();
 
            var group = vm_list.GroupBy(x => x.Name);
            for (int i = 0; i < group.Count(); i++)
            {
                var color = GetRandomColor(i);
                var item = group.ElementAt(i);
                var name = item.Key;
                //var scada_flow_list = item.Select(x => new TimeValue(x.Date, x.ScadaFlow)).ToList();
                //var model_flow_list = item.Select(x => new TimeValue(x.Date, x.MonitorFlow)).ToList();
                //var flow_diff_list = item.Select(x => new TimeValue(x.Date, x.FlowDiff)).ToList();
 
                //var scada_pressure_list = item.Select(x => new TimeValue(x.Date, x.ScadaPressure)).ToList();
                //var model_pressure_list = item.Select(x => new TimeValue(x.Date, x.MonitorPressure)).ToList();
                var pressure_diff_list = item.Where(x => !(Math.Abs(x.PressureDiff) > 2)).Select(x => new TimeValue(x.Date, x.PressureDiff)).ToList();
 
                //this.timeValueSwiftPlotChartView1.AddSwiftPlotSeries(name, color, name + "(监测流量)", "流量", scada_flow_list);
                //this.timeValueSwiftPlotChartView1.AddSwiftPlotSeries(name, color, name + "(模型流量)", "流量", model_flow_list);
                //this.timeValueSwiftPlotChartView1.AddSwiftPlotSeries(name, color, name + "(偏差流量)", "流量", flow_diff_list);
 
 
                // this.timeValueSwiftPlotChartView1.AddSwiftPlotSeries(name, color, name + "(监测压力)", "压力", scada_pressure_list);
                //this.timeValueSwiftPlotChartView1.AddSwiftPlotSeries(name, color, name + "(模型压力)", "压力", model_pressure_list);
                timeValueSwiftPlotChartView1.AddSwiftPlotSeries(name, color, name + "(偏差压力)", "压力", pressure_diff_list);
            }
        }
 
        #region Color
 
        private List<Color> ColorArray = new List<Color>()
        { Color.Red, Color.Blue, Color.Green, Color.DodgerBlue,
            Color.Fuchsia, Color.MidnightBlue, Color.Maroon,
            Color.Aquamarine, Color.Bisque, Color.BurlyWood
        };
 
        /// <summary>
        /// 获取随机颜色
        /// </summary>
        /// <returns></returns>
        private Color GetRandomColor(int count)
        {
            if (count < ColorArray.Count)
            {
                return ColorArray[count];
            }
 
            return ColorHelper.GetRandomColor();
        }
        #endregion
 
        bool CheckFitPointList(List<CurvePoint> fit_point_list, int nPoints)
        {
            var arr = fit_point_list.ToArray();
            var max_y = fit_point_list[0].Y;
            for (int j = 1; j < nPoints; j++)
            {
                if (arr[j].Y > max_y)
                {
                    return false;
                }
                else
                {
                    max_y = fit_point_list.Take(j).Max(x => x.Y);
                }
            }
            return true;
        }
 
 
        private Dictionary<int, Model.CurveExpress> GetFlagCurveDict()
        {
            var dict = new Dictionary<int, Model.CurveExpress>();
            var bll_curve = new BLL.PumpCurve();
            var station_list = new BLL.Station().GetAll();
            foreach (var station in station_list)
            {
                var eq_list = new BLL.Equipment().GetPumpListByBelongTypeAndBelongID(IStation.ObjectType.Station, station.ID);
                if (eq_list == null || !eq_list.Any())
                {
                    return default;
                }
 
                foreach (var eq in eq_list)
                {
                    Model.CurveExpress qh = null;
                    var curve_info = bll_curve.GetDefaultWorkingByPumpID(eq.ID)?.CurveInfo;
                    if (curve_info != null)
                    {
                        qh = curve_info.CurveQH;
                    }
                    dict.Add(eq.SortCode, qh);
                }
            }
 
            return dict;
        }
 
 
        private void cmbFlag_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearChart();
            if (_pump_vm_list == null || !_pump_vm_list.Any())
            {
                return;
            }
            if (!int.TryParse(cmbFlag.Text, out int flag))
            {
                return;
            }
            var vm_list = _pump_vm_list.Where(x => x.Flag == flag).ToList();
            if (vm_list == null || !vm_list.Any())
            {
                return;
            }
            chartControl1.BeginInit();
            foreach (var vm in vm_list)
            {
                var time = vm.Time;
                var diff = vm.ModelOutletPressure - vm.OutletPressure;
                if (Math.Abs(diff) > 4)
                {
                    continue;
                }
                _series_default_head.Points.Add(new SeriesPoint(time, vm.OutletPressure));
                _series_curve_head.Points.Add(new SeriesPoint(time, vm.ModelOutletPressure));
                _series_correct_curve_head.Points.Add(new SeriesPoint(time, Math.Round(diff, 2)));
            }
 
            chartControl1.EndInit();
        }
 
 
        //加载
        private void barCekLoad_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            WaitFrmHelper.ShowWaitForm();
            SetBindingData(_monitorDataSources, _station);
            WaitFrmHelper.HideWaitForm();
        }
 
 
        // 刷新数据
        private void barBtnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            InitialDataSource();
        }
 
        private void barBtnExportAnalysisDev_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (_monitorDataSources == null || _station == null)
            {
                return;
            }
            if (_pump_list == null || !_pump_list.Any())
            {
                return;
            }
            if (_model_combine_list == null || !_model_combine_list.Any())
            {
                return;
            }
 
            WaitFrmHelper.ShowWaitForm("正在导出");
            var run_flags_flow_pressure_diff_dict = _model_combine_list
                .Select(x => new Tuple<string, double, List<Tuple<int, double, double>>>(x.RunFlags, x.ScadaTotalFlow, x.ModelDeviation))
                .ToList();
            var bol = AnalysisHelper.SaveAnalysisDeviationDtoList(_station.SortCode, _pump_list, run_flags_flow_pressure_diff_dict, _min_flow, _max_flow, _space_flow);
            if (!bol)
            {
                XtraMessageBox.Show("导出失败!");
                return;
            }
            WaitFrmHelper.HideWaitForm();
            AlertTool.ShowInfo(System.Windows.Forms.Application.OpenForms[0], "提示", "导出完成!");
 
        }
    }
 
 
}