HeatBuf.cs 43.2 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
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 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 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 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 1243 1244 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 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 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
using System;
using System.Collections.Generic;
using System.Linq;
using FLY.FeedbackRenZiJia.Common;
using FLY.Thick.RemoteHistory;
using Misc;
using System.IO;
using System.Text;
using System.ComponentModel;
using FLY.FeedbackRenZiJia.IService;
using FObjBase;

namespace FLY.FeedbackRenZiJia.Server
{
    /// <summary>
    /// 存放一堆厚度与加热数据。
    /// 1.用于判断加热是否稳定了;
    /// 2.加热偏移;
    /// 3.加热/厚度
    /// </summary>
    public class HeatBuf: IHeatBuf, Misc.ISaveToXml
    {

        #region 属性,对外接口
        #region 参数


        private List<int> heatEffectCurve = new List<int>();
        /// <summary>
        /// 加热生效曲线,允许为空,则不生效
        /// </summary>
        public List<int> HeatEffectCurve
        {
            get{
                return heatEffectCurve;
            }
            set {
                heatEffectCurve = value;
                NotifyPropertyChanged("HeatEffectCurve");
            }
        }

        private int stablerange = 2;
        /// <summary>
        /// 厚度稳定范围 %, 偏差在范围内,都是稳定的 
        /// </summary>
        public int StableRange
        {
            get { return stablerange; }
            set {
                if (stablerange != value)
                {
                    stablerange = value;
                    NotifyPropertyChanged("StableRange");
                }
            }
        }

        private int stablerange0 = 2;
        /// <summary>
        /// 厚度稳定范围 %, 加热量变化为0时,偏差在范围内,都是稳定的 
        /// </summary>
        public int StableRange0
        {
            get { return stablerange0; }
            set
            {
                if (stablerange0 != value)
                {
                    stablerange0 = value;
                    NotifyPropertyChanged("StableRange0");
                }
            }
        }

        private double thresholdR = 0.7;
        /// <summary>
        /// 对位模式, 加热与厚度相关性阀值, 相关性 >=0.7
        /// </summary>
        public double ThresholdR
        {
            get { return thresholdR; }
            set {
                if (thresholdR != value)
                {
                    thresholdR = value;
                    NotifyPropertyChanged("ThresholdR");
                }
            }
        }

        private int thresholdMaxMin = 8;
        /// <summary>
        /// 对位模式 厚度%差 的极差 >= +4%-4%=8%, 单位%
        /// </summary>
        public int ThresholdMaxMin
        {
            get { return thresholdMaxMin; }
            set
            {
                if (thresholdMaxMin != value)
                {
                    thresholdMaxMin = value;
                    NotifyPropertyChanged("ThresholdMaxMin");
                }
            }
        }

        private int thresholdSigmaMax = 20;
        /// <summary>
        /// %
        /// 最大sigma, 只有当前的sigma  在 最大sigma 与 最小 sigma 内,才能控制
        /// </summary>
        public int ThresholdSigmaMax
        {
            get { return thresholdSigmaMax; }
            set
            {
                if (thresholdSigmaMax != value)
                {
                    thresholdSigmaMax = value;
                    NotifyPropertyChanged("ThresholdSigmaMax");
                }
            }
        }


        private bool isUsedKp = false;
        /// <summary>
        /// 使用这里独立的Kp, 与 HeatCell 不一样
        /// </summary>
        public bool IsUsedLocalKp
        {
            get { return isUsedKp; }
            set {
                if (isUsedKp != value)
                {
                    isUsedKp = value;
                    NotifyPropertyChanged("IsUsedLocalKp");
                }
            }
        }

        private double localkp = 3;
        /// <summary>
        /// 本地Kp, 用于判断稳定性
        /// </summary>
        public double LocalKp
        {
            get { return localkp; }
            set {
                if (localkp != value)
                {
                    localkp = value;
                    NotifyPropertyChanged("LocalKp");
                }
            }
        }



        #endregion

        #region 状态

        private TimeSpan delay = TimeSpan.FromSeconds(100);
        /// <summary>
        /// 总延时 =Delay+mRenZiJiaService.FilmLength/mRenZiJiaService.Velocity
        /// </summary>
        public TimeSpan Delay
        {
            get { return delay; }
            set
            {
                if (delay != value)
                {
                    delay = value;
                    NotifyPropertyChanged("Delay");
                }
            }
        }


        #region 对位
        private bool isIntoAutoONo = false;
        /// <summary>
        /// 进入了对位模式
        /// </summary>
        public bool IsIntoAutoONo
        {
            get { return isIntoAutoONo; }
            set
            {
                if (isIntoAutoONo != value)
                {
                    isIntoAutoONo = value;
                    NotifyPropertyChanged("IsIntoAutoONo");
                }
            }
        }

        private EAutoONoResult autoONoResult = EAutoONoResult.Idle;
        /// <summary>
        /// 对位模式结果
        /// </summary>
        public EAutoONoResult AutoONoResult
        {
            get { return autoONoResult; }
            set {
                if (autoONoResult != value)
                {
                    autoONoResult = value;
                    NotifyPropertyChanged("AutoONoResult");
                }
            }
        }

        private int bestOrgBoltNo = -1;
        /// <summary>
        /// 计算的最佳复位区号
        /// </summary>
        public int BestOrgBoltNo
        {
            get { return bestOrgBoltNo; }
            set {
                if (bestOrgBoltNo != value)
                {
                    bestOrgBoltNo = value;
                    NotifyPropertyChanged("BestOrgBoltNo");
                }
            }
        }

        private double bestkp = -1;
        /// <summary>
        /// 计算的最佳复位区号 对应的 加热/厚度 
        /// </summary>
        public double BestKp
        {
            get { return bestkp; }
            set
            {
                if (bestkp != value)
                {
                    bestkp = value;
                    NotifyPropertyChanged("BestKp");
                }
            }
        }

        private double maxR = -1;
        /// <summary>
        /// 计算的最佳复位区号 对应的 加热与厚度相关性
        /// </summary>
        public double MaxR
        {
            get { return maxR; }
            set
            {
                if (maxR != value)
                {
                    maxR = value;
                    NotifyPropertyChanged("MaxR");
                }
            }
        }

        private double maxmin = -1;
        /// <summary>
        /// 计算的最佳复位区号 对应的 厚度%变化极差 单位%
        /// </summary>
        public double MaxMin
        {
            get { return maxmin; }
            set {
                if (maxmin != value)
                {
                    maxmin = value;
                    NotifyPropertyChanged("MaxMin");
                }
            }
        }
        #endregion

        #region 稳定性
        private STABILITY stability = STABILITY.IDLE;
        /// <summary>
        /// 当前检测出来的厚度数据 稳定状态
        /// </summary>
        public STABILITY Stability
        {
            get { return stability; }
            protected set {
                if (stability != value)
                {
                    stability = value;
                    NotifyPropertyChanged("Stability");
                }
            }
        }

        private double currR = -1; 
        /// <summary>
        /// 当前检测出来的厚度数据 的稳定性 
        /// </summary>
        public double CurrR
        {
            get { return currR; }
            set {
                if (currR != value)
                {
                    currR = value;
                    NotifyPropertyChanged("CurrR");
                }
            }
        }

        private double curr2Sigma = -1;
        /// <summary>
        /// 当前检测出来的厚度数据 2Sigma
        /// </summary>
        public double Curr2Sigma
        {
            get
            {
                return curr2Sigma;
            }
            set {
                if (curr2Sigma != value)
                {
                    curr2Sigma = value;
                    NotifyPropertyChanged("Curr2Sigma");
                }
            }
        }

        private double currBreakUp = 50;
        /// <summary>
        /// 当前打散程度。 
        /// 连续N点都在平均值同一侧为一个块;
        /// 这些块的长度平均值/总长度, 为打散度;
        /// 打散度越小越好, 最小为 1/NBolts
        /// </summary>
        public double CurrBreakUp
        {
            get
            {
                return currBreakUp;
            }
            protected set
            {
                if (currBreakUp != value)
                {
                    currBreakUp = value;
                    NotifyPropertyChanged("CurrBreakUp");
                }
            }
        }

        DateTime currtime = DateTime.MinValue;
        /// <summary>
        /// 当前检测出来的厚度数据,时间
        /// </summary>
        public DateTime CurrTime
        {
            get
            {
                return currtime;
            }
            set
            {
                if (currtime != value)
                {
                    currtime = value;
                    NotifyPropertyChanged("CurrTime");
                }
            }
        }

        private Misc.DIRECTION currDirection = Misc.DIRECTION.FORWARD;
        /// <summary>
        /// 当前检测出来的厚度数据,方向
        /// </summary>
        public Misc.DIRECTION CurrDirection
        {
            get { return currDirection; }
            protected set
            {
                if (currDirection != value)
                {
                    currDirection = value;
                    NotifyPropertyChanged("CurrDirection ");
                }
            }
        }


        #endregion

        #region 列表
        private int lastbm = 0;
        /// <summary>
        /// 列表最后1个BM
        /// </summary>
        public int LastBM
        {
            get { return lastbm; }
            protected set
            {
                if (lastbm != value)
                {
                    lastbm = value;
                    NotifyPropertyChanged("LastBM");
                }
            }
        }

        private int firstbm = 0;
        /// <summary>
        /// 列表第1个BM
        /// </summary>
        public int FirstBM
        {
            get { return firstbm; }
            protected set
            {
                if (firstbm != value)
                {
                    firstbm = value;
                    NotifyPropertyChanged("FirstBM");
                }
            }
        }
        #endregion

        #region 每个分区状态
        private bool[] boltIsStable;
        public bool[] BoltIsStable
        {
            get { return boltIsStable; }
            set {
                boltIsStable = value;
                NotifyPropertyChanged("BoltIsStable");
            }
        }
        #endregion

        #endregion

        #endregion


        private double kp = 3;
        /// <summary>
        /// HeatCell 的 Kp
        /// </summary>
        public double Kp
        {
            get { return kp; }
            set
            {
                if (kp != value)
                {
                    kp = value;
                    NotifyPropertyChanged("Kp");
                }
            }
        }
        
        /// <summary>
        /// 厚度数量
        /// </summary>
        int BoltCnt = 96;

        /// <summary>
        /// 加热数量
        /// </summary>
        int ChannelCnt = 96;
        
        /// <summary>
        /// 缓存区大小
        /// </summary>
        int BufSize = 60;
        
        /// <summary>
        /// 最后一幅数据的复位区号
        /// </summary>
        int orgBoltNo = 1;
        /// <summary>
        /// 最后一幅数据的旋转角度
        /// </summary>
        double rAngle = 355;

        public History<FlyData_FeedbackHeat> mHistory;
        public RList<FlyData_FeedbackHeat> mData;
        /// <summary>
        /// 当复位区号改变,它应该被清空
        /// </summary>
        public BoltHeat[] mBoltData;
        static HeatBuf()
        {

        }
        public HeatBuf()
        {
            mHistory = new History<Common.FlyData_FeedbackHeat>("history");
            mHistory.SaveRows = 100;

            mData = new RList<FlyData_FeedbackHeat>(BufSize);

            Load();
            checkParamErr();
            PropertyChanged += HeatBuf_PropertyChanged;
        }
        void checkParamErr()
        {
            if (StableRange < 1 || StableRange > 10)
            {
                StableRange = 2;
            }

            if (StableRange0 < 1 || StableRange0 > 10)
            {
                StableRange0 = 2;
            }

            if (ThresholdR < 0.1 || ThresholdR > 0.9)
            {
                ThresholdR = 0.7;
            }

            if (ThresholdMaxMin < 2 || ThresholdMaxMin > 20)
            {
                ThresholdMaxMin = 8;
            }

            if (LocalKp < 1 || LocalKp > 20)
            {
                LocalKp = 3;
            }
        }
        private void HeatBuf_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsIntoAutoONo")
            {
                if (IsIntoAutoONo)
                {
                    AutoONoResult = EAutoONoResult.Idle;
                }
                else
                {
                    if (AutoONoResult == EAutoONoResult.Idle)
                    {
                        //被强制关闭
                        AutoONoResult = EAutoONoResult.Err_Break;
                    }
                }
            }
        }

        public void Init(int boltCnt, int channelCnt) 
        {
            BoltCnt = boltCnt;
            ChannelCnt = channelCnt;
            mBoltData = new BoltHeat[BoltCnt];
            for (int i = 0; i < BoltCnt; i++)
            {
                mBoltData[i] = new BoltHeat();
            }
            mData.Clear();
            mHistory.Flush();
            //TODO 测试
            //LoadData();
        }
        


        public bool IsStable()
        {
            if ((int)Stability > 0)
                return true;
            else
                return false;
        }
        public bool IsUnstable()
        {
            if ((int)Stability < 0)
                return true;
            else
                return false;
        }

        public int[] GetThicks() 
        {
            if (mData.Count() == 0)
                return null;
            return mData.Last().Thicks;
        }


        /// <summary>
        /// 1.添加数据到缓冲;
        /// 2.判断是否稳定
        /// 3.根据稳定变化,加热变化,计算偏移
        /// </summary>
        /// <param name="time">测厚的开始时间</param>
        /// <param name="endtime">测厚的结束时间</param>
        /// <param name="direction">方向</param>
        /// <param name="period">旋转时间</param>
        /// <param name="rotateCnt">旋转次数</param>
        /// <param name="orgBoltNo">复位区号</param>
        /// <param name="rAngle">旋转角度</param>
        /// <param name="filmLength">膜距离</param>
        /// <param name="thicks">厚度数据</param>
        /// <param name="htime">加热的时间</param>
        /// <param name="heats">加热量</param>
        /// <returns></returns>
        public bool Add(
            DateTime time, DateTime endtime, Misc.DIRECTION direction, TimeSpan period, int rotateCnt,
            int orgBoltNo, double rAngle, double filmLength,
            int[] thicks,
            DateTime htime, int[] heats)
        {
            //thicks 的数据量一定要是 BoltCnt
            //heats 的数据量一定要是 ChannelCnt
            //不是返回 false
            
            if (thicks.Count() != BoltCnt)//异常
                return false;

            if (heats.Count() != ChannelCnt)//异常
                return false;

            FlyData_FeedbackHeat d = new FlyData_FeedbackHeat()
            {
                Time = time,
                EndTime = endtime,
                Direction = direction,
                RotatePeriod = period,
                RotateCnt = rotateCnt,

                OrgBoltNo = orgBoltNo,
                RAngle = rAngle,
                FilmLength = filmLength,

                Thicks = thicks,

                HTime = htime,
                Heats = heats
            };
            UpdateStable1(d);//判断是否异常数据

           
            //检查,它可能只是因为 复位区号,或旋转角度,膜距离改变了,再重发一次而已
            if (mData.Count() > 0)
            {
                for (int i = 0; i < mData.Count(); i++)
                {
                    int idx = mData.Count() - 1 - i;
                    FlyData_FeedbackHeat f = mData[idx];
                    if (time < f.Time)
                    {
                        //要继续找向前找
                        if (idx == 0)
                        {
                            //已经到头了, 在idx前面插入
                            mData.Insert(0, d);
                            return false;
                        }
                    }
                    else if (f.Time == time)
                    {
                        //只是以前的数据而已,替换掉
                        mData[idx] = d;
                        return false;
                    }
                    else
                    {
                        //找过了,在idx后面插入
                        if (idx == mData.Count() - 1)
                        {
                            //在最后插入数据
                            //mData.RAdd(d);
                            //idx_new = idx;
                        }
                        else
                        {
                            mData.Insert(idx, d);
                            return false;
                        }
                        break;
                    }
                }
            }

            if ((d.RAngle != this.rAngle) || (d.OrgBoltNo != this.orgBoltNo))
            {
                ClearBoltHeat();
                this.rAngle = d.RAngle;
                this.orgBoltNo = d.OrgBoltNo;
            }

            if (d.Stability != STABILITY.IDLE)
            {
                //数据异常
                CurrR = -1;
            }
            else
            {
                //自动对位
                if (IsIntoAutoONo)
                {
                    UpdateAutoONo(d);
                    IsIntoAutoONo = false;
                }
                else
                {
                    //更新每个分区的稳定状态
                    UpdateStable2(d);
                }
            }

            Stability = d.Stability;
            CurrDirection = d.Direction;
            CurrTime = d.Time;

            mHistory.Add(d);
            mData.RAdd(d);

            LastBM = mData.GetLastNo();
            FirstBM = LastBM + 1 - mData.Count();
            //TODO 测试
            //SaveData();

            return true;
        }
        #region 测试用
        string data_path = "heatbuf.csv";
        void SaveData()
        {

            //当文件不存在,重新写入全部
            //当文件存在,只追加
            if (File.Exists(data_path))
            {
                using (StreamWriter sw = new StreamWriter(data_path, true, Encoding.GetEncoding("GB2312")))
                {
                    sw.WriteLine(mData.Last().ToString());
                    sw.Flush();
                    sw.Close();
                }
            }
            else
            {
                using (StreamWriter sw = new StreamWriter(data_path,false, Encoding.GetEncoding("GB2312")))
                {
                    sw.WriteLine(mData.First().GetHeader());
                    for (int i=0;i<mData.Count();i++)
                    {
                        sw.WriteLine(mData[i].ToString());
                    }
                    sw.Flush();
                    sw.Close();
                }
            }
        }
        void LoadData()
        {
            mData.Clear();
            try
            {
                using (StreamReader sr = new StreamReader(data_path, Encoding.GetEncoding("GB2312")))
                {
                    //第1行是标题
                    string header = sr.ReadLine();

                    while (!sr.EndOfStream)
                    {
                        string s = sr.ReadLine();
                        FlyData_FeedbackHeat f = new FlyData_FeedbackHeat();
                        if (!f.TryParse(header, s))
                        {
                            break;//异常失败!!!
                        }
                        mData.RAdd(f);
                    }
                }
            }
            catch(Exception e)
            {

            }
            if (mData.Count() > 0)
            {
                LastBM = mData.GetLastNo();
                FirstBM = LastBM + 1 - mData.Count();
            }
            else
            {
                LastBM = -1;
                FirstBM = -1;
            }
        }
        #endregion


        /// <summary>
        /// 获取上一次没有交集的数据序号
        /// </summary>
        /// <param name="index">在列表中的待比较数据序号</param>
        /// <returns></returns>
        int GetJustBeforeIdx(FlyData_FeedbackHeat d_now, int index)
        {
            for (int i = 0; i <= index; i++)
            {
                int idx = index - i;
                FlyData_FeedbackHeat d = mData[idx];
                if (d.EndTime <= d_now.Time)
                    return idx;
            }
            return -1;
        }
        bool CanCompared(STABILITY stability)
        {
            switch (stability)
            {
                case STABILITY.ERROR_NO_ARRIVE:
                case STABILITY.ERROR_POSITION_NOTSURE:
                case STABILITY.ERROR_SIGMA_OVERSIZE:
                    return false;
                default:
                    return true;
                //case STABILITY.IDLE:
                //case STABILITY.ERROR_ROTATE_CHANGED:
                //case STABILITY.ERROR_THICK_CHANGED:
                //case STABILITY.ERROR_CORREL:
                //case STABILITY.OK_SIGMA_SMALL_ENOUGH:
                //case STABILITY.OK_CORREL:
                //case STABILITY.OK_HEAT_AND_THICK_CORREL:
                //    return true;

            }
        }

        
        /// <summary>
        /// 更新稳定状态, 一个就能判断的状态
        /// </summary>
        /// <param name="d"></param>
        void UpdateStable1(FlyData_FeedbackHeat d)
        {
            if (d.RotateCnt <= 0)//旋转次数太少,位置不能确定
            {
                d.Stability = STABILITY.ERROR_POSITION_NOTSURE;
                return;
            }


            {
                DateTime dt_takeeffect = d.HTime + Delay;//起效时间

                if (d.Time >= dt_takeeffect)//最早的时间都比起效时间晚,不用删除
                {

                }
                else
                {
                    DateTime dt = d.Time + TimeSpan.FromTicks((long)((d.EndTime - d.Time).Ticks * 0.3));
                    if (dt < dt_takeeffect)
                    {
                        //有30% 数据都是以前的,无效, 加热还没起效
                        d.Stability = STABILITY.ERROR_NO_ARRIVE;
                        return;
                    }
                }
            }

            int avg = Misc.MyMath.Avg(d.Thicks);
            CurrBreakUp = Common.MyMath.BreakUp(d.Thicks) * 100.0;
            int sigma = Misc.MyMath.Sigma(d.Thicks);
            double sigma2_percents = 100.0 * 2 * sigma / avg;
            Curr2Sigma = sigma2_percents;
            
            if (sigma2_percents >= ThresholdSigmaMax)
            {
                //一副数据,Sigma > 15% : 不稳定,变化太大,超出控制范围 , (当为自动时,停止所有加热)
                d.Stability = STABILITY.ERROR_SIGMA_OVERSIZE;
                return;
            }
        }

        /// <summary>
        /// 更新稳定状态,需要2幅数据才能比较的
        /// </summary>
        /// <param name="index">在列表的数据</param>
        void UpdateStable2(FlyData_FeedbackHeat d)
        {
            if (mData.Count() == 0)//没有以前的数据
                return;

            //找到之前没有交集的一幅数据, 并且它不是异常的
            int idx_last = mData.Count() - 1;
            FlyData_FeedbackHeat d_last;
            while (true)
            {
                idx_last = GetJustBeforeIdx(d, idx_last);
                if (idx_last < 0)//没有上一幅数据,暂时待定
                {
                    return;
                }
                d_last = mData[idx_last];
                if (CanCompared(d_last.Stability))
                {
                    break;
                }
                idx_last--;
                if (idx_last < 0)//没有上一幅数据,暂时待定
                    return;
            }

            if (Math.Abs((d_last.RotatePeriod - d.RotatePeriod).TotalSeconds / d.RotatePeriod.TotalSeconds) > 0.03)
            {
                //连续两幅图旋转时间变化 > 3%:不稳定,旋转速度波动大,测量不准确
                d.Stability = STABILITY.ERROR_ROTATE_CHANGED;
                return;
            }

            int avg = Misc.MyMath.Avg(d.Thicks);
            int avg_last = Misc.MyMath.Avg(d_last.Thicks);
            if (Math.Abs( ((double)(avg_last - avg)) / avg) > 0.05)
            {
                //厚度变化5%, 不稳定
                d.Stability = STABILITY.ERROR_THICK_CHANGED;
                return;
            }

            int[] thickpercents_diff, thickpercents_mid, heatpercents_diff, heatpercents_mid;

            GetPercentDatas(d, d_last,
                out thickpercents_diff, out thickpercents_mid,
                out heatpercents_diff, out heatpercents_mid);

            UpdateR(thickpercents_diff, thickpercents_mid, heatpercents_diff, heatpercents_mid);

            if (CurrR >= ThresholdR)
            {
                d.Stability = STABILITY.OK_HEAT_AND_THICK_CORREL;
                if (d.Heats.All((h) => { return h == 0; }))
                    d.Stability = STABILITY.OK_CORREL;
            }
        }

        void GetPercentDatas(FlyData_FeedbackHeat d, FlyData_FeedbackHeat d_last,
            out int[] thickpercents_diff,out int[] thickpercents_mid,
            out int[] heatpercents_diff,out int[] heatpercents_mid
            )
        {
            //厚度%偏差
            int[] thickpercents_now = Common.MyMath.GetPercent(d.Thicks);
            //当两幅图复位区号不一致时,移动以前的数据,使之一致
            int[] thickpercents_last = Common.MyMath.Move(Common.MyMath.GetPercent(d_last.Thicks), d.OrgBoltNo - d_last.OrgBoltNo);
            thickpercents_diff = Common.MyMath.GetDiff(thickpercents_now, thickpercents_last);
            thickpercents_mid = Common.MyMath.GetMid(thickpercents_now, thickpercents_last);

            //加热%偏差
            int[] heatpercents_now = Common.MyMath.OffsetAvgBe0(d.Heats);//平移到平均值为0
            heatpercents_now = Common.MyMath.ZoomIn(heatpercents_now, BoltCnt / ChannelCnt);//放大数量为分区量
            heatpercents_now = Common.MyMath.Filter(heatpercents_now, HeatEffectCurve.ToArray());//滤波变为加热对厚度的效果,还没 / Kp

            int[] heatpercents_last = Common.MyMath.OffsetAvgBe0(d_last.Heats);//平移到平均值为0
            heatpercents_last = Common.MyMath.ZoomIn(heatpercents_last, BoltCnt / ChannelCnt);//放大数量为分区量
            heatpercents_last = Common.MyMath.Filter(heatpercents_last, HeatEffectCurve.ToArray());//滤波变为加热对厚度的效果,还没 / Kp

            heatpercents_diff = Common.MyMath.GetDiff(heatpercents_last, heatpercents_now);//-加热增量, 它是反转的!!!!
            heatpercents_mid = Common.MyMath.GetMid(heatpercents_now, heatpercents_last);//加热均值
        }

        void UpdateR(
            int[] thickpercents_diff, int[] thickpercents_mid,
            int[] heatpercents_diff, int[] heatpercents_mid)
        {
            //降低要求
            thickpercents_diff = Common.MyMath.Filter(thickpercents_diff, 3);
            thickpercents_mid = Common.MyMath.Filter(thickpercents_mid, 3);
            heatpercents_diff = Common.MyMath.Filter(heatpercents_diff, 3);
            heatpercents_mid = Common.MyMath.Filter(heatpercents_mid, 3);

            double kp = (IsUsedLocalKp) ? LocalKp : Kp;
            if (kp < 1)
                kp = 1;

            //当加热全为0,使用StableRange0
            int stableRange = (heatpercents_diff.All((h) => h == 0)) ? StableRange0 : StableRange;
            if (stableRange < 1)
                stableRange = 1;

             
            for (int i = 0; i < BoltCnt; i++)
            {
                BoltHeatRecord record = new BoltHeatRecord()
                {
                    ThickDiff = thickpercents_diff[i],
                    ThickMid = thickpercents_mid[i],
                    HeatDiff = -heatpercents_diff[i],
                    HeatMid = heatpercents_mid[i]
                };
                mBoltData[i].ThickRange = StableRange0;
                mBoltData[i].HeatRange = 5;
                if ((Misc.MyBase.ISVALIDATA(thickpercents_diff[i])) &&
                    (Math.Abs(thickpercents_diff[i] + heatpercents_diff[i] / kp) <= stableRange))
                {
                    //稳定!!!!!
                    mBoltData[i].IsStable = true;
                    mBoltData[i].StableAdd(record);
                    
                }
                else
                {
                    mBoltData[i].IsStable = false;
                    mBoltData[i].UnstableAdd(record);
                }
            }

            CurrR = 1.0 * mBoltData.Count((_b) => { return _b.IsStable; }) / mBoltData.Count();


            var IsStables = from r in mBoltData select r.IsStable;
            BoltIsStable = IsStables.ToArray();

        }
        /// <summary>
        /// 执行自动对位
        /// </summary>
        /// <param name="d"></param>
        /// <returns>处理完</returns>
        void UpdateAutoONo(FlyData_FeedbackHeat d)
        {
           //d 这幅图,是刚加热生效的, 它必须是稳定的, 只有找到以前空加热的数据,对比就好了。


            if (mData.Count() == 0)//没有以前的数据
            {
                //异常
                AutoONoResult = EAutoONoResult.Err_Break;
                return;
            }


            //找到之前没有交集的一幅数据, 并且它不是异常的

            //找出空的那幅数据!!!!!
            int idx_last = mData.Count() - 1;
            FlyData_FeedbackHeat d_last;
            while (true)
            {
                idx_last = GetJustBeforeIdx(d, idx_last);
                if (idx_last < 0)//没有上一幅数据,暂时待定
                {
                    //异常
                    AutoONoResult = EAutoONoResult.Err_Break;
                    return;
                }
                d_last = mData[idx_last];
                if (CanCompared(d_last.Stability))
                {
                    break;
                }
                idx_last--;
                if (idx_last < 0)//没有上一幅数据,暂时待定
                {
                    //异常
                    AutoONoResult = EAutoONoResult.Err_Break;
                    return;
                }
            }

            if (Math.Abs((d_last.RotatePeriod - d.RotatePeriod).TotalSeconds / d.RotatePeriod.TotalSeconds) > 0.03)
            {
                //连续两幅图旋转时间变化 > 3%:不稳定,旋转速度波动大,测量不准确
                d.Stability = STABILITY.ERROR_ROTATE_CHANGED;
                //异常
                AutoONoResult = EAutoONoResult.Err_Break;
                return;
            }

            int avg = Misc.MyMath.Avg(d.Thicks);
            int avg_last = Misc.MyMath.Avg(d_last.Thicks);
            if (Math.Abs(((double)(avg_last - avg)) / avg) > 0.05)
            {
                //厚度变化5%, 不稳定
                d.Stability = STABILITY.ERROR_THICK_CHANGED;

                //异常
                AutoONoResult = EAutoONoResult.Err_Break;
                return;
            }



            int[] thickpercents_diff, thickpercents_mid, heatpercents_diff, heatpercents_mid;

            GetPercentDatas(d, d_last,
                out thickpercents_diff, out thickpercents_mid,
                out heatpercents_diff, out heatpercents_mid);

            //计算极差
            MaxMin = Common.MyMath.CalMaxMin(Common.MyMath.Filter(thickpercents_diff, 3));
            
            //计算平移
            int offset;
            double max_r;

            Common.MyMath.CalBestMove(heatpercents_diff, thickpercents_diff, 0.5, out offset, out max_r);
            MaxR = max_r;

            int orgboltno = d.OrgBoltNo + offset;
            if (orgboltno > BoltCnt)
                orgboltno -= BoltCnt;
            else if (orgboltno < 1)
                orgboltno += BoltCnt;

            BestOrgBoltNo = orgboltno;

            //计算Kp
            int[] thickpercents_diff_mov = Common.MyMath.Move(thickpercents_diff, offset);

            double b;
            double a;
            Misc.MyMath.Linest(heatpercents_diff, thickpercents_diff_mov, out a, out b);
            BestKp = a;

            if (MaxMin >= ThresholdMaxMin)
            {
                if (MaxR >= ThresholdR)
                {
                    //计算结果可靠性很高
                    AutoONoResult = EAutoONoResult.OK;
                }
                else
                {
                    AutoONoResult = EAutoONoResult.Err_MaxR;
                }
            }
            else
            {
                AutoONoResult = EAutoONoResult.Err_MaxMin;
            }

            if (AutoONoResult == EAutoONoResult.OK)
            {
                Kp = BestKp;

                if (offset != 0)
                {
                    d.Thicks = Common.MyMath.Move(d.Thicks, offset);
                    d.OrgBoltNo = BestOrgBoltNo;


                    thickpercents_diff = Common.MyMath.Move(thickpercents_diff, offset);
                    thickpercents_mid = Common.MyMath.Move(thickpercents_mid, offset);
                    ClearBoltHeat();
                }
            }

            UpdateR(thickpercents_diff, thickpercents_mid, heatpercents_diff, heatpercents_mid);

            if (CurrR >= ThresholdR)
            {
                d.Stability = STABILITY.OK_HEAT_AND_THICK_CORREL;
                if (d.Heats.All((h) => { return h == 0; }))
                    d.Stability = STABILITY.OK_CORREL;
            }
        }




        #region 列表
        /// <summary>
        /// 获取记录历史 返回类型为 FlyData_FeedbackHeat
        /// </summary>
        /// <param name="bookmark">记录点</param>
        /// <param name="AsyncDelegate"></param>
        /// <param name="AsyncState"></param>
        public void GetHeatsData(int bookmark, AsyncCBHandler AsyncDelegate, object AsyncState)
        {
            int idx = mData.No2Index(bookmark);
            if (idx < 0 || idx >= mData.Count())
            {
                //返回空数据
                AsyncDelegate(AsyncState, null);
            }
            else
            {
                AsyncDelegate(AsyncState, mData[idx]);
            }
        }

        #endregion

        /// <summary>
        /// 清空每个分区的加热记录
        /// </summary>
        public void ClearBoltHeat()
        {
            foreach (BoltHeat h in mBoltData)
            {
                h.StableList.Clear();
                h.UnstableList.Clear();
            }
        }

        /// <summary>
        /// 获取每个分区的加热历史 返回 FlyData_BoltHeatRecord
        /// </summary>
        /// <param name="no">分区号</param>
        /// <param name="AsyncDelegate"></param>
        /// <param name="AsyncState"></param>
        public void GetBoltHeatRecord(int no, AsyncCBHandler AsyncDelegate, object AsyncState)
        {
            if (no < 1 || no > mBoltData.Count())
            {
                AsyncDelegate(AsyncState, null);
            }
            else
            {
                FlyData_BoltHeatRecord f = new FlyData_BoltHeatRecord();
                f.StableList = mBoltData[no - 1].StableList.ToArray();
                f.UnstableList = mBoltData[no - 1].UnstableList.ToArray();
                AsyncDelegate(AsyncState, f);
            }
        }

        public void Apply()
        {
            Save();
        }
        bool Load()
        {
            return Misc.SaveToXmlHepler.Load("heatbuf.xml", this);
        }
        void Save()
        {
            Misc.SaveToXmlHepler.Save("heatbuf.xml", this);
        }

        #region INotifyPropertyChanged 成员

        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged(string propertyname)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyname));
            }
        }
        #endregion

        public string[] GetSavePropertyNames()
        {
            return new string[]{
                "HeatEffectCurve",
                "StableRange",
                "StableRange0",
                "ThresholdR",
                "ThresholdMaxMin",
                "ThresholdSigmaMax",
                "IsUsedLocalKp",
                "LocalKp"
            };
        }
    }

    /// <summary>
    /// 单个分区判断
    /// </summary>
    public class BoltHeat
    {
        /// <summary>
        /// 当前是否稳定
        /// </summary>
        public bool IsStable = false;
        /// <summary>
        /// 稳定列表
        /// </summary>
        public RList<BoltHeatRecord> StableList;
        /// <summary>
        /// 不稳定列表
        /// </summary>
        public RList<BoltHeatRecord> UnstableList;
        /// <summary>
        /// 厚度%相同的定义
        /// </summary>
        public int ThickRange=5;
        /// <summary>
        /// 加热%相同的定义
        /// </summary>
        public int HeatRange=5;

        public BoltHeat()
        {
            StableList = new RList<BoltHeatRecord>(60);
            UnstableList = new RList<BoltHeatRecord>(60);
            
        }
        public void StableAdd(BoltHeatRecord r)
        {
            var ss = from s in StableList
                     where
                     (Math.Abs(s.HeatDiff - r.HeatDiff) <= HeatRange) &&
                     (Math.Abs(s.HeatMid - r.HeatMid) <= HeatRange) &&
                     (Math.Abs(s.ThickDiff - r.ThickDiff) <= ThickRange) &&
                     (Math.Abs(s.ThickMid - r.ThickMid) <= ThickRange)
                     select s;
            if (ss.Count() > 0)
            {
                ss.First().Cnt++;
            }
            else
            {
                StableList.Add(r);
            }
        }
        public void UnstableAdd(BoltHeatRecord r)
        {
            var ss = from s in UnstableList
                     where
                     (Math.Abs(s.HeatDiff - r.HeatDiff) <= HeatRange) &&
                     (Math.Abs(s.HeatMid - r.HeatMid) <= HeatRange) &&
                     (Math.Abs(s.ThickDiff - r.ThickDiff) <= ThickRange) &&
                     (Math.Abs(s.ThickMid - r.ThickMid) <= ThickRange)
                     select s;
            if (ss.Count() > 0)
            {
                ss.First().Cnt++;
            }
            else
            {
                UnstableList.Add(r);
            }
        }
        /// <summary>
        /// 根据历史,判断最佳输出
        /// </summary>
        /// <param name="thickpercent">当前厚度%</param>
        /// <param name="heat">当前加热%</param>
        /// <param name="offset">准备要改变的加热量</param>
        /// <returns></returns>
        public int Suggest(int thickpercent, int heat, int offset)
        {
            
            if (offset == 0)//没有加热,直接返回
                return offset;
            if (StableList.Count() == 0 && UnstableList.Count() == 0)//没有历史,直接返回
                return offset;

            //从稳定的历史找相同的加热
            var lr_s = from r in StableList
                    where r.IsSameThick(thickpercent, ThickRange) &&
                    (Math.Abs(Math.Abs(offset) - Math.Abs(r.HeatDiff)) <= HeatRange)
                    select r;
            int cnt = lr_s.Sum((r) => { return r.Cnt; });
            if (cnt > 3)//数量要足够多,才可信
            {
                //看看以前这样加热 厚度变化了多少
                int thickdiff;
                if (offset > 0)
                {
                    thickdiff = (int)lr_s.Average((r) =>
                    {
                        if (r.HeatDiff > 0)
                            return r.ThickDiff;
                        else
                            return -r.ThickDiff;
                    });
                }
                else
                {
                    thickdiff = (int)lr_s.Average((r) =>
                    {
                        if (r.HeatDiff > 0)
                            return -r.ThickDiff;
                        else
                            return r.ThickDiff;
                    });
                }
                if (Math.Abs(thickdiff) <= ThickRange)
                {
                    //变化很小,不如别调
                    //TODO, 加热以前最小的加热量
                    //int min_heat = lr_s.Min((r) => { return Math.Min(Math.Abs(r.Heat0), Math.Abs(r.Heat1)); });
                    //offset = min_heat - heat;
                    //return offset;
                    return 0;
                }
            }
            else
            {
                //这样加热没有稳定的历史

                //从不稳定的历史找相同的加热
                var lr_u = from r in UnstableList
                           where r.IsSameThick(thickpercent, ThickRange) &&
                           (Math.Abs(Math.Abs(offset) - Math.Abs(r.HeatDiff)) <= HeatRange)
                           select r;
                cnt = lr_u.Sum((r) => { return r.Cnt; });
                if (cnt > 3)//数量要足够多,才可信
                {
                    //这样加热肯定不稳定,别调了
                    return 0;
                }
            }
            return offset;
        }

        

    }

}