using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using LumenWorks.Framework.IO.Csv;
using System.IO;
using DotSpatial.Topology.Voronoi;
using System.Windows.Forms;
using DotSpatial.Data;

namespace SMAT_CE
{
    class OzoneCommonClass
    {
        public static DateTime _beginTime;//记录开始时间
        public static DateTime _endTime;//记录结束时间
        public static string _resultFilePath = "";
        public static bool OzoneAnalysis(BaseScenario baseScenario, SMAT_CE mats)
        {
            if (!(baseScenario.configuration is OzoneAnalysisConfiguration))
            {
                return false;
            }
            try
            {
                OzoneAnalysisConfiguration ozoneAnalysisConfiguration = (baseScenario.configuration) as OzoneAnalysisConfiguration;
                string sFirstLine = "";

                _beginTime = DateTime.Now;
                CommonClass.CurrentLog = "Read monitor data \"" + Path.GetFileName(ozoneAnalysisConfiguration.dataInputO.ozoneMonitorDataFile) + "\".";
                CommonClass.CurrentBaseScenario.log.lstLog.Add(CommonClass.CurrentLog);
                bool errorOccur = false;
                DataTable dtMonitor = CommonClass.getDataSetFromCSVAndFirstLine(ozoneAnalysisConfiguration.dataInputO.ozoneMonitorDataFile, ref sFirstLine, ref errorOccur);
                if (dtMonitor == null || errorOccur)
                {
                    CommonClass.CurrentLog = "Fail to read monitor data \"" + Path.GetFileName(ozoneAnalysisConfiguration.dataInputO.ozoneMonitorDataFile) + "\".";
                    CommonClass.CurrentBaseScenario.log.lstLog.Add(CommonClass.CurrentLog);
                    return false;
                }

                string startYear = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneStartYear.Split('-')[1];
                string endYear = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Split('-')[1];
                List<string> lstMonitorYear = new List<string>();
                for (int i = Convert.ToInt16(startYear); i <= Convert.ToInt16(endYear); i++)
                {
                    lstMonitorYear.Add(i.ToString());
                }
                string lastYear = "";
                #region Read Monitor from csv
                Dictionary<string, OzoneMonitor> dicOzoneMonitor = new Dictionary<string, OzoneMonitor>();
                //-------首先得到各个字段的index-------
                int iID = -1, iType = -1, iLat = -1, iLong = -1, iPOC = -1, iDVYear = -1, iO3 = -1, iStateName = -1, iCountyName = -1;
                try
                {
                    for (int i = 0; i < dtMonitor.Columns.Count; i++)
                    {
                        DataColumn dc = dtMonitor.Columns[i];
                        switch (dc.ColumnName.ToLower().Trim())
                        {
                            case "_id":
                                iID = i;
                                break;
                            case "_type":
                                iType = i;
                                break;
                            case "lat":
                                iLat = i;
                                break;
                            case "long":
                                iLong = i;
                                break;
                            case "poc":
                                iPOC = i;
                                break;
                            case "dvyear":
                                iDVYear = i;
                                break;
                            case "_state_name":
                                iStateName = i;
                                break;
                            case "_county_name":
                                iCountyName = i;
                                break;
                            case "o3":
                                iO3 = i;
                                break;
                        }
                    }
                    //bool isOK = true;
                    foreach (DataRow dr in dtMonitor.Rows)
                    {
                        //try
                        //{
                        //----------解析Monitor 首先去掉=-9的值，然后根据StartYear 求出 StartYear,StartYear+1,StartYear+2的均值*10 -> int /10 最后仍然是int 值。如果都没有Ozone="."
                        //if ((dr[iDVYear].ToString() == ozoneAnalysisConfiguration.filteringInterpolationO.endYear.Substring(0,4) ||
                        //    dr[iDVYear].ToString() == (Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.endYear.Substring(0, 4)) + 1).ToString() ||
                        //    dr[iDVYear].ToString() == (Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.endYear.Substring(0, 4)) + 2).ToString()))
                        //{
                        if (dicOzoneMonitor.ContainsKey(dr[iID].ToString()))
                        {
                            dicOzoneMonitor[dr[iID].ToString()].dicOzone.Add(dr[iDVYear].ToString(), Convert.ToDouble(dr[iO3]));

                        }
                        else
                        {
                            dicOzoneMonitor.Add(dr[iID].ToString(), new OzoneMonitor());
                            dicOzoneMonitor[dr[iID].ToString()].dicOzone = new Dictionary<string, double>();
                            dicOzoneMonitor[dr[iID].ToString()].dicOzone.Add(dr[iDVYear].ToString(), Convert.ToDouble(dr[iO3]));
                            dicOzoneMonitor[dr[iID].ToString()].id = dr[iID].ToString();
                            dicOzoneMonitor[dr[iID].ToString()].lat = Convert.ToDouble(dr[iLat]);
                            dicOzoneMonitor[dr[iID].ToString()].longitude = Convert.ToDouble(dr[iLong]);
                            dicOzoneMonitor[dr[iID].ToString()].county = dr[iCountyName].ToString();
                            dicOzoneMonitor[dr[iID].ToString()].state = dr[iStateName].ToString();
                        }

                    }

                }
                catch
                {
                    CommonClass.CurrentLog = "Fail to read monitor data \"" + Path.GetFileName(ozoneAnalysisConfiguration.dataInputO.ozoneMonitorDataFile) + "\".";
                    CommonClass.CurrentBaseScenario.log.lstLog.Add(CommonClass.CurrentLog);
                    return false;
                }
                dtMonitor.Dispose();
                GC.Collect();

                _endTime = DateTime.Now;
                CommonClass.TotalTime = Math.Round(_endTime.Subtract(_beginTime).TotalSeconds, 3);
                CommonClass.CurrentLog = "Finish reading monitor data: " + CommonClass.TotalTime + " s.";
                CommonClass.CurrentBaseScenario.log.lstLog.Add(CommonClass.CurrentLog);

                #region
                //--------------修正dicOzoneMonitor的坐标系！-------------------
                double[] dConvertArrayMonitor = null;
                List<double> lstConvertArrayMonitor = new List<double>();
                List<string> lstKeyMonitor = dicOzoneMonitor.Keys.ToList();
                for (int iLstKey = 0; iLstKey < dicOzoneMonitor.Keys.Count; iLstKey++)
                {
                    lstConvertArrayMonitor.Add(dicOzoneMonitor[lstKeyMonitor[iLstKey]].longitude);
                    lstConvertArrayMonitor.Add(dicOzoneMonitor[lstKeyMonitor[iLstKey]].lat);
                }
                dConvertArrayMonitor = lstConvertArrayMonitor.ToArray();
                DotSpatial.Projections.Reproject.ReprojectPoints(dConvertArrayMonitor, null, DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984,
                   DotSpatial.Projections.ProjectionInfo.FromProj4String(CommonClass.projUSACMAQ), 0, dConvertArrayMonitor.Length / 2);
                for (int iLstKey = 0; iLstKey < dicOzoneMonitor.Keys.Count; iLstKey++)
                {
                    dicOzoneMonitor[lstKeyMonitor[iLstKey]].longitudeLamber = dConvertArrayMonitor[2 * iLstKey] / 100.00;
                    dicOzoneMonitor[lstKeyMonitor[iLstKey]].latitudeLamber = dConvertArrayMonitor[2 * iLstKey + 1] / 100.00;
                }
                #endregion
                List<string> lstrequiredDVPeriods = new List<string>();
                if (ozoneAnalysisConfiguration.filteringInterpolationO.requiredDVPeriods != "None selected")
                {
                    string[] s = ozoneAnalysisConfiguration.filteringInterpolationO.requiredDVPeriods.Split(',');
                    for (int i = 0; i < s.Count(); i++)
                    {
                        lstrequiredDVPeriods.Add(s[i].Substring(s[i].Length - 4, 4));
                    }
                }
                ozoneAnalysisConfiguration.filteringInterpolationO.minNumDV = ozoneAnalysisConfiguration.filteringInterpolationO.minNumDV > lstMonitorYear.Count ? lstMonitorYear.Count : ozoneAnalysisConfiguration.filteringInterpolationO.minNumDV;
                foreach (KeyValuePair<string, OzoneMonitor> k in dicOzoneMonitor)
                {
                    //dicOzoneMonitor[k.Key].dicOzone = dicOzoneMonitor[k.Key].dicOzone.Where(p => p.Value != -9).ToList();
                    if (k.Key == "011210003")
                    {

                    }
                    List<double> lstTemp = new List<double>();
                    bool isValid = true;
                    int iValid = 0;

                    foreach (KeyValuePair<string, double> kin in dicOzoneMonitor[k.Key].dicOzone)
                    {
                        if (lstMonitorYear.Contains(kin.Key))
                        //if ((kin.Key == ozoneAnalysisConfiguration.filteringInterpolationO.requiredDVPeriods.Substring(0, 4) ||
                        //kin.Key == (Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.requiredDVPeriods.Substring(0, 4)) + 1).ToString() ||
                        //kin.Key == (Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.requiredDVPeriods.Substring(0, 4)) + 2).ToString()))
                        {
                            if (kin.Value >= 0)
                            {
                                lstTemp.Add(kin.Value);
                                iValid++;
                            }
                            else if (lstrequiredDVPeriods.Contains(kin.Key))
                            {
                                isValid = false;
                                break;
                            }

                        }
                    }

                    if (iValid < ozoneAnalysisConfiguration.filteringInterpolationO.minNumDV)
                        isValid = false;
                    if (lstTemp.Count > 0 && isValid)
                    {
                        //if (lstTemp.Count <= 2)
                        //{
                        //    dicOzoneMonitor[k.Key].ozone = -7;
                        //}
                        //else
                        //{
                        dicOzoneMonitor[k.Key].ozone = Math.Round(lstTemp.Average(), 1);// Convert.ToInt32((dicOzoneMonitor[k.Key].lstOzone.Average() * 10)) / 10;
                        dicOzoneMonitor[k.Key].datacount = lstTemp.Count;
                        //}
                    }
                    else
                        dicOzoneMonitor[k.Key].ozone = -7;
                }

                #endregion
                //----------解析Monitor 首先去掉=-9的值，然后根据StartYear 求出 StartYear,StartYear+1,StartYear+2的均值*10 -> int /10 最后仍然是int 值。如果都没有Ozone="."

                // DataSet dsModelBase = CommonClass.getDataSetFromCSV(ozoneAnalysisConfiguration.dataInputO.baselineFile);//-------太大了。
                #region Read OzoneModel Base from csv
                //CommonClass.CurrentBaseScenario.log.lstLog.Add("Begin loading Baseline Model Data...");
                //CommonClass.CurrentLog = "Begin loading Baseline Model Data...";
                _beginTime = DateTime.Now;
                CommonClass.CurrentLog = "Read model data \"" + Path.GetFileName(ozoneAnalysisConfiguration.dataInputO.baselineModelDataFile) + "\".";
                CommonClass.CurrentBaseScenario.log.lstLog.Add(CommonClass.CurrentLog);

                iID = -1; iType = -1; iLat = -1; iLong = -1; iO3 = -1;
                int iDate = -1;
                Dictionary<string, OzoneModel> dicOzoneModel = new Dictionary<string, OzoneModel>();
                //读ModelBase
                // 要与只读方式打开csv文件，可以防止excel文档被占用问题
                FileStream fs = new FileStream(ozoneAnalysisConfiguration.dataInputO.baselineModelDataFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                try
                {
                    using (StreamReader csv = new StreamReader(fs, System.Text.Encoding.UTF8))
                    {
                        //int fieldCount = csv.FieldCount;

                        //string[] headers = csv.GetFieldHeaders();
                        //csv.ReadNextRecord(false,true);
                        string strLine = csv.ReadLine();
                        string[] strLineArray = csv.ReadLine().Split(new char[] { ',' });
                        int i = 0;
                        while (i < strLineArray.Length)
                        {
                            string s = strLineArray[i];
                            switch (s.Trim().ToLower())
                            {
                                case "_id":
                                    iID = i;
                                    break;
                                case "_type":
                                    iType = i;
                                    break;
                                case "lat":
                                    iLat = i;
                                    break;
                                case "long":
                                    iLong = i;
                                    break;
                                case "date":
                                    iDate = i;
                                    break;
                                case "o3":
                                    iO3 = i;
                                    break;

                            }
                            i++;
                        }
                        while (strLine != null)
                        {
                            strLine = csv.ReadLine();
                            if (strLine == null) break;
                            strLineArray = strLine.Split(new char[] { ',' });
                            //if (strLineArray[iDate].Substring(0, 4) != startYear) continue;
                            if (dicOzoneModel.ContainsKey(strLineArray[iID].ToString().Trim()))//strLineArray[iDate].Substring(0, 4)))
                            {
                                //try
                                //{
                                dicOzoneModel[strLineArray[iID].ToString().Trim()].lstOzone.Add(strLineArray[iDate].Substring(4), new float[2] { Convert.ToSingle(strLineArray[iO3]), -9 });
                                //}
                                //catch
                                //{
                                //}
                            }
                            else
                            {
                                dicOzoneModel.Add(strLineArray[iID].ToString().Trim(), new OzoneModel()
                                {
                                    Date = strLineArray[iDate].Substring(0, 4),
                                    id = strLineArray[iID],
                                    lat = Convert.ToDouble(strLineArray[iLat]),
                                    longitude = Convert.ToDouble(strLineArray[iLong]),
                                    type = strLineArray[iType],
                                    lstOzone = new Dictionary<string, float[]>(),
                                    // lstOzoneForecast = new Dictionary<string, float>(),
                                });
                                dicOzoneModel[strLineArray[iID].ToString().Trim()].lstOzone.Add(strLineArray[iDate].Substring(4), new float[2] { Convert.ToSingle(strLineArray[iO3]), -9 });
                            }

                        }
                        csv.Dispose(); fs.Dispose();
                        GC.Collect();
                    }
                }
                catch
                {
                    CommonClass.CurrentLog = "Fail to read model data \"" + Path.GetFileName(ozoneAnalysisConfiguration.dataInputO.baselineModelDataFile) + "\".";
                    CommonClass.CurrentBaseScenario.log.lstLog.Add(CommonClass.CurrentLog);
                    return false;
                }

                #endregion
                _endTime = DateTime.Now;
                CommonClass.TotalTime = Math.Round(_endTime.Subtract(_beginTime).TotalSeconds, 3);
                CommonClass.CurrentLog = "Finish reading model data: " + CommonClass.TotalTime + " s.";
                CommonClass.CurrentBaseScenario.log.lstLog.Add(CommonClass.CurrentLog);

                _beginTime = DateTime.Now;
                CommonClass.CurrentLog = "Read model data \"" + Path.GetFileName(ozoneAnalysisConfiguration.dataInputO.forecastModelDataFile) + "\".";
                CommonClass.CurrentBaseScenario.log.lstLog.Add(CommonClass.CurrentLog);
                #region Read Ozone Model Forcast from csv
                //CommonClass.CurrentBaseScenario.log.lstLog.Add("Begin loading forecast model data...");
                //CommonClass.CurrentLog = "Begin loading forecast model data...";
                _beginTime = DateTime.Now;
                //要与只读方式打开csv文件，可以防止excel文档被占用问题
                fs = new FileStream(ozoneAnalysisConfiguration.dataInputO.forecastModelDataFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                try
                {
                    using (StreamReader csv = new StreamReader(fs, System.Text.Encoding.UTF8))
                    {
                        //int fieldCount = csv.FieldCount;

                        //string[] headers = csv.GetFieldHeaders();
                        //csv.ReadNextRecord(false,true);
                        string strLine = csv.ReadLine();
                        string[] strLineArray = csv.ReadLine().Split(new char[] { ',' });
                        int i = 0;
                        while (i < strLineArray.Length)
                        {
                            string s = strLineArray[i];
                            switch (s.Trim().ToLower())
                            {
                                case "_id":
                                    iID = i;
                                    break;
                                case "_type":
                                    iType = i;
                                    break;
                                case "lat":
                                    iLat = i;
                                    break;
                                case "long":
                                    iLong = i;
                                    break;
                                case "date":
                                    iDate = i;
                                    break;
                                case "o3":
                                    iO3 = i;
                                    break;

                            }
                            i++;
                        }
                        while (strLine != null)
                        {
                            strLine = csv.ReadLine();
                            if (strLine == null) break;
                            strLineArray = strLine.Split(new char[] { ',' });
                            //if (strLineArray[iDate].Substring(0, 4) != startYear) continue;
                            if (lastYear == "") lastYear = strLineArray[iDate].Substring(0, 4);
                            if (strLineArray[iID] == "140001" && strLineArray[iDate] == "20150625")
                            {
                            }
                            if (dicOzoneModel.ContainsKey(strLineArray[iID].ToString().Trim()))
                            {
                                //dicOzoneModel[strLineArray[iID].ToString().Trim()].lstOzoneForecast.Add(strLineArray[iDate].Substring(4), Convert.ToSingle(strLineArray[iO3]));
                                float f = Convert.ToSingle(Convert.ToDecimal(strLineArray[iO3]));
                                dicOzoneModel[strLineArray[iID].ToString().Trim()].lstOzone[strLineArray[iDate].Substring(4)][1] = f;// Convert.ToSingle(strLineArray[iO3]);
                            }
                            else
                            {

                            }

                        }
                        csv.Dispose(); fs.Dispose();
                        GC.Collect();
                    }
                }
                catch
                {
                    CommonClass.CurrentLog = "Fail to read model data \"" + Path.GetFileName(ozoneAnalysisConfiguration.dataInputO.forecastModelDataFile) + "\".";
                    CommonClass.CurrentBaseScenario.log.lstLog.Add(CommonClass.CurrentLog);
                    return false;
                }
                //--------------修正dicQuarterlyModelDataPM的坐标系！-------------------
                #region
                double[] dConvertArrayModel = null;
                List<double> lstConvertArrayModel = new List<double>();
                List<string> lstKeyModel = dicOzoneModel.Keys.ToList();
                for (int iLstKey = 0; iLstKey < dicOzoneModel.Keys.Count; iLstKey++)
                {
                    lstConvertArrayModel.Add(dicOzoneModel[lstKeyModel[iLstKey]].longitude);
                    lstConvertArrayModel.Add(dicOzoneModel[lstKeyModel[iLstKey]].lat);
                }
                dConvertArrayModel = lstConvertArrayModel.ToArray();
                DotSpatial.Projections.Reproject.ReprojectPoints(dConvertArrayModel, null, DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984,
                   DotSpatial.Projections.ProjectionInfo.FromProj4String(CommonClass.projUSACMAQ), 0, dConvertArrayModel.Length / 2);
                for (int iLstKey = 0; iLstKey < dicOzoneModel.Keys.Count; iLstKey++)
                {
                    dicOzoneModel[lstKeyModel[iLstKey]].longitudeLamber = dConvertArrayModel[2 * iLstKey] / 100.00;
                    dicOzoneModel[lstKeyModel[iLstKey]].latitudeLamber = dConvertArrayModel[2 * iLstKey + 1] / 100.00;
                }
                #endregion

                _endTime = DateTime.Now;
                CommonClass.TotalTime = Math.Round(_endTime.Subtract(_beginTime).TotalSeconds, 3);

                //读ModelControl
                #endregion
                _endTime = DateTime.Now;
                CommonClass.TotalTime = Math.Round(_endTime.Subtract(_beginTime).TotalSeconds, 3);
                CommonClass.CurrentLog = "Finish reading model data: " + CommonClass.TotalTime + " s.";
                CommonClass.CurrentBaseScenario.log.lstLog.Add(CommonClass.CurrentLog);

                //change project - write in dictionary (lat,long to lambert) - for draw map
                DataTable dt = new DataTable();
                dt.Columns.Add("id");
                dt.Columns.Add("lat");
                dt.Columns.Add("long");
                foreach (KeyValuePair<string, OzoneModel> keyvalue in dicOzoneModel)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = keyvalue.Key;
                    dr[1] = keyvalue.Value.lat;
                    dr[2] = keyvalue.Value.longitude;
                    dt.Rows.Add(dr);
                }
                mats.changeProject(dt, "USA");


                if (!CommonClass.IsBatch)
                {
                    if (_resultFilePath == "" && _resultFilePath.Length == 0 || _resultFilePath != CommonClass.ResultFilePath + @"\Result\Output\" + ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName)
                        _resultFilePath = CommonClass.ResultFilePath + @"\Result\Output\" + ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName;
                }
                else
                {
                    if (_resultFilePath == "" && _resultFilePath.Length == 0 || _resultFilePath != CommonClass.ResultFilePath + @"\" + ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName)
                        _resultFilePath = CommonClass.ResultFilePath + @"\" + ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName;
                }
                if (!Directory.Exists(_resultFilePath))
                    System.IO.Directory.CreateDirectory(_resultFilePath);
                _beginTime = DateTime.Now;
                //Del这个步骤
                foreach (KeyValuePair<string, OzoneModel> k in dicOzoneModel)
                {
                    getThresholdsOfOzoneModel(k.Value, ozoneAnalysisConfiguration, true);//model ozone base,future,rrf used in calculate vna/evna (1*1)
                }
                //if do vna/evna future and check do backstop, model data(base,future,rrf..) used in calculate monitor and spatial field is different.
                //output the model data used for calculate sparial field now..
                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doQuarterlyModelData)
                {
                    SaveOzoneQuarterlyModelData(CommonClass.CurrentBaseScenario, dicOzoneModel, lastYear);
                }
                _endTime = DateTime.Now;
                CommonClass.TotalTime = Math.Round(_endTime.Subtract(_beginTime).TotalSeconds, 3);
                CommonClass.CurrentBaseScenario.log.lstLog.Add("Finish computing gradient structures: " + CommonClass.TotalTime + " s.");
                CommonClass.CurrentLog = "Finish computing gradient structures: " + CommonClass.TotalTime + " s.";

                #region Get Point Value And Save

                _beginTime = DateTime.Now;

                //--------------首先得到monitor属于哪个网格-------简单的方法可以判断以最近的点作为它的网格。首先可以求出第一个网格的大小，在小于一倍网格宽度和长度的最大值求最近点
                Dictionary<string, string> dicMonitorInModel = new Dictionary<string, string>();
                double dFirst = dicOzoneModel.First().Value.longitude, dLen = 0, dLat = 0;
                int iFirst = Convert.ToInt32(dicOzoneModel.First().Key);

                if (dicOzoneModel.ContainsKey((((iFirst / 1000) + 1) * 1000 + iFirst % 1000).ToString()))
                {

                    dLen = Math.Abs(dicOzoneModel[(((iFirst / 1000) + 1) * 1000 + iFirst % 1000).ToString()].longitude -
                        dicOzoneModel.First().Value.longitude
                        );
                    dLat = Math.Abs(dicOzoneModel[(((iFirst / 1000)) * 1000 + iFirst % 1000 + 1).ToString()].lat -
                        dicOzoneModel.First().Value.lat
                        );
                    dLen *= 2; dLat *= 2;

                }
                //----------修正算法 首先计算出所有的左上角和右下角以及Model中心点的对应关系--------
                Dictionary<string, Extent> dicExtentForModel = new Dictionary<string, Extent>();
                foreach (KeyValuePair<string, OzoneModel> k in dicOzoneModel)
                {
                    try
                    {
                        if (k.Key == "182144")
                        {
                        }
                        int Col = Convert.ToInt32(k.Key) / 1000;
                        int Row = Convert.ToInt32(k.Key) % 1000;
                        //------如果没有上格，则使用下格
                        OzoneModel ozoneModelTop = null, ozoneModelLeft = null;
                        if (dicOzoneModel.ContainsKey(((Col - 1) * 1000 + Row).ToString()))
                        {
                            ozoneModelLeft = dicOzoneModel[((Col - 1) * 1000 + Row).ToString()];
                        }
                        else if (dicOzoneModel.ContainsKey(((Col + 1) * 1000 + Row).ToString()))
                        {
                            ozoneModelLeft = dicOzoneModel[((Col + 1) * 1000 + Row).ToString()];
                        }
                        if (dicOzoneModel.ContainsKey((Col * 1000 + Row + 1).ToString()))
                        {
                            ozoneModelTop = dicOzoneModel[(Col * 1000 + Row + 1).ToString()];
                        }
                        else if (dicOzoneModel.ContainsKey((Col * 1000 + Row - 1).ToString()))
                        {
                            ozoneModelTop = dicOzoneModel[(Col * 1000 + Row - 1).ToString()];
                        }
                        if (ozoneModelLeft != null && ozoneModelTop != null)
                        {
                            dicExtentForModel.Add(k.Key, new Extent(k.Value.longitude - Math.Abs(ozoneModelTop.longitude - ozoneModelLeft.longitude) / 2.00,
                                k.Value.lat - Math.Abs(ozoneModelLeft.lat - ozoneModelTop.lat) / 2.00, k.Value.longitude + Math.Abs(ozoneModelTop.longitude - ozoneModelLeft.longitude) / 2.00,
                                k.Value.lat + Math.Abs(ozoneModelLeft.lat - ozoneModelTop.lat) / 2.00));

                        }
                    }
                    catch (Exception ex)
                    {
                        CommonClass.LogError(ex);
                    }

                }
                //---------计算两个网格之内；然后属于哪个的网格
                foreach (KeyValuePair<string, OzoneMonitor> k in dicOzoneMonitor)
                {
                    //double dlenTemp = dLen;
                    if (k.Key == "090050005")
                    {
                    }
                    try
                    {
                        var query = dicOzoneModel.Where(p => Math.Abs(p.Value.longitude - k.Value.longitude) < dLen && Math.Abs(p.Value.lat - k.Value.lat) < dLat).ToList();
                        string sModelIDTemp = "";
                        if (query.Count() > 0)
                        {
                            DotSpatial.Topology.Coordinate coor = new DotSpatial.Topology.Coordinate(k.Value.longitude, k.Value.lat);
                            if (k.Key == "90090027" || k.Key == "090090027")
                            {
                                Dictionary<string, double> dicDistance = new Dictionary<string, double>();
                                foreach (KeyValuePair<string, OzoneModel> kModel in query)
                                {
                                    dicDistance.Add(kModel.Key, CommonClass.getDistanceFrom2Point(kModel.Value.longitude, kModel.Value.lat, k.Value.longitude, k.Value.lat));
                                }
                            }
                            if (sModelIDTemp == "")
                            {
                                sModelIDTemp = query.OrderBy(p => CommonClass.getDistanceFrom2Point(p.Value.longitude, p.Value.lat, k.Value.longitude, k.Value.lat)).First().Key;
                                dicMonitorInModel.Add(k.Key, sModelIDTemp);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        CommonClass.LogError(ex);
                    }
                }

                //--------------------根据3*3 
                Dictionary<string, OzoneMonitorControl> dicOzoneMonitorControl = new Dictionary<string, OzoneMonitorControl>();
                Dictionary<string, OzoneMonitorControlMax> dicOzoneMonitorControlMax = new Dictionary<string, OzoneMonitorControlMax>();

                List<Dictionary<string, OzoneMonitorControl>> lstDicOzoneMonitorControlPeriod = new List<Dictionary<string, OzoneMonitorControl>>();
                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doDesignValuePeriods)
                {
                    for (int i = 0; i < lstMonitorYear.Count; i++)
                    {
                        lstDicOzoneMonitorControlPeriod.Add(new Dictionary<string, OzoneMonitorControl>());
                    }
                    //lstDicOzoneMonitorControlPeriod.Add(new Dictionary<string, OzoneMonitorControl>());
                    //lstDicOzoneMonitorControlPeriod.Add(new Dictionary<string, OzoneMonitorControl>());

                }
                foreach (KeyValuePair<string, OzoneMonitor> k in dicOzoneMonitor)
                {
                    //---------首先根据
                    if (!dicMonitorInModel.ContainsKey(k.Key)) continue;
                    int Col = Convert.ToInt32(dicMonitorInModel[k.Key]) / 1000;
                    int Row = Convert.ToInt32(dicMonitorInModel[k.Key]) % 1000;
                    List<string> lstSurround = new List<string>();
                    switch (ozoneAnalysisConfiguration.dataInputO.temporalAdjustmentAtMonitorGrid)
                    {
                        case "1x1":
                            lstSurround.Add(dicMonitorInModel[k.Key]);
                            break;
                        case "3x3":
                            for (int i3 = -1; i3 <= 1; i3++)
                            {
                                for (int j3 = -1; j3 <= 1; j3++)
                                {
                                    lstSurround.Add(((Col + i3) * 1000 + (Row + j3)).ToString());
                                }

                            }
                            break;
                        case "5x5":
                            for (int i5 = -2; i5 <= 2; i5++)
                            {
                                for (int j5 = -2; j5 <= 2; j5++)
                                {
                                    lstSurround.Add(((Col + i5) * 1000 + (Row + j5)).ToString());
                                }

                            }
                            break;
                        case "7x7":
                            for (int i7 = -3; i7 <= 3; i7++)
                            {
                                for (int j7 = -3; j7 <= 3; j7++)
                                {
                                    lstSurround.Add(((Col + i7) * 1000 + (Row + j7)).ToString());
                                }

                            }
                            break;

                    }
                    //cboStatisticOzone.Items.Add("Mean");
                    // cboStatisticOzone.Items.Add("Maximum");
                    var query = dicOzoneModel.Where(p => lstSurround.Contains(p.Key)).ToList();
                    int iQueryCount = query.Count;
                    switch (ozoneAnalysisConfiguration.dataInputO.temporalAdjustmentType)
                    {
                        case "Mean":
                            #region mean
                            if (query.Count() > 0)
                            {
                                //---------------------求每天的最大值--得到一个新的OzoneModel---重新算ppb等---------And future!!!
                                List<double> lstOzoneTemp = new List<double>();

                                OzoneModel omTemp = new OzoneModel()
                                {
                                    id = k.Value.id,
                                    lat = Convert.ToSingle(k.Value.lat),
                                    longitude = Convert.ToSingle(k.Value.longitude),

                                };
                                Dictionary<string, float[]> dicOmBaseTemp = new Dictionary<string, float[]>();// query.First().Value.lstOzone;
                                foreach (KeyValuePair<string, float[]> kIn in query.First().Value.lstOzone)
                                {
                                    dicOmBaseTemp.Add(kIn.Key, new float[] { kIn.Value[0], kIn.Value[1] });
                                }
                                //Dictionary<string, float> dicOmForcastTemp = query.First().Value.lstOzoneForecast;
                                List<string> lstDicOmBaseTempKeys = dicOmBaseTemp.Keys.ToList();
                                //List<string> lstDicOmForcastTempKeys = dicOmForcastTemp.Keys.ToList();
                                // foreach (KeyValuePair<string, OzoneModel> kin in query)
                                for (int iKin = 1; iKin < query.Count(); iKin++)
                                {
                                    KeyValuePair<string, OzoneModel> kin = query.ToArray()[iKin];
                                    foreach (KeyValuePair<string, float[]> kBase in kin.Value.lstOzone)
                                    {

                                        dicOmBaseTemp[kBase.Key][0] += kBase.Value[0];
                                        dicOmBaseTemp[kBase.Key][1] += kBase.Value[1];

                                    }
                                    //foreach (KeyValuePair<string, float> kBase in kin.Value.lstOzoneForecast)
                                    //{

                                    //    dicOmForcastTemp[kBase.Key] += kBase.Value;


                                    //}
                                }

                                foreach (string s in lstDicOmBaseTempKeys)
                                {

                                    dicOmBaseTemp[s][0] = dicOmBaseTemp[s][0] / iQueryCount;
                                    dicOmBaseTemp[s][1] = dicOmBaseTemp[s][1] / iQueryCount;

                                }

                                //foreach (string s in lstDicOmForcastTempKeys)
                                //{

                                //    dicOmForcastTemp[s] = dicOmForcastTemp[s] / iQueryCount;


                                //}
                                omTemp.lstOzone = dicOmBaseTemp;
                                //omTemp.lstOzoneForecast = dicOmForcastTemp;
                                getThresholdsOfOzoneModel(omTemp, ozoneAnalysisConfiguration, false);
                                omTemp.lstOzone.Clear();
                                //omTemp.lstOzoneForecast.Clear();
                                OzoneMonitorControl omControl = new OzoneMonitorControl()
                                {
                                    id = k.Value.id,
                                    lat = k.Value.lat,
                                    longitude = k.Value.longitude,
                                    rrf = omTemp.rrf,
                                    days = omTemp.days,
                                    lim = omTemp.lim,
                                    ppb = omTemp.ppb,
                                    ozonebase = k.Value.ozone,
                                    ozonecontrol = k.Value.ozone < 0 ? -9 : omTemp.rrf == -9 ? -9 : CommonClass.ToFixed(k.Value.ozone * omTemp.rrf, 1),//omTemp.rrf == -9 ? -9 : CommonClass.ToFixed(k.Value.ozone * omTemp.rrf, 1),// Convert.ToInt16(k.Value.ozone*om.rrf*10)/10,
                                    county = k.Value.county,
                                    referencecell = dicMonitorInModel[k.Key],// om.id,
                                    state = k.Value.state
                                };
                                dicOzoneMonitorControl.Add(k.Value.id, omControl);
                                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doMaxDesignValuePeriods)
                                {
                                    KeyValuePair<string, double> ozonebMax = k.Value.dicOzone.Where(q => lstMonitorYear.Contains(q.Key)).ToDictionary(q => q.Key, q => q.Value).OrderByDescending(q => q.Value).First();//.Select(q => q.Value).ToList().Max();
                                    OzoneMonitorControlMax omControlMax = new OzoneMonitorControlMax()
                                    {
                                        id = k.Value.id,
                                        lat = k.Value.lat,
                                        longitude = k.Value.longitude,
                                        rrf = omTemp.rrf,
                                        days = omTemp.days,
                                        lim = omTemp.lim,
                                        ppb = omTemp.ppb,
                                        ozonebase = ozonebMax.Value,
                                        ozonecontrol = ozonebMax.Value < 0 ? -9 : omTemp.rrf == -9 ? -9 : CommonClass.ToFixed(ozonebMax.Value * omTemp.rrf, 1),// Convert.ToInt16(k.Value.ozone*om.rrf*10)/10,
                                        county = k.Value.county,
                                        referencecell = dicMonitorInModel[k.Key],// om.id,
                                        state = k.Value.state,
                                        data = ozonebMax.Key
                                    };
                                    dicOzoneMonitorControlMax.Add(k.Value.id, omControlMax);
                                }
                                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doDesignValuePeriods)
                                {
                                    //----------存三个!
                                    //if (ozoneAnalysisConfiguration.filteringInterpolationO.requiredDVPeriods == "None selected")
                                    //{
                                    //            ozoneAnalysisConfiguration.filteringInterpolationO.endYear.Substring(0, 4) ||
                                    //kin.Key == (Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.endYear.Substring(0, 4)) + 1).ToString() ||
                                    //kin.Key == (Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.endYear.Substring(0, 4)) + 2).ToString()))
                                    for (int iPeriod = 0; iPeriod < lstMonitorYear.Count; iPeriod++)
                                    {
                                        OzoneMonitorControl omControlPeriod1 = new OzoneMonitorControl()
                                        {
                                            id = k.Value.id,
                                            lat = k.Value.lat,
                                            longitude = k.Value.longitude,
                                            rrf = omTemp.rrf,
                                            days = omTemp.days,
                                            lim = omTemp.lim,
                                            ppb = omTemp.ppb,
                                            ozonebase = k.Value.dicOzone[lstMonitorYear[iPeriod]],//(Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(0, 4)) + iPeriod).ToString()],
                                            ozonecontrol = omTemp.rrf == -9 ? -9 : CommonClass.ToFixed(k.Value.dicOzone[lstMonitorYear[iPeriod]] * omTemp.rrf, 1),//[(Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(0, 4)) + iPeriod).ToString()] * omTemp.rrf, 1),// Convert.ToInt16(k.Value.ozone*om.rrf*10)/10,
                                            county = k.Value.county,
                                            referencecell = dicMonitorInModel[k.Key],// om.id,
                                            state = k.Value.state
                                        };
                                        if (omControlPeriod1.ozonebase == -9 || omControlPeriod1.ozonebase == -7)
                                        {
                                            omControlPeriod1.ozonebase = -7;
                                            omControlPeriod1.ozonecontrol = -9;
                                        }
                                        lstDicOzoneMonitorControlPeriod[iPeriod].Add(k.Value.id, omControlPeriod1);
                                    }
                                    //}
                                    //else
                                    //{
                                    //    for (int iPeriod = 0; iPeriod < 3; iPeriod++)
                                    //    {
                                    //        OzoneMonitorControl omControlPeriod1 = new OzoneMonitorControl()
                                    //        {
                                    //            id = k.Value.id,
                                    //            lat = k.Value.lat,
                                    //            longitude = k.Value.longitude,
                                    //            rrf = omTemp.rrf,
                                    //            days = omTemp.days,
                                    //            lim = omTemp.lim,
                                    //            ppb = omTemp.ppb,
                                    //            ozonebase = k.Value.dicOzone[(Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.requiredDVPeriods.Substring(0, 4)) + iPeriod).ToString()],
                                    //            ozonecontrol = omTemp.rrf == -9 ? -9 : CommonClass.ToFixed(k.Value.dicOzone[(Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.requiredDVPeriods.Substring(0, 4)) + iPeriod).ToString()] * omTemp.rrf, 1),// Convert.ToInt16(k.Value.ozone*om.rrf*10)/10,
                                    //            county = k.Value.county,
                                    //            referencecell = dicMonitorInModel[k.Key],// om.id,
                                    //            state = k.Value.state
                                    //        };
                                    //        if (omControlPeriod1.ozonebase == -9 || omControlPeriod1.ozonebase == -7)
                                    //        {
                                    //            omControlPeriod1.ozonebase = -7;
                                    //            omControlPeriod1.ozonecontrol = -9;
                                    //        }
                                    //        lstDicOzoneMonitorControlPeriod[iPeriod].Add(k.Value.id, omControlPeriod1);
                                    //    }
                                    //}
                                }
                            }
                            #endregion
                            break;
                        case "Maximum"://首先得到周围最大的，然后得到相应forecast的，然后计算rrf等等。应用到monitor计算出MonitorControl
                            #region maximum
                            if (query.Count() > 0)
                            {
                                //---------------------求每天的最大值--得到一个新的OzoneModel---重新算ppb等---------And future!!!
                                List<double> lstOzoneTemp = new List<double>();
                                OzoneModel omTemp = new OzoneModel()
                                {
                                    id = k.Value.id,
                                    lat = Convert.ToSingle(k.Value.lat),
                                    longitude = Convert.ToSingle(k.Value.longitude),

                                };
                                Dictionary<string, float[]> dicOmBaseTemp = new Dictionary<string, float[]>();// query.First().Value.lstOzone;
                                //Dictionary<string, float> dicOmForcastTemp = new Dictionary<string, float>();//query.First().Value.lstOzoneForecast;

                                foreach (KeyValuePair<string, OzoneModel> kin in query)
                                {
                                    foreach (KeyValuePair<string, float[]> kBase in kin.Value.lstOzone)
                                    {
                                        if (!dicOmBaseTemp.ContainsKey(kBase.Key))
                                        {
                                            dicOmBaseTemp.Add(kBase.Key, new float[] { kBase.Value[0], kBase.Value[1] });
                                        }
                                        else if (dicOmBaseTemp[kBase.Key][0] < kBase.Value[0])
                                        {
                                            dicOmBaseTemp[kBase.Key][0] = kBase.Value[0];

                                        }
                                    }
                                    foreach (KeyValuePair<string, float[]> kBase in kin.Value.lstOzone)
                                    {
                                        if (!dicOmBaseTemp.ContainsKey(kBase.Key))
                                        {
                                            dicOmBaseTemp.Add(kBase.Key, new float[] { kBase.Value[0], kBase.Value[1] });
                                        }
                                        else if (dicOmBaseTemp[kBase.Key][1] < kBase.Value[1])
                                        {
                                            dicOmBaseTemp[kBase.Key][1] = kBase.Value[1];

                                        }
                                    }
                                    //foreach (KeyValuePair<string, float> kBase in kin.Value.lstOzoneForecast)
                                    //{
                                    //    if (!dicOmForcastTemp.ContainsKey(kBase.Key))
                                    //    {
                                    //        dicOmForcastTemp.Add(kBase.Key, kBase.Value);
                                    //    }
                                    //    else if (dicOmForcastTemp[kBase.Key] < kBase.Value)
                                    //    {
                                    //        dicOmForcastTemp[kBase.Key] = kBase.Value;

                                    //    }
                                    //}
                                }
                                omTemp.lstOzone = dicOmBaseTemp;
                                //omTemp.lstOzoneForecast = dicOmForcastTemp;
                                if (k.Value.id == "0120813002" || k.Value.id == "120813002"
                                    || k.Value.id == "120813002" || k.Value.id == "0120813002"//120571035  291650023
                                    || k.Value.id == "291650023" || k.Value.id == "0291650023"
                                    || k.Value.id == "390490081" || k.Value.id == "0390490081"
                                    )
                                {
                                    string s = "";
                                }

                                getThresholdsOfOzoneModel(omTemp, ozoneAnalysisConfiguration, false);
                                omTemp.lstOzone.Clear();
                                //omTemp.lstOzoneForecast.Clear();
                                OzoneMonitorControl omControl = new OzoneMonitorControl()
                                {
                                    id = k.Value.id,
                                    lat = k.Value.lat,
                                    longitude = k.Value.longitude,
                                    rrf = omTemp.rrf,
                                    days = omTemp.days,
                                    lim = omTemp.lim,
                                    ppb = omTemp.ppb,
                                    ozonebase = k.Value.ozone,
                                    ozonecontrol = k.Value.ozone < 0 ? -9 : omTemp.rrf == -9 ? -9 : CommonClass.ToFixed(k.Value.ozone * omTemp.rrf, 1),// Convert.ToInt16(k.Value.ozone*om.rrf*10)/10,
                                    county = k.Value.county,
                                    referencecell = dicMonitorInModel[k.Key],// om.id,
                                    state = k.Value.state
                                };
                                dicOzoneMonitorControl.Add(k.Value.id, omControl);
                                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doMaxDesignValuePeriods)
                                {
                                    KeyValuePair<string, double> ozonebMax = k.Value.dicOzone.Where(q => lstMonitorYear.Contains(q.Key)).ToDictionary(q => q.Key, q => q.Value).OrderByDescending(q => q.Value).First();//.Select(q => q.Value).ToList().Max();
                                    OzoneMonitorControlMax omControlMax = new OzoneMonitorControlMax()
                                    {
                                        id = k.Value.id,
                                        lat = k.Value.lat,
                                        longitude = k.Value.longitude,
                                        rrf = omTemp.rrf,
                                        days = omTemp.days,
                                        lim = omTemp.lim,
                                        ppb = omTemp.ppb,
                                        ozonebase = ozonebMax.Value,
                                        ozonecontrol = ozonebMax.Value < 0 ? -9 : omTemp.rrf == -9 ? -9 : CommonClass.ToFixed(ozonebMax.Value * omTemp.rrf, 1),// Convert.ToInt16(k.Value.ozone*om.rrf*10)/10,
                                        county = k.Value.county,
                                        referencecell = dicMonitorInModel[k.Key],// om.id,
                                        state = k.Value.state,
                                        data = ozonebMax.Key
                                    };
                                    dicOzoneMonitorControlMax.Add(k.Value.id, omControlMax);
                                }
                                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doDesignValuePeriods)
                                {
                                    //----------存三个!
                                    //if (ozoneAnalysisConfiguration.filteringInterpolationO.requiredDVPeriods == "None Selected")
                                    //{
                                    //            ozoneAnalysisConfiguration.filteringInterpolationO.endYear.Substring(0, 4) ||
                                    //kin.Key == (Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.endYear.Substring(0, 4)) + 1).ToString() ||
                                    //kin.Key == (Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.endYear.Substring(0, 4)) + 2).ToString()))
                                    for (int iPeriod = 0; iPeriod < lstMonitorYear.Count; iPeriod++)
                                    {
                                        OzoneMonitorControl omControlPeriod1 = new OzoneMonitorControl()
                                        {
                                            id = k.Value.id,
                                            lat = k.Value.lat,
                                            longitude = k.Value.longitude,
                                            rrf = omTemp.rrf,
                                            days = omTemp.days,
                                            lim = omTemp.lim,
                                            ppb = omTemp.ppb,
                                            ozonebase = k.Value.dicOzone[lstMonitorYear[iPeriod]],//(Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(0, 4)) + iPeriod).ToString()],
                                            ozonecontrol = omTemp.rrf == -9 ? -9 : CommonClass.ToFixed(k.Value.dicOzone[lstMonitorYear[iPeriod]] * omTemp.rrf, 1),//[(Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(0, 4)) + iPeriod).ToString()] * omTemp.rrf, 1),// Convert.ToInt16(k.Value.ozone*om.rrf*10)/10,
                                            county = k.Value.county,
                                            referencecell = dicMonitorInModel[k.Key],// om.id,
                                            state = k.Value.state
                                        };
                                        if (omControlPeriod1.ozonebase == -9 || omControlPeriod1.ozonebase == -7)
                                        {
                                            omControlPeriod1.ozonebase = -7;
                                            omControlPeriod1.ozonecontrol = -9;
                                        }
                                        lstDicOzoneMonitorControlPeriod[iPeriod].Add(k.Value.id, omControlPeriod1);
                                    }
                                    //}
                                    //else
                                    //{
                                    //    for (int iPeriod = 0; iPeriod < 3; iPeriod++)
                                    //    {
                                    //        OzoneMonitorControl omControlPeriod1 = new OzoneMonitorControl()
                                    //        {
                                    //            id = k.Value.id,
                                    //            lat = k.Value.lat,
                                    //            longitude = k.Value.longitude,
                                    //            rrf = omTemp.rrf,
                                    //            days = omTemp.days,
                                    //            lim = omTemp.lim,
                                    //            ppb = omTemp.ppb,
                                    //            ozonebase = k.Value.dicOzone[(Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.requiredDVPeriods.Substring(0, 4)) + iPeriod).ToString()],
                                    //            ozonecontrol = omTemp.rrf == -9 ? -9 : CommonClass.ToFixed(k.Value.dicOzone[(Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.requiredDVPeriods.Substring(0, 4)) + iPeriod).ToString()] * omTemp.rrf, 1),// Convert.ToInt16(k.Value.ozone*om.rrf*10)/10,
                                    //            county = k.Value.county,
                                    //            referencecell = dicMonitorInModel[k.Key],// om.id,
                                    //            state = k.Value.state
                                    //        };
                                    //        if (omControlPeriod1.ozonebase == -9 || omControlPeriod1.ozonebase == -7)
                                    //        {
                                    //            omControlPeriod1.ozonebase = -7;
                                    //            omControlPeriod1.ozonecontrol = -9;
                                    //        }
                                    //        lstDicOzoneMonitorControlPeriod[iPeriod].Add(k.Value.id, omControlPeriod1);
                                    //    }
                                    //}
                                }
                            }
                            #endregion
                            break;
                        case "Maximum-paired in space"://The maximum value should be based on the baseline file maximum grid cell, and the RRF should be calculated at the same grid cell in the future (paired in space)
                            #region maximum-paired in space
                            if (query.Count() > 0)
                            {
                                //---------------------先得到baseline的每日最大值，根据base的id得到对应future的model，在计算RRF
                                List<double> lstOzoneTemp = new List<double>();
                                OzoneModel omTemp = new OzoneModel()
                                {
                                    id = k.Value.id,
                                    lat = Convert.ToSingle(k.Value.lat),
                                    longitude = Convert.ToSingle(k.Value.longitude),

                                };
                                Dictionary<string, float[]> dicOmBaseTemp = new Dictionary<string, float[]>();// query.First().Value.lstOzone;


                                foreach (KeyValuePair<string, OzoneModel> kin in query)
                                {
                                    foreach (KeyValuePair<string, float[]> kBase in kin.Value.lstOzone)
                                    {
                                        if (!dicOmBaseTemp.ContainsKey(kBase.Key))
                                        {
                                            dicOmBaseTemp.Add(kBase.Key, new float[] { kBase.Value[0], kBase.Value[1] });
                                        }
                                        else if (dicOmBaseTemp[kBase.Key][0] < kBase.Value[0])
                                        {
                                            dicOmBaseTemp[kBase.Key] = kBase.Value;
                                        }
                                    }

                                }
                                omTemp.lstOzone = dicOmBaseTemp;
                                //omTemp.lstOzoneForecast = dicOmForcastTemp;
                                if (k.Value.id == "0120813002" || k.Value.id == "120813002"
                                    || k.Value.id == "120813002" || k.Value.id == "0120813002"//120571035  291650023
                                    || k.Value.id == "291650023" || k.Value.id == "0291650023"
                                    || k.Value.id == "390490081" || k.Value.id == "0390490081"
                                    )
                                {
                                    string s = "";
                                }

                                getThresholdsOfOzoneModel(omTemp, ozoneAnalysisConfiguration, false);
                                omTemp.lstOzone.Clear();
                                //omTemp.lstOzoneForecast.Clear();
                                OzoneMonitorControl omControl = new OzoneMonitorControl()
                                {
                                    id = k.Value.id,
                                    lat = k.Value.lat,
                                    longitude = k.Value.longitude,
                                    rrf = omTemp.rrf,
                                    days = omTemp.days,
                                    lim = omTemp.lim,
                                    ppb = omTemp.ppb,
                                    ozonebase = k.Value.ozone,
                                    ozonecontrol = k.Value.ozone < 0 ? -9 : omTemp.rrf == -9 ? -9 : CommonClass.ToFixed(k.Value.ozone * omTemp.rrf, 1),// Convert.ToInt16(k.Value.ozone*om.rrf*10)/10,
                                    county = k.Value.county,
                                    referencecell = dicMonitorInModel[k.Key],// om.id,
                                    state = k.Value.state
                                };
                                dicOzoneMonitorControl.Add(k.Value.id, omControl);
                                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doMaxDesignValuePeriods)
                                {
                                    KeyValuePair<string, double> ozonebMax = k.Value.dicOzone.Where(q => lstMonitorYear.Contains(q.Key)).ToDictionary(q => q.Key, q => q.Value).OrderByDescending(q => q.Value).First();//.Select(q => q.Value).ToList().Max();
                                    OzoneMonitorControlMax omControlMax = new OzoneMonitorControlMax()
                                    {
                                        id = k.Value.id,
                                        lat = k.Value.lat,
                                        longitude = k.Value.longitude,
                                        rrf = omTemp.rrf,
                                        days = omTemp.days,
                                        lim = omTemp.lim,
                                        ppb = omTemp.ppb,
                                        ozonebase = ozonebMax.Value,
                                        ozonecontrol = ozonebMax.Value < 0 ? -9 : omTemp.rrf == -9 ? -9 : CommonClass.ToFixed(ozonebMax.Value * omTemp.rrf, 1),// Convert.ToInt16(k.Value.ozone*om.rrf*10)/10,
                                        county = k.Value.county,
                                        referencecell = dicMonitorInModel[k.Key],// om.id,
                                        state = k.Value.state,
                                        data = ozonebMax.Key
                                    };
                                    dicOzoneMonitorControlMax.Add(k.Value.id, omControlMax);
                                }
                                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doDesignValuePeriods)
                                {

                                    for (int iPeriod = 0; iPeriod < lstMonitorYear.Count; iPeriod++)
                                    {
                                        OzoneMonitorControl omControlPeriod1 = new OzoneMonitorControl()
                                        {
                                            id = k.Value.id,
                                            lat = k.Value.lat,
                                            longitude = k.Value.longitude,
                                            rrf = omTemp.rrf,
                                            days = omTemp.days,
                                            lim = omTemp.lim,
                                            ppb = omTemp.ppb,
                                            ozonebase = k.Value.dicOzone[lstMonitorYear[iPeriod]],// (Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(0, 4)) + iPeriod).ToString()],
                                            ozonecontrol = omTemp.rrf == -9 ? -9 : CommonClass.ToFixed(k.Value.dicOzone[lstMonitorYear[iPeriod]] * omTemp.rrf, 1),//[(Convert.ToInt32(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(0, 4)) + iPeriod).ToString()] * omTemp.rrf, 1),// Convert.ToInt16(k.Value.ozone*om.rrf*10)/10,
                                            county = k.Value.county,
                                            referencecell = dicMonitorInModel[k.Key],// om.id,
                                            state = k.Value.state
                                        };
                                        if (omControlPeriod1.ozonebase == -9 || omControlPeriod1.ozonebase == -7)
                                        {
                                            omControlPeriod1.ozonebase = -7;
                                            omControlPeriod1.ozonecontrol = -9;
                                        }
                                        lstDicOzoneMonitorControlPeriod[iPeriod].Add(k.Value.id, omControlPeriod1);
                                    }
                                }
                            }
                            #endregion
                            break;
                    }

                }

                if (!CommonClass.IsBatch)
                {
                    if (_resultFilePath == "" && _resultFilePath.Length == 0 || _resultFilePath != CommonClass.ResultFilePath + @"\Result\Output\" + ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName)
                        _resultFilePath = CommonClass.ResultFilePath + @"\Result\Output\" + ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName;
                }
                else
                {
                    if (_resultFilePath == "" && _resultFilePath.Length == 0 || _resultFilePath != CommonClass.ResultFilePath + @"\" + ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName)
                        _resultFilePath = CommonClass.ResultFilePath + @"\" + ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName;
                }
                if (!Directory.Exists(_resultFilePath))
                    System.IO.Directory.CreateDirectory(_resultFilePath);

                SaveDicOzoneMonitorControl(dicOzoneMonitorControl, baseScenario, lastYear, "");
                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doMaxDesignValuePeriods)
                {
                    SaveDicOzoneMonitorControlMax(dicOzoneMonitorControlMax, baseScenario, lastYear);
                    dicOzoneMonitorControlMax.Clear();
                }
                SaveDicOzoneMonitorControlCounty(dicOzoneMonitorControl, baseScenario, lastYear, "");
                //dicOzoneMonitorControl.Clear();
                GC.Collect();
                //CommonClass.CurrentProgressBar++;
                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doDesignValuePeriods)
                {
                    for (int iPeriod = 0; iPeriod < lstMonitorYear.Count; iPeriod++)
                    {
                        //SaveDicOzoneMonitorControl(lstDicOzoneMonitorControlPeriod[iPeriod], baseScenario, (Convert.ToInt32(lastYear) - 3 + iPeriod).ToString(), "Period " + (iPeriod + 1).ToString());
                        //SaveDicOzoneMonitorControlCounty(lstDicOzoneMonitorControlPeriod[iPeriod], baseScenario, (Convert.ToInt32(lastYear) - 3 + iPeriod).ToString(), "Period " + (iPeriod + 1).ToString());
                        SaveDicOzoneMonitorControl(lstDicOzoneMonitorControlPeriod[iPeriod], baseScenario, lastYear, "Period " + (iPeriod + 1).ToString());
                        SaveDicOzoneMonitorControlCounty(lstDicOzoneMonitorControlPeriod[iPeriod], baseScenario, lastYear, "Period " + (iPeriod + 1).ToString());

                    }
                }
                lstDicOzoneMonitorControlPeriod.Clear();
                GC.Collect();
                _endTime = DateTime.Now;
                CommonClass.TotalTime = Math.Round(_endTime.Subtract(_beginTime).TotalSeconds, 3);
                CommonClass.CurrentBaseScenario.log.lstLog.Add("Finish creating required averages: " + CommonClass.TotalTime + " s.");
                CommonClass.CurrentLog = "Finish creating required averages: " + CommonClass.TotalTime + " s.";
                #endregion
                #region clear lstOzone
                foreach (KeyValuePair<string, OzoneModel> k in dicOzoneModel)
                {
                    k.Value.lstOzone.Clear();
                }
                GC.Collect();
                #endregion
                #region VNA & downscaler added by Yangwenwei

                //----------求OzoneControl----------
                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimates || ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyVNA || ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyVNA
                    || ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimatesGradAdj || ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyEVNA || ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyEVNA
                    || ozoneAnalysisConfiguration.chooseDesiredOutputO.doDownscaler || ozoneAnalysisConfiguration.chooseDesiredOutputO.DSBaseOnly || ozoneAnalysisConfiguration.chooseDesiredOutputO.DSFutureOnly)
                {
                    _beginTime = DateTime.Now;

                    Dictionary<string, NeighborFileClass> dicNeighborFile = new Dictionary<string, NeighborFileClass>();
                    //-------------如果需要VNA求VNA------------------------------------------------
                    //-----------得到Neighbor --VNA---------
                    Dictionary<string, OzoneMonitorControl> dicOzoneMonitorLatLong = new Dictionary<string, OzoneMonitorControl>();
                    double iMinLong = 180, iMinLat = 180, iMaxLong = -180, iMaxLat = -180, dLong10 = 1, dLat10 = 1;
                    foreach (KeyValuePair<string, OzoneMonitorControl> kin in dicOzoneMonitorControl)
                    {
                        if (dicOzoneMonitor.ContainsKey(kin.Key) && !dicOzoneMonitorLatLong.ContainsKey(dicOzoneMonitor[kin.Key].longitudeLamber + "," + dicOzoneMonitor[kin.Key].latitudeLamber))
                        {
                            if (dicOzoneMonitor[kin.Key].ozone > 0)
                            {
                                dicOzoneMonitorLatLong.Add(dicOzoneMonitor[kin.Key].longitudeLamber + "," + dicOzoneMonitor[kin.Key].latitudeLamber, kin.Value);
                                if (kin.Value.longitude > iMaxLong) iMaxLong = kin.Value.longitude;
                                if (kin.Value.lat > iMaxLat) iMaxLat = kin.Value.lat;
                                if (kin.Value.longitude < iMinLong) iMinLong = kin.Value.longitude;
                                if (kin.Value.lat < iMinLat) iMinLat = kin.Value.lat;

                            }
                        }
                        else
                        {
                        }
                    }
                    dLong10 = (iMaxLong - iMinLong) / 10.00;
                    dLat10 = (iMaxLat - iMinLat) / 10.00;
                    List<OzoneModelOutput> lstOzoneModelOutput = new List<OzoneModelOutput>();

                    bool VNAorEVNA = (ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimates || ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyVNA || ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyVNA
                    || ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimatesGradAdj || ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyEVNA || ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyEVNA);

                    foreach (KeyValuePair<string, OzoneModel> k in dicOzoneModel)
                    {
                        if (k.Key.Replace("\"", "") == "6081" || k.Key.Replace("\"", "") == "06081")
                        {
                            string s = "";
                        }
                        List<double> fsInter = new List<double>();
                        fsInter.Add(k.Value.longitudeLamber);
                        fsInter.Add(k.Value.latitudeLamber);
                        OzoneModelOutput ozoneModelOutput = new OzoneModelOutput()
                        {
                            id = k.Value.id,
                            lat = k.Value.lat,
                            longitude = k.Value.longitude,
                            Date = lastYear,
                            days = k.Value.daysforSptailfield,
                            ppb = k.Value.ppbforSptailfield,
                            type = "",
                            rrf = k.Value.rrfforSptailfield,
                            bO3modelForSpatialField = k.Value.bO3forSptailfield,
                        };
                        #region VNA or eVNA begins here
                        if (VNAorEVNA)
                        {
                            //VNA简化算法求半径范围内的监测点做VNA ，一开始以5个经纬度来算一直达到10个为止
                            Dictionary<string, double> dicDistanceMonitor = new Dictionary<string, double>();

                            foreach (KeyValuePair<string, OzoneMonitorControl> kin in dicOzoneMonitorLatLong)
                            {
                                if (dicMonitorInModel.ContainsKey(kin.Value.id))
                                {
                                    dicDistanceMonitor.Add(kin.Value.id, (k.Value.longitude - kin.Value.longitude) * (k.Value.longitude - kin.Value.longitude) + (k.Value.lat - kin.Value.lat) * (k.Value.lat - kin.Value.lat));
                                }
                            }
                            List<KeyValuePair<string, double>> query = new List<KeyValuePair<string, double>>();
                            bool isSame = false;
                            if (dicOzoneMonitorLatLong.ContainsKey(k.Value.longitudeLamber + "," + k.Value.latitudeLamber)) isSame = true;
                            if (!isSame)
                            {
                                if (Math.Abs(k.Value.longitude - iMinLong) < dLong10 || Math.Abs(iMaxLong - k.Value.longitude) < dLong10
                                    || Math.Abs(k.Value.lat - iMinLat) < dLat10 || Math.Abs(iMaxLat - k.Value.lat) < dLat10)
                                {
                                    query = dicDistanceMonitor.Where(p => p.Value < 484).ToList();
                                }
                                else
                                {
                                    query = dicDistanceMonitor.Where(p => p.Value < 64).ToList();//.OrderBy(p=>p.Value).ToList().GetRange(0,idicMonitorValues).ToDictionary(p=>p.Key,p=>p.Value);// .Where(p => lstDouble.GetRange(0, idicMonitorValues).Contains(p.Value));
                                    int iDistanceForQuery = 1;
                                    while (query.Count < 20 && query.Count < dicDistanceMonitor.Count)
                                    {
                                        query = dicDistanceMonitor.Where(p => p.Value < 64 + iDistanceForQuery).ToList();
                                        iDistanceForQuery++;

                                    }
                                }

                                foreach (KeyValuePair<string, double> kin in query)
                                {
                                    if (dicOzoneMonitor.ContainsKey(kin.Key))
                                    {
                                        fsInter.Add(dicOzoneMonitor[kin.Key].longitudeLamber);
                                        fsInter.Add(dicOzoneMonitor[kin.Key].latitudeLamber);

                                    }
                                }
                            }
                            //----------------end VNA简化算法
                            double vnaSum = 0, evnaSum = 0, distanceSum = 0, distance = 0, distanceSumEvna = 0;
                            double vna = 0, evna = 0, vnaForcast = 0, evnaForcast = 0;
                            List<double> fsout = new List<double>();
                            if (!isSame)
                                CommonClass.VoronoiPoints(fsInter.ToArray(), ref fsout);//
                            else
                            {
                                fsout.Add(k.Value.longitudeLamber);
                                fsout.Add(k.Value.latitudeLamber);
                            }
                            //----------------根据得到的邻居计算数值----------------
                            List<string> fsoutString = new List<string>();
                            for (int ifsout = 0; ifsout < fsout.Count; ifsout++)
                            {
                                if (ifsout % 2 == 1)
                                {
                                    fsoutString.Add(fsout[ifsout - 1] + "," + fsout[ifsout]);
                                }
                            }
                            //-----------------加入对NeighborsFile的考虑需要导出NeighborsFile
                            dicNeighborFile.Add(k.Key, new NeighborFileClass()
                            {
                                id = k.Key,
                                monitorLat = k.Value.lat,
                                monitorLong = k.Value.longitude,
                                //quarter = 1,
                                dicNeighbors = new Dictionary<string, NeighborInfo>(),
                            });
                            //-------------------------------------------------------------
                            if (fsoutString.Count == 0) continue;
                            switch (ozoneAnalysisConfiguration.filteringInterpolationO.defaultInterpolationMethod)
                            {
                                case "Equal Weighting of Monitors"://不需要求距离直接平均

                                    #region "Equal Weighting of Monitors"                                   
                                    int n = 0;
                                    foreach (string s in fsoutString)
                                    {
                                        double d = CommonClass.getDistanceFrom2Point(k.Value.longitude, k.Value.lat, dicOzoneMonitorLatLong[s].longitude, dicOzoneMonitorLatLong[s].lat);
                                        if (ozoneAnalysisConfiguration.filteringInterpolationO.doCheckToSetMaxDistance && d > ozoneAnalysisConfiguration.filteringInterpolationO.maxDistance) continue;
                                        vnaSum += dicOzoneMonitorLatLong[s].ozonebase;
                                        if (k.Value.srf > 0 && dicOzoneModel[dicMonitorInModel[dicOzoneMonitorLatLong[s].id]].srf > 0)
                                        {
                                            evnaSum += dicOzoneMonitorLatLong[s].ozonebase * Math.Round(dicOzoneModel[dicMonitorInModel[dicOzoneMonitorLatLong[s].id]].srf, 1) / Math.Round(k.Value.srf, 1);
                                            n++;
                                        }
                                        dicNeighborFile[k.Key].dicNeighbors.Add(dicOzoneMonitorLatLong[s].id, new NeighborInfo()
                                    {
                                        neighbor = dicOzoneMonitorLatLong[s].id,
                                        neighbor_gridcell = dicMonitorInModel[dicOzoneMonitorLatLong[s].id],
                                        distance = d,
                                    });
                                    }
                                    try
                                    {
                                        if (vnaSum < 0 || Double.IsNaN(vnaSum))
                                            vna = -13;
                                        else
                                            vna = vnaSum / fsoutString.Count; //vna = Math.Round(vnaSum / fsoutString.Count, 1);
                                        if (evnaSum < 0 || Double.IsNaN(evnaSum) || n == 0)
                                            evna = -8;
                                        else
                                            evna = evnaSum / n; //evna = Math.Round(evnaSum / n, 1);
                                        if (k.Value.rrfforSptailfield < 0)
                                            vnaForcast = -9;
                                        else
                                            vnaForcast = vna * k.Value.rrfforSptailfield;// CommonClass.ToFixed(vna * k.Value.rrfforSptailfield, 1);
                                        if (evna < 0 || k.Value.rrfforSptailfield < 0 || Double.IsNaN(evna))
                                            evnaForcast = -9;
                                        else
                                            evnaForcast = evna * k.Value.rrfforSptailfield; CommonClass.ToFixed(evna * k.Value.rrfforSptailfield, 1);
                                    }
                                    catch
                                    {

                                    }
                                     #endregion "Equal Weighting of Monitors"

                                    break;
                                case "Inverse Distance Weights": //1/distance
                                    #region "Inverse Distance Weights"
                                  
                                    foreach (string s in fsoutString)
                                    {
                                        double d = CommonClass.getDistanceFrom2Point(k.Value.longitude, k.Value.lat, dicOzoneMonitorLatLong[s].longitude, dicOzoneMonitorLatLong[s].lat);
                                        if (ozoneAnalysisConfiguration.filteringInterpolationO.doCheckToSetMaxDistance && d > ozoneAnalysisConfiguration.filteringInterpolationO.maxDistance) continue;
                                        distance = d == 0 ? 1 : 1.0000 / d;
                                        //Console.WriteLine("distance=" + d + ",1/d=" + distance + ",monitor_A=" + dicOzoneMonitorLatLong[s].ozonebase + ",Model_E=" + Math.Round(k.Value.srf, 1) + ",model_A=" + Math.Round(dicOzoneModel[dicMonitorInModel[dicOzoneMonitorLatLong[s].id]].srf, 1));
                                        distanceSum += distance;
                                        vnaSum += dicOzoneMonitorLatLong[s].ozonebase * distance;
                                        dicNeighborFile[k.Key].dicNeighbors.Add(dicOzoneMonitorLatLong[s].id, new NeighborInfo()
                                        {
                                            neighbor = dicOzoneMonitorLatLong[s].id,
                                            neighbor_gridcell = dicMonitorInModel[dicOzoneMonitorLatLong[s].id],
                                            distance = d,
                                        });
                                        try
                                        {
                                            if (k.Value.srf > 0 && dicOzoneModel[dicMonitorInModel[dicOzoneMonitorLatLong[s].id]].srf > 0)
                                            {
                                                evnaSum += dicOzoneMonitorLatLong[s].ozonebase * distance * Math.Round(k.Value.srf, 1) / Math.Round(dicOzoneModel[dicMonitorInModel[dicOzoneMonitorLatLong[s].id]].srf, 1);
                                                distanceSumEvna += distance;
                                            }
                                        }
                                        catch
                                        {
                                        }
                                    }//foreach (string s in fsoutString)
                                    try
                                    {
                                        if (vnaSum < 0 || Double.IsNaN(vnaSum) || distanceSum == 0)
                                            vna = -13;
                                        else
                                            vna = vnaSum / distanceSum;//Math.Round(vnaSum / distanceSum, 1);
                                        if (evnaSum < 0 || Double.IsNaN(evnaSum) || distanceSumEvna == 0)
                                            evna = -8;
                                        else
                                            evna = evnaSum / distanceSumEvna; //Math.Round(evnaSum / distanceSumEvna, 1);
                                        if (k.Value.rrfforSptailfield < 0)
                                            vnaForcast = -9;
                                        else
                                            vnaForcast = vna * k.Value.rrfforSptailfield;//CommonClass.ToFixed(vna * k.Value.rrfforSptailfield, 1)

                                        if (evna < 0 || k.Value.rrfforSptailfield < 0 || Double.IsNaN(evna))
                                            evnaForcast = -9;
                                        else
                                            evnaForcast = evna * k.Value.rrfforSptailfield;//CommonClass.ToFixed(evna * k.Value.rrfforSptailfield, 1);
                                    }
                                    catch
                                    {
                                    }
                                      #endregion "Inverse Distance Weights"

                                    break;
                                case "Inverse Distance Squared Weights"://1/Math.Pow(distance,2)
                                    #region "Inverse Distance Squared Weights"                                   
                                    foreach (string s in fsoutString)
                                    {
                                        double d = CommonClass.getDistanceFrom2Point(k.Value.longitude, k.Value.lat, dicOzoneMonitorLatLong[s].longitude, dicOzoneMonitorLatLong[s].lat);
                                        if (ozoneAnalysisConfiguration.filteringInterpolationO.doCheckToSetMaxDistance && d > ozoneAnalysisConfiguration.filteringInterpolationO.maxDistance) continue;
                                        distance = d == 0 ? 1 : 1.0000 / Math.Pow(d, 2);
                                        distanceSum += distance;
                                        vnaSum += dicOzoneMonitorLatLong[s].ozonebase * distance;
                                        dicNeighborFile[k.Key].dicNeighbors.Add(dicOzoneMonitorLatLong[s].id, new NeighborInfo()
                                        {
                                            neighbor = dicOzoneMonitorLatLong[s].id,
                                            neighbor_gridcell = dicMonitorInModel[dicOzoneMonitorLatLong[s].id],
                                            distance = d,
                                        });
                                        try
                                        {
                                            if (k.Value.srf > 0 && dicOzoneModel[dicMonitorInModel[dicOzoneMonitorLatLong[s].id]].srf > 0)
                                            {
                                                evnaSum += dicOzoneMonitorLatLong[s].ozonebase * distance * Math.Round(k.Value.srf, 1) / Math.Round(dicOzoneModel[dicMonitorInModel[dicOzoneMonitorLatLong[s].id]].srf, 1);

                                                distanceSumEvna += distance;
                                            }
                                        }
                                        catch
                                        {
                                        }
                                    }
                                    try
                                    {
                                        if (vnaSum < 0 || Double.IsNaN(vnaSum) || distanceSum == 0)
                                            vna = -13;
                                        else
                                            vna = vnaSum / distanceSum;//Math.Round(vnaSum / distanceSum, 1);
                                        if (evnaSum < 0 || Double.IsNaN(evnaSum) || distanceSumEvna == 0)
                                            evna = -9;
                                        else
                                            evna = evnaSum / distanceSumEvna;//Math.Round(evnaSum / distanceSumEvna, 1)
                                        if (k.Value.rrfforSptailfield < 0)
                                            vnaForcast = -9;
                                        else
                                            vnaForcast = vna * k.Value.rrfforSptailfield;//CommonClass.ToFixed(vna * k.Value.rrfforSptailfield, 1);
                                        if (evna < 0 || k.Value.rrfforSptailfield < 0 || Double.IsNaN(evna))
                                            evnaForcast = -9;
                                        else
                                            evnaForcast = evna * k.Value.rrfforSptailfield;// CommonClass.ToFixed(evna * k.Value.rrfforSptailfield, 1);
                                    }
                                    catch
                                    {
                                    }
                                     #endregion "Inverse Distance Squared Weights"

                                    break;
                            }
                           

                            ozoneModelOutput.vna = Convert.ToSingle(vna);
                            ozoneModelOutput.evna = Convert.ToSingle(evna);
                            ozoneModelOutput.ga_conc = Convert.ToSingle(k.Value.srf);
                            ozoneModelOutput.vnaForcast = Convert.ToSingle(vnaForcast);
                            ozoneModelOutput.evnaForcast = Convert.ToSingle(evnaForcast);
                            ozoneModelOutput.referencecell = k.Value.id;
                        }
                        #endregion

                        lstOzoneModelOutput.Add(ozoneModelOutput);
                    }
                    _endTime = DateTime.Now;
                    CommonClass.TotalTime = Math.Round(_endTime.Subtract(_beginTime).TotalSeconds, 3);
                    CommonClass.CurrentBaseScenario.log.lstLog.Add("Finish interpolating spatial field: " + CommonClass.TotalTime + " s.");
                    CommonClass.CurrentLog = "Finish interpolating spatial field: " + CommonClass.TotalTime + " s.";

                    #region Downscaler begins here by Yangwenwei
                    List<DownscaleR.Ozone.OzoneModel> lstDSresult = new List<DownscaleR.Ozone.OzoneModel>();
                    if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doDownscaler || ozoneAnalysisConfiguration.chooseDesiredOutputO.DSBaseOnly || ozoneAnalysisConfiguration.chooseDesiredOutputO.DSFutureOnly)
                    //if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doDownscaler)//只计算dsBase或dsFuture需要进入ds模块就行运算。by sclong
                    {
                        _beginTime = DateTime.Now;
                        CommonClass.CurrentLog = "Start downscaler computation.";
                        CommonClass.CurrentBaseScenario.log.lstLog.Add(CommonClass.CurrentLog);


                        string[] lstModelID4DS = dicOzoneModel.Select(p => p.Value.id).ToArray();
                        double[] lstModelLat4DS = dicOzoneModel.Select(p => p.Value.lat).ToArray();
                        double[] lstModelLong4DS = dicOzoneModel.Select(p => p.Value.longitude).ToArray();
                        double[] lstModel4DS = dicOzoneModel.Select(p => Convert.ToDouble(p.Value.bO3forSptailfield)).ToArray();
                        Tuple<string[], double[], double[], double[]> _tupleModel4DS = new Tuple<string[], double[], double[], double[]>(
                            lstModelID4DS,
                            lstModelLat4DS,
                            lstModelLong4DS,
                            lstModel4DS
                            );
                        #region output model
                        //SaveDSModelData(dicOzoneModel);
                        #endregion

                        string[] lstMonitorID4DS = dicOzoneMonitorControl.Select(p => p.Value.id).ToArray();
                        double[] lstMonitorLat4DS = dicOzoneMonitorControl.Select(p => p.Value.lat).ToArray();
                        double[] lstMonitorLongl4DS = dicOzoneMonitorControl.Select(p => p.Value.longitude).ToArray();
                        double[] lstMonitor4DS = dicOzoneMonitorControl.Select(p => p.Value.ozonebase).ToArray();
                        Tuple<string[], double[], double[], double[]> _tupleMonitor4DS = new Tuple<string[], double[], double[], double[]>(
                            lstMonitorID4DS,
                            lstMonitorLat4DS,
                            lstMonitorLongl4DS,
                            lstMonitor4DS
                            );
                        #region output monitor
                        //SaveDSMonitorData(dicOzoneMonitorControl);
                        #endregion

                        DownscaleR.CommonSettings common = new DownscaleR.CommonSettings();
                        common.Burn = ozoneAnalysisConfiguration.chooseDesiredOutputO.DSBurn;
                        common.Cmaqres = ozoneAnalysisConfiguration.chooseDesiredOutputO.DSCmaqres;
                        common.Thin = ozoneAnalysisConfiguration.chooseDesiredOutputO.DSThin;
                        common.Numit = ozoneAnalysisConfiguration.chooseDesiredOutputO.DSNumit;

                        //DateTime start = DateTime.Now;

                        DownscaleR.Ozone.OzoneAnalysis analysis = new DownscaleR.Ozone.OzoneAnalysis(common, _tupleMonitor4DS, _tupleModel4DS);
                        analysis.Start();
                        // 获取结果
                        //analysis.MCMCOutputData //蒙特卡洛输出结果
                        lstDSresult = analysis.ResultOutputData;// 预测值

                        //DateTime end = DateTime.Now;
                        _endTime = DateTime.Now;

                        CommonClass.TotalTime = Math.Round(_endTime.Subtract(_beginTime).TotalSeconds, 3);
                        CommonClass.CurrentBaseScenario.log.lstLog.Add("Finish downscalser computation in " + CommonClass.TotalTime + " s.");
                        CommonClass.CurrentLog = "Finish downscalser computation in " + CommonClass.TotalTime + " s.";
                    }
                    #endregion

                    SaveLstOzoneModelOutput(lstOzoneModelOutput, baseScenario, lastYear, lstDSresult);

                    #region BenMAP ready Spatial Field


                    #region output option
                    bool vnab, vnaf, evnab, evnaf, dsb, dsf;
                    vnab = false;
                    vnaf = false;
                    evnab = false;
                    evnaf = false;
                    dsb = false;
                    dsf = false;
                    //VNA---output option----
                    if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimates || ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyVNA)
                    {
                        vnab = true;
                        vnaf = true;
                    }
                    if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyVNA)
                    {
                        vnab = true;
                    }
                    //eVNA----output option-----------
                    if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimatesGradAdj || ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyEVNA)
                    {
                        evnab = true;
                        evnaf = true;
                    }
                    if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyEVNA)
                    {
                        evnab = true;
                    }
                    //DS----output option-----------
                    if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doDownscaler || ozoneAnalysisConfiguration.chooseDesiredOutputO.DSFutureOnly)
                    {
                        dsb = true;
                        dsf = true;
                    }
                    if (ozoneAnalysisConfiguration.chooseDesiredOutputO.DSBaseOnly)
                    {
                        dsb = true;
                    }
                    #endregion


                    if (vnab || vnaf || evnab || evnaf || dsb || dsf)
                    {
                        Dictionary<double[], int[]> dic = new Dictionary<double[], int[]>();
                        IFeatureSet ifs = FeatureSet.Open(Application.StartupPath + @"\Data\ShapeFiles\CMAQ_12km_Nation.shp");
                        if (!ifs.AttributesPopulated) ifs.FillAttributes();
                        //change projection
                        ifs.Projection = DotSpatial.Projections.KnownCoordinateSystems.Geographic.World.WGS1984;
                        ifs.Reproject(DotSpatial.Projections.ProjectionInfo.FromProj4String(CommonClass.projUSACMAQ));
                        Dictionary<string, int[]> dicColRow = new Dictionary<string, int[]>();

                        foreach (IFeature f in ifs.Features)
                        {
                            dic.Add(new double[2] { f.Centroid().Coordinates.First().X / 100.0, f.Centroid().Coordinates.First().Y / 100.0 }, new int[2] { Convert.ToInt16(f.DataRow["COL"]), Convert.ToInt16(f.DataRow["ROW"]) });
                        }

                        foreach (var kv in dicOzoneModel)
                        {
                            var q = dic.Where(p => Math.Abs(kv.Value.longitudeLamber - p.Key[0]) <= 60 && Math.Abs(kv.Value.latitudeLamber - p.Key[1]) <= 60).ToList();
                            if (q.Count >= 0)
                            {
                                var v = q.OrderBy(p => Math.Pow(kv.Value.longitudeLamber - p.Key[0], 2) + Math.Pow(kv.Value.latitudeLamber - p.Key[1], 2)).First();
                                dicColRow.Add(kv.Value.id, new int[2] { v.Value[0], v.Value[1] });
                            }
                            else
                            {
                                var v = dic.OrderBy(p => Math.Pow(kv.Value.longitudeLamber - p.Key[0], 2) + Math.Pow(kv.Value.latitudeLamber - p.Key[1], 2)).ToList().First();
                                dicColRow.Add(kv.Value.id, new int[2] { v.Value[0], v.Value[1] });
                            }
                        }



                        if (vnab || vnaf)
                        {
                            SaveOzoneSpatialFieldForBenMAP(baseScenario, lstOzoneModelOutput, dicColRow, vnab, vnaf);
                        }
                        if (evnab || evnaf)
                        {
                            SaveOzoneSpatialFieldGradAdjForBenMAP(baseScenario, lstOzoneModelOutput, dicColRow, evnab, evnaf);
                        }
                        if (dsb || dsf)
                        {
                            SaveOzoneSpatialFieldDSForBenMAP(baseScenario, lstOzoneModelOutput, dicColRow, lstDSresult, dsb, dsf);
                        }
                    }
                    #endregion

                    lstOzoneModelOutput.Clear();
                    lstDSresult.Clear();
                    GC.Collect();
                    if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doNeighborFileSpatial)
                    {
                        SaveOzoneNeighborFileSpatialField(CommonClass.CurrentBaseScenario, dicNeighborFile);
                    }
                    dicNeighborFile.Clear();
                    GC.Collect();
                }
                #endregion
                //_endTime = DateTime.Now;
                //CommonClass.TotalTime = Math.Round(_endTime.Subtract(_beginTime).TotalSeconds, 3);
                //CommonClass.CurrentBaseScenario.log.lstLog.Add("Finish interpolating spatial field: " + CommonClass.TotalTime + " s.");
                //CommonClass.CurrentLog = "Finish interpolating spatial field: " + CommonClass.TotalTime + " s.";
                //CommonClass.CurrentProgressBar++;
                //------------------

                //调整结果文件排序
                List<BaseOutput> lstNew = new List<BaseOutput>();
                List<BaseOutput> bo = new List<BaseOutput>();

                string scenarioName = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " ";
                bo = baseScenario.lstOutput.Where(q => q.outputName.Substring(scenarioName.Length, q.outputName.Length - scenarioName.Length).Contains("- Ozone Monitors -- monitor data, temporally adjusted ")).ToList();
                if (bo.Count > 0) lstNew.Add(bo.First());
                bo = baseScenario.lstOutput.Where(q => q.outputName.Substring(scenarioName.Length, q.outputName.Length - scenarioName.Length).Contains("- Ozone Monitors -- county high monitoring sites, temporally adjusted ")).ToList();
                if (bo.Count > 0) lstNew.Add(bo.First());
                bo = baseScenario.lstOutput.Where(q => q.outputName.Substring(scenarioName.Length, q.outputName.Length - scenarioName.Length).Contains("- Ozone Monitors_Max -- temporally adjusted")).ToList();
                if (bo.Count > 0) lstNew.Add(bo.First());
                bo = baseScenario.lstOutput.Where(q => q.outputName.Substring(scenarioName.Length, q.outputName.Length - scenarioName.Length).Contains("- Spatial Field -- interpolated monitor data, temporally adjusted; gradient-adjusted monitor data, ")).ToList();
                if (bo.Count > 0) lstNew.Add(bo.First());
                bo = baseScenario.lstOutput.Where(q => q.outputName.Substring(scenarioName.Length, q.outputName.Length - scenarioName.Length).Contains("- Base & Future Model Data - used average")).ToList();
                if (bo.Count > 0) lstNew.Add(bo.First());
                bo = baseScenario.lstOutput.Where(q => q.outputName.Substring(scenarioName.Length, q.outputName.Length - scenarioName.Length).Contains("BenMAP-ready O3 Spatial Field Base (VNA)")).ToList();
                if (bo.Count > 0) lstNew.Add(bo.First());
                bo = baseScenario.lstOutput.Where(q => q.outputName.Substring(scenarioName.Length, q.outputName.Length - scenarioName.Length).Contains("BenMAP-ready O3 Spatial Field Future (VNA)")).ToList();
                if (bo.Count > 0) lstNew.Add(bo.First());
                bo = baseScenario.lstOutput.Where(q => q.outputName.Substring(scenarioName.Length, q.outputName.Length - scenarioName.Length).Contains("BenMAP-ready O3 Spatial Field Base (eVNA)")).ToList();
                if (bo.Count > 0) lstNew.Add(bo.First());
                bo = baseScenario.lstOutput.Where(q => q.outputName.Substring(scenarioName.Length, q.outputName.Length - scenarioName.Length).Contains("BenMAP-ready O3 Spatial Field Future (eVNA)")).ToList();
                if (bo.Count > 0) lstNew.Add(bo.First());
                bo = baseScenario.lstOutput.Where(q => q.outputName.Substring(scenarioName.Length, q.outputName.Length - scenarioName.Length).Contains("BenMAP-ready O3 Spatial Field Base (Downscaler)")).ToList();
                if (bo.Count > 0) lstNew.Add(bo.First());
                bo = baseScenario.lstOutput.Where(q => q.outputName.Substring(scenarioName.Length, q.outputName.Length - scenarioName.Length).Contains("BenMAP-ready O3 Spatial Field Future (Downscaler)")).ToList();
                if (bo.Count > 0) lstNew.Add(bo.First());
                baseScenario.lstOutput = lstNew;

                //if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doQuarterlyModelData)
                //{
                //    BaseOutput bo = CommonClass.CurrentBaseScenario.lstOutput[0];
                //    CommonClass.CurrentBaseScenario.lstOutput.RemoveAt(0);
                //    CommonClass.CurrentBaseScenario.lstOutput.Add(bo);
                //}
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {

            }

        }

        public static void getThresholdsOfOzoneModel(OzoneModel ozoneModel, OzoneAnalysisConfiguration ozoneAnalysisConfiguration, bool IsSpatialField)
        {
            try
            {
                int firstDay = ozoneAnalysisConfiguration.rrfSpatialGradientO.subrangeFirstDay;
                int endDay = ozoneAnalysisConfiguration.rrfSpatialGradientO.subrangeLastDay;
                if (endDay > ozoneModel.lstOzone.Count())
                    endDay = ozoneModel.lstOzone.Count();
                int getDays = endDay - firstDay + 1;
                Dictionary<string, float[]> dicUsedinRRF = ozoneModel.lstOzone.OrderBy(q => q.Key).ToList().GetRange(firstDay - 1, getDays).OrderByDescending(p => p.Value[0]).ToDictionary(q => q.Key, q => q.Value);
                ozoneModel.lstOzone = ozoneModel.lstOzone.OrderByDescending(p => p.Value[0]).ToDictionary(p => p.Key, p => p.Value);
                float[] values = ozoneModel.lstOzone.Values.Select(p => p[0]).ToArray();
                if (values[0] == -9 || values[0] == -7)
                {
                    ozoneModel.ozone = -9;
                    ozoneModel.futureOzone = -9;
                    ozoneModel.bO3forSptailfield = -9;//added by Yangwenwei
                    if (IsSpatialField)
                    {
                        if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimatesGradAdj || ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyEVNA)
                        {
                            ozoneModel.ppb = -8;
                            ozoneModel.days = -8;
                            ozoneModel.rrf = -8;
                            ozoneModel.srf = -13;
                        }
                        else
                        {
                            if (ozoneAnalysisConfiguration.rrfSpatialGradientO.doBackstop)
                                ozoneModel.ppb = Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.backstopMinThresholdforSpatialField);//65;
                            else
                                ozoneModel.ppb = Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minAllowableThresholdValue);//70;
                            ozoneModel.days = 0;
                            ozoneModel.rrf = -9;
                            ozoneModel.srf = -9;
                        }
                    }
                    else
                    {
                        ozoneModel.ppb = Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minAllowableThresholdValue);//70;
                        ozoneModel.days = 0;
                        ozoneModel.rrf = -9;
                        ozoneModel.srf = -9;
                    }
                    //---------- -13?
                    return;
                }
                //------------求SRF-------根据StartDay,EndDay--------
                #region 求SRF,先根据StartDay,EndDay取值，然后再排序
                ozoneModel.srf = dicUsedinRRF.Select(p => p.Value[0]).ToList().GetRange(Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.SRF_StartValue) - 1,
                    Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.SRF_EndValue) - Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.SRF_StartValue) + 1).Average();
                //ozoneModel.srf = values.ToList().GetRange(Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.SRF_StartValue) - 1,
                //  Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.SRF_EndValue) - Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.SRF_StartValue) + 1).Average();//这里是先排序后取值，是错的计算过程。所以注释，sclong, 2017-02-17
                //Console.WriteLine("先取值：" + srf + "先排序：" + ozoneModel.srf);
                #endregion
              
           
               
                //------------求SRF-------根据StartDay,EndDay--------
                //ozoneModel.srf = Math.Round(values.ToList().GetRange(Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.SRF_StartValue) - 1,
                //    Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.SRF_EndValue) - Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.SRF_StartValue) + 1).Average(), 1);

                //select model days according to subrang first and last day
                values = dicUsedinRRF.Select(p => p.Value[0]).ToArray();
                int j = 0, iThresh = 0;
                if (ozoneAnalysisConfiguration.rrfSpatialGradientO.useInitialThreshold)
                {
                    while (j <= Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.initialThresholdValue) - Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minAllowableThresholdValue))
                    {
                        iThresh = 0;
                        while (iThresh < dicUsedinRRF.Count)//ozoneModel.lstOzone.Count)
                        {
                            if (values[iThresh] < Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.initialThresholdValue) - j) break;
                            iThresh++;
                        }
                        if (iThresh >= Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minNumofDaysAtorAboveThreshold)) break;
                        j++;

                    }
                    if (j > Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.initialThresholdValue) - Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minAllowableThresholdValue))
                        j = Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.initialThresholdValue) - Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minAllowableThresholdValue);

                    ozoneModel.ppb = Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.initialThresholdValue) - j;

                }
                else
                {
                    if (values[ozoneAnalysisConfiguration.rrfSpatialGradientO.topXDays - 1] > Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minAllowableThresholdValue))
                    {
                        iThresh = ozoneAnalysisConfiguration.rrfSpatialGradientO.topXDays;
                        ozoneModel.ppb = (int)Math.Floor(values[iThresh - 1]);
                    }
                    else
                    {
                        while (j <= Math.Ceiling(values[0]) - Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minAllowableThresholdValue))
                        {
                            iThresh = 0;
                            while (iThresh < dicUsedinRRF.Count)//ozoneModel.lstOzone.Count)
                            {
                                if (values[iThresh] < Math.Ceiling(values[0]) - j) break;
                                iThresh++;
                            }
                            if (iThresh >= Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minNumofDaysAtorAboveThreshold)) break;
                            j++;

                        }
                        if (j > (int)Math.Ceiling(values[0]) - Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minAllowableThresholdValue))
                            j = (int)Math.Ceiling(values[0]) - Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minAllowableThresholdValue);

                        ozoneModel.ppb = (int)Math.Ceiling(values[0]) - j;
                    }
                }

                float[] valuesTemp = values.Where(p => p > -9).ToArray();

                ozoneModel.days = iThresh;
                if (iThresh < Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minNumDaysAtorAboveMinAllowableThreshold) && (!IsSpatialField || !ozoneAnalysisConfiguration.rrfSpatialGradientO.doBackstop))
                {
                    ozoneModel.ozone = -9;
                    ozoneModel.futureOzone = -9;
                    ozoneModel.rrf = -9;
                    //ozoneModel.ppb = 0;
                    if (ozoneModel.days == 0) ozoneModel.ppb = Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minAllowableThresholdValue);//70;
                    //return;
                }
                else
                    ozoneModel.ozone = Convert.ToSingle(Convert.ToDecimal(valuesTemp.ToList().GetRange(0, valuesTemp.Length > iThresh ? iThresh : valuesTemp.Length).Average()));

                #region by Yangwenwei
                if (IsSpatialField)
                {
                    //select model days according to subrang first and last day
                    values = dicUsedinRRF.Select(p => p.Value[0]).ToArray();

                    int Thresh_Step = 0, count = 0;

                    int miniThresh = ozoneAnalysisConfiguration.rrfSpatialGradientO.doBackstop ? Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.backstopMinThresholdforSpatialField) : 0;

                    if (ozoneAnalysisConfiguration.rrfSpatialGradientO.useInitialThreshold)
                    {
                        int iniThresh = Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.initialThresholdValue);

                        while (Thresh_Step <= iniThresh - miniThresh)
                        {
                            count = 0;
                            while (count < dicUsedinRRF.Count)//ozoneModel.lstOzone.Count)
                            {
                                if (values[count] < iniThresh - Thresh_Step) break;
                                count++;
                            }
                            if (count >= Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minNumofDaysAtorAboveThreshold)) break;//enough,stop
                            Thresh_Step++;

                        }
                        if (Thresh_Step > iniThresh - miniThresh)
                            Thresh_Step = iniThresh - miniThresh;

                        ozoneModel.ppbforSptailfield = iniThresh - Thresh_Step;

                    }
                    else
                    {
                        if (values[ozoneAnalysisConfiguration.rrfSpatialGradientO.topXDays - 1] > miniThresh)
                        {
                            count = ozoneAnalysisConfiguration.rrfSpatialGradientO.topXDays;
                            ozoneModel.ppbforSptailfield = (int)Math.Floor(values[count - 1]);
                        }
                        else
                        {
                            while (Thresh_Step <= Math.Ceiling(values[0]) - miniThresh)
                            {
                                count = 0;
                                while (count < dicUsedinRRF.Count)//ozoneModel.lstOzone.Count)
                                {
                                    if (values[count] < Math.Ceiling(values[0]) - Thresh_Step) break;
                                    count++;
                                }
                                if (count >= Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minNumofDaysAtorAboveThreshold)) break;
                                Thresh_Step++;

                            }
                            if (Thresh_Step > (int)Math.Ceiling(values[0]) - miniThresh)
                                Thresh_Step = (int)Math.Ceiling(values[0]) - miniThresh;

                            ozoneModel.ppbforSptailfield = (int)Math.Ceiling(values[0]) - Thresh_Step;
                        }
                    }


                    float[] ValidValues = values.Where(p => p > -9).ToArray();
                    ozoneModel.daysforSptailfield = count;
                    if (count < Convert.ToInt32(ozoneAnalysisConfiguration.rrfSpatialGradientO.minNumDaysAtorAboveMinAllowableThreshold))
                    {
                        ozoneModel.bO3forSptailfield = -9;
                        //return;
                    }
                    else
                        ozoneModel.bO3forSptailfield = Convert.ToSingle(Convert.ToDecimal(ValidValues.ToList().GetRange(0, ValidValues.Length > count ? count : ValidValues.Length).Average()));


                    if (ozoneModel.bO3forSptailfield > 0)
                    {
                        if (!ozoneAnalysisConfiguration.rrfSpatialGradientO.doPairDays)
                        {
                            string[] IDArray = dicUsedinRRF.Keys.ToList().GetRange(0, count).ToArray();//ozoneModel.lstOzone.Keys.ToList().GetRange(0, ozoneModel.days).ToArray();
                            float[] valuesForecast = new float[count];
                            for (int iArray = 0; iArray < count; iArray++)
                            {
                                if (dicUsedinRRF[IDArray[iArray]][1] >= 0)
                                    valuesForecast[iArray] = dicUsedinRRF[IDArray[iArray]][1];
                            }
                            //if (valuesForecast.Average() == -9 || valuesForecast.Average() == -7) { ozoneModel.rrf = -9; return; }
                            //double[] valuesForecast = ozoneModel.lstOzoneForecast.Select(p => p.Value).Where(p => p != -9).OrderByDescending(p => p).ToArray();
                            // valuesForecast = valuesForecast.Where(p => p > 0).ToArray();
                            if (valuesForecast.Count() > 0)
                            {

                                ozoneModel.rrfforSptailfield = CommonClass.ToFixed(Convert.ToSingle(valuesForecast.Average()) / ozoneModel.bO3forSptailfield, 4);// Math.Round(valuesForecast.Where(p => p != -9).Average() / ozoneModel.ozone, 3);
                                //ozoneModel.futureOzone = Convert.ToSingle(valuesForecast.Average());
                            }
                            else
                            {
                                ozoneModel.rrfforSptailfield = -9;
                                //ozoneModel.futureOzone = -9;
                            }

                        }
                        else
                        {
                            List<float> lstfuture = dicUsedinRRF.OrderByDescending(q => q.Value[1]).Select(q => q.Value[1]).ToList().GetRange(0, count).Where(q => q >= 0).ToList();
                            if (lstfuture.Count > 0)
                            {
                                ozoneModel.rrfforSptailfield = CommonClass.ToFixed(Convert.ToSingle(lstfuture.Average()) / ozoneModel.ozone, 4);
                                //ozoneModel.futureOzone = Convert.ToSingle(lstfuture.Average());
                            }
                            else
                            {
                                ozoneModel.rrfforSptailfield = -9;
                                //ozoneModel.futureOzone = -9;
                            }
                        }
                    }
                    else { ozoneModel.rrfforSptailfield = -9; }

                }

                #endregion


                //得到rrf
                //-----首先得到OzoneForecast,
                if (ozoneModel.ozone > 0)
                {
                    try
                    {
                        if (!ozoneAnalysisConfiguration.rrfSpatialGradientO.doPairDays)
                        {
                            string[] IDArray = dicUsedinRRF.Keys.ToList().GetRange(0, ozoneModel.days).ToArray();//ozoneModel.lstOzone.Keys.ToList().GetRange(0, ozoneModel.days).ToArray();
                            float[] valuesForecast = new float[ozoneModel.days];
                            for (int iArray = 0; iArray < ozoneModel.days; iArray++)
                            {
                                if (dicUsedinRRF[IDArray[iArray]][1] >= 0)
                                    valuesForecast[iArray] = dicUsedinRRF[IDArray[iArray]][1];
                            }
                            if (valuesForecast.Average() == -9 || valuesForecast.Average() == -7) { ozoneModel.rrf = -9; return; }
                            //double[] valuesForecast = ozoneModel.lstOzoneForecast.Select(p => p.Value).Where(p => p != -9).OrderByDescending(p => p).ToArray();
                            // valuesForecast = valuesForecast.Where(p => p > 0).ToArray();
                            if (valuesForecast.Count() > 0)
                            {

                                ozoneModel.rrf = CommonClass.ToFixed(Convert.ToSingle(valuesForecast.Average()) / ozoneModel.ozone, 4);// Math.Round(valuesForecast.Where(p => p != -9).Average() / ozoneModel.ozone, 3);
                                ozoneModel.futureOzone = Convert.ToSingle(valuesForecast.Average());
                            }
                            else
                            {
                                ozoneModel.rrf = -9;
                                ozoneModel.futureOzone = -9;
                            }

                        }
                        else
                        {
                            List<float> lstfuture = dicUsedinRRF.OrderByDescending(q => q.Value[1]).Select(q => q.Value[1]).ToList().GetRange(0, ozoneModel.days).Where(q => q >= 0).ToList();
                            if (lstfuture.Count > 0)
                            {
                                ozoneModel.rrf = CommonClass.ToFixed(Convert.ToSingle(lstfuture.Average()) / ozoneModel.ozone, 4);
                                ozoneModel.futureOzone = Convert.ToSingle(lstfuture.Average());
                            }
                            else
                            {
                                ozoneModel.rrf = -9;
                                ozoneModel.futureOzone = -9;
                            }
                        }
                    }
                    catch
                    {
                    }
                }
                else
                    ozoneModel.futureOzone = -9;
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
            }

        }

        public static bool SaveOzoneSpatialFieldForBenMAP(BaseScenario baseScenario, List<OzoneModelOutput> lstOzoneOpt, Dictionary<string, int[]> dicColRow, bool isBase, bool isFuture)
        {
            if (!(baseScenario.configuration is OzoneAnalysisConfiguration))
                return false;
            try
            {
                OzoneAnalysisConfiguration BenMapOzone = baseScenario.configuration as OzoneAnalysisConfiguration;
                DataTable dtOzoneSpatial = new DataTable();
                DataTable dtControl = new DataTable();
                dtOzoneSpatial.Columns.Add("Column");
                dtOzoneSpatial.Columns.Add("Row");
                dtOzoneSpatial.Columns.Add("Metric");
                dtOzoneSpatial.Columns.Add("Seasonal Metric");
                dtOzoneSpatial.Columns.Add("Statistic");
                dtOzoneSpatial.Columns.Add("Values");
                dtOzoneSpatial.Columns.Add("gridcell_lat");
                dtOzoneSpatial.Columns.Add("gridcell_long");

                dtControl.Columns.Add("Column");
                dtControl.Columns.Add("Row");
                dtControl.Columns.Add("Metric");
                dtControl.Columns.Add("Seasonal Metric");
                dtControl.Columns.Add("Statistic");
                dtControl.Columns.Add("Values");
                dtControl.Columns.Add("gridcell_lat");
                dtControl.Columns.Add("gridcell_long");
                foreach (var k in lstOzoneOpt)
                {
                    DataRow dr = dtOzoneSpatial.NewRow();
                    DataRow dr2 = dtControl.NewRow();
                    dr[0] = dicColRow[k.id][0];
                    dr[1] = dicColRow[k.id][1];
                    dr[2] = "D8HourMax";
                    dr[3] = "";
                    dr[4] = "Mean";
                    dr[5] = Math.Round(k.vna, 8);
                    dr[6] = Math.Round(k.lat, 6);
                    dr[7] = Math.Round(k.longitude, 6);
                    dtOzoneSpatial.Rows.Add(dr);
                    dr2[0] = dicColRow[k.id][0];
                    dr2[1] = dicColRow[k.id][1];
                    dr2[2] = "D8HourMax";
                    dr2[3] = "";
                    dr2[4] = "Mean";
                    dr2[5] = Math.Round(k.vnaForcast, 8);
                    dr2[6] = Math.Round(k.lat, 6);
                    dr2[7] = Math.Round(k.longitude, 6);
                    dtControl.Rows.Add(dr2);
                }
                if (!CommonClass.IsBatch)
                {
                    if (_resultFilePath == "" && _resultFilePath.Length == 0 || _resultFilePath != CommonClass.ResultFilePath + @"\Result\Output\" + (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName)
                        _resultFilePath = CommonClass.ResultFilePath + @"\Result\Output\" + (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName;
                }
                else
                {
                    if (_resultFilePath == "" && _resultFilePath.Length == 0 || _resultFilePath != CommonClass.ResultFilePath + @"\" + (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName)
                        _resultFilePath = CommonClass.ResultFilePath + @"\" + (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName;
                }
                if (!Directory.Exists(_resultFilePath))
                    System.IO.Directory.CreateDirectory(_resultFilePath);

                //修正文件名称
                if (isBase)//Base
                {
                    string strFile = BenMapOzone.chooseDesiredOutputO.scenarioName + " BenMAP-ready O3 Spatial Field Base (VNA).csv";
                    BaseOutput baseOutput = new BaseOutput();
                    CommonClass.SaveCSV(dtOzoneSpatial, _resultFilePath + @"\" + strFile, "");
                    baseOutput.outputName = strFile.Replace(".csv", "");
                    baseOutput.outputType = "Monitor Network";
                    baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                    if (File.Exists(_resultFilePath + @"\" + strFile))
                    {
                        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                        baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                    }
                    else
                    {
                        baseOutput.outputSize = 0;
                    }
                    baseScenario.lstOutput.Add(baseOutput);
                    dtOzoneSpatial.Dispose();
                }
                if (isFuture)//Future
                {
                    string strFile = BenMapOzone.chooseDesiredOutputO.scenarioName + " BenMAP-ready O3 Spatial Field Future (VNA).csv";
                    BaseOutput baseOutput2 = new BaseOutput();
                    CommonClass.SaveCSV(dtControl, _resultFilePath + @"\" + strFile, "");
                    baseOutput2.outputName = strFile.Replace(".csv", "");
                    baseOutput2.outputType = "Monitor Network";
                    baseOutput2.outputFilePath = _resultFilePath + @"\" + strFile;
                    if (File.Exists(_resultFilePath + @"\" + strFile))
                    {
                        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                        baseOutput2.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                    }
                    else
                    {
                        baseOutput2.outputSize = 0;
                    }
                    baseScenario.lstOutput.Add(baseOutput2);
                    dtControl.Dispose();
                }
                GC.Collect();
                return true;
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
                return false;
            }
        }
        public static bool SaveOzoneSpatialFieldGradAdjForBenMAP(BaseScenario baseScenario, List<OzoneModelOutput> lstOzoneOpt, Dictionary<string, int[]> dicColRow, bool isBase, bool isFuture)
        {
            if (!(baseScenario.configuration is OzoneAnalysisConfiguration))
                return false;
            try
            {

                OzoneAnalysisConfiguration BenMapOzone = baseScenario.configuration as OzoneAnalysisConfiguration;
                DataTable dtGradAdjOzoneSpatial = new DataTable();
                DataTable dtControl = new DataTable();


                dtGradAdjOzoneSpatial.Columns.Add("Column");
                dtGradAdjOzoneSpatial.Columns.Add("Row");
                dtGradAdjOzoneSpatial.Columns.Add("Metric");
                dtGradAdjOzoneSpatial.Columns.Add("Seasonal Metric");
                dtGradAdjOzoneSpatial.Columns.Add("Statistic");
                dtGradAdjOzoneSpatial.Columns.Add("Values");
                dtGradAdjOzoneSpatial.Columns.Add("gridcell_lat");
                dtGradAdjOzoneSpatial.Columns.Add("gridcell_long");

                dtControl.Columns.Add("Column");
                dtControl.Columns.Add("Row");
                dtControl.Columns.Add("Metric");
                dtControl.Columns.Add("Seasonal Metric");
                dtControl.Columns.Add("Statistic");
                dtControl.Columns.Add("Values");
                dtControl.Columns.Add("gridcell_lat");
                dtControl.Columns.Add("gridcell_long");


                foreach (var k in lstOzoneOpt)
                {
                    DataRow dr = dtGradAdjOzoneSpatial.NewRow();
                    DataRow dr2 = dtControl.NewRow();
                    dr[0] = dicColRow[k.id][0];
                    dr[1] = dicColRow[k.id][1];
                    dr[2] = "D8HourMax";
                    dr[3] = "";
                    dr[4] = "Mean";
                    dr[5] = Math.Round(k.evna, 8);
                    dr[6] = Math.Round(k.lat, 6);
                    dr[7] = Math.Round(k.longitude, 6);
                    dtGradAdjOzoneSpatial.Rows.Add(dr);
                    dr2[0] = dicColRow[k.id][0];
                    dr2[1] = dicColRow[k.id][1];
                    dr2[2] = "D8HourMax";
                    dr2[3] = "";
                    dr2[4] = "Mean";
                    dr2[5] = Math.Round(k.evnaForcast, 8);
                    dr2[6] = Math.Round(k.lat, 6);
                    dr2[7] = Math.Round(k.longitude, 6);
                    dtControl.Rows.Add(dr2);

                }

                if (!CommonClass.IsBatch)
                {
                    if (_resultFilePath == "" && _resultFilePath.Length == 0 || _resultFilePath != CommonClass.ResultFilePath + @"\Result\Output\" + (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName)
                        _resultFilePath = CommonClass.ResultFilePath + @"\Result\Output\" + (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName;
                }
                else
                {
                    if (_resultFilePath == "" && _resultFilePath.Length == 0 || _resultFilePath != CommonClass.ResultFilePath + @"\" + (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName)
                        _resultFilePath = CommonClass.ResultFilePath + @"\" + (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName;
                }
                if (!Directory.Exists(_resultFilePath))
                    System.IO.Directory.CreateDirectory(_resultFilePath);

                if (isBase)
                {
                    //修正文件名称
                    string strFile = BenMapOzone.chooseDesiredOutputO.scenarioName + " BenMAP-ready O3 Spatial Field Base (eVNA).csv";
                    BaseOutput baseOutput = new BaseOutput();
                    CommonClass.SaveCSV(dtGradAdjOzoneSpatial, _resultFilePath + @"\" + strFile, "");
                    baseOutput.outputName = strFile.Replace(".csv", "");
                    baseOutput.outputType = "Monitor Network";
                    baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                    if (File.Exists(_resultFilePath + @"\" + strFile))
                    {
                        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                        baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                    }
                    else
                    {
                        baseOutput.outputSize = 0;
                    }
                    baseScenario.lstOutput.Add(baseOutput);
                    dtGradAdjOzoneSpatial.Dispose();
                }
                if (isFuture)
                {
                    string strFile = BenMapOzone.chooseDesiredOutputO.scenarioName + " BenMAP-ready O3 Spatial Field Future (eVNA).csv";
                    BaseOutput baseOutput2 = new BaseOutput();
                    CommonClass.SaveCSV(dtControl, _resultFilePath + @"\" + strFile, "");
                    baseOutput2.outputName = strFile.Replace(".csv", "");
                    baseOutput2.outputType = "Monitor Network";
                    baseOutput2.outputFilePath = _resultFilePath + @"\" + strFile;
                    if (File.Exists(_resultFilePath + @"\" + strFile))
                    {
                        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                        baseOutput2.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                    }
                    else
                    {
                        baseOutput2.outputSize = 0;
                    }
                    baseScenario.lstOutput.Add(baseOutput2);
                    dtControl.Dispose();
                }
                GC.Collect();
                return true;
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
                return false;
            }
        }
        public static bool SaveOzoneSpatialFieldDSForBenMAP(BaseScenario baseScenario, List<OzoneModelOutput> lstOzoneOpt, Dictionary<string, int[]> dicColRow, List<DownscaleR.Ozone.OzoneModel> lstDSvalue, bool isBase, bool isFuture)
        {
            if (!(baseScenario.configuration is OzoneAnalysisConfiguration))
                return false;
            try
            {
                OzoneAnalysisConfiguration BenMapOzone = baseScenario.configuration as OzoneAnalysisConfiguration;
                DataTable dtOzoneDSBase = new DataTable();
                DataTable dtOzoneDSControl = new DataTable();
                {
                    dtOzoneDSBase.Columns.Add("Column");
                    dtOzoneDSBase.Columns.Add("Row");
                    dtOzoneDSBase.Columns.Add("Metric");
                    dtOzoneDSBase.Columns.Add("Seasonal Metric");
                    dtOzoneDSBase.Columns.Add("Statistic");
                    dtOzoneDSBase.Columns.Add("Values");
                    dtOzoneDSBase.Columns.Add("gridcell_lat");
                    dtOzoneDSBase.Columns.Add("gridcell_long");

                    dtOzoneDSControl.Columns.Add("Column");
                    dtOzoneDSControl.Columns.Add("Row");
                    dtOzoneDSControl.Columns.Add("Metric");
                    dtOzoneDSControl.Columns.Add("Seasonal Metric");
                    dtOzoneDSControl.Columns.Add("Statistic");
                    dtOzoneDSControl.Columns.Add("Values");
                    dtOzoneDSControl.Columns.Add("gridcell_lat");
                    dtOzoneDSControl.Columns.Add("gridcell_long");
                    for (int i = 0; i < lstOzoneOpt.Count; i++)
                    {
                        DataRow dr = dtOzoneDSBase.NewRow();
                        DataRow dr2 = dtOzoneDSControl.NewRow();
                        dr[0] = dicColRow[lstOzoneOpt[i].id][0];
                        dr[1] = dicColRow[lstOzoneOpt[i].id][1];
                        dr[2] = "D8HourMax";
                        dr[3] = "";
                        dr[4] = "Mean";
                        dr[5] = lstDSvalue[i].DS_Prediction;
                        dr[6] = Math.Round(lstOzoneOpt[i].lat, 6);
                        dr[7] = Math.Round(lstOzoneOpt[i].longitude, 6);
                        dtOzoneDSBase.Rows.Add(dr);
                        dr2[0] = dicColRow[lstOzoneOpt[i].id][0];
                        dr2[1] = dicColRow[lstOzoneOpt[i].id][1];
                        dr2[2] = "D8HourMax";
                        dr2[3] = "";
                        dr2[4] = "Mean";
                        dr2[5] = lstOzoneOpt[i].rrf < 0 ? -9 : (lstDSvalue[i].DS_Prediction < 0 ? -9 : lstDSvalue[i].DS_Prediction * lstOzoneOpt[i].rrf);
                        dr2[6] = Math.Round(lstOzoneOpt[i].lat, 6);
                        dr2[7] = Math.Round(lstOzoneOpt[i].longitude, 6);
                        dtOzoneDSControl.Rows.Add(dr2);
                    }

                }
                if (!CommonClass.IsBatch)
                {
                    if (_resultFilePath == "" && _resultFilePath.Length == 0 || _resultFilePath != CommonClass.ResultFilePath + @"\Result\Output\" + (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName)
                        _resultFilePath = CommonClass.ResultFilePath + @"\Result\Output\" + (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName;
                }
                else
                {
                    if (_resultFilePath == "" && _resultFilePath.Length == 0 || _resultFilePath != CommonClass.ResultFilePath + @"\" + (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName)
                        _resultFilePath = CommonClass.ResultFilePath + @"\" + (CommonClass.CurrentBaseScenario.configuration as OzoneAnalysisConfiguration).chooseDesiredOutputO.scenarioName;
                }
                if (!Directory.Exists(_resultFilePath))
                    System.IO.Directory.CreateDirectory(_resultFilePath);
                if (isBase)
                {
                    //修正文件名称
                    string strFile = BenMapOzone.chooseDesiredOutputO.scenarioName + " BenMAP-ready O3 Spatial Field Base (Downscaler).csv";
                    BaseOutput baseOutput = new BaseOutput();
                    CommonClass.SaveCSV(dtOzoneDSBase, _resultFilePath + @"\" + strFile, "");
                    baseOutput.outputName = strFile.Replace(".csv", "");
                    baseOutput.outputType = "Spatial Field";
                    baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                    if (File.Exists(_resultFilePath + @"\" + strFile))
                    {
                        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                        baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                    }
                    else
                    {
                        baseOutput.outputSize = 0;
                    }
                    baseScenario.lstOutput.Add(baseOutput);
                    dtOzoneDSBase.Dispose();
                }

                if (isFuture)
                {
                    string strFile = BenMapOzone.chooseDesiredOutputO.scenarioName + " BenMAP-ready O3 Spatial Field Future (Downscaler).csv";
                    BaseOutput baseOutput2 = new BaseOutput();
                    CommonClass.SaveCSV(dtOzoneDSControl, _resultFilePath + @"\" + strFile, "");
                    baseOutput2.outputName = strFile.Replace(".csv", "");
                    baseOutput2.outputType = "Spatial Field";
                    baseOutput2.outputFilePath = _resultFilePath + @"\" + strFile;
                    if (File.Exists(_resultFilePath + @"\" + strFile))
                    {
                        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                        baseOutput2.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                    }
                    else
                    {
                        baseOutput2.outputSize = 0;
                    }
                    baseScenario.lstOutput.Add(baseOutput2);
                    dtOzoneDSControl.Dispose();
                }
                GC.Collect();
                return true;
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
                return false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="lstOzoneModelOutput"></param>
        /// <param name="baseScenario"></param>
        /// <param name="forcastYear"></param>
        public static bool SaveLstOzoneModelOutput(List<OzoneModelOutput> lstOzoneModelOutput, BaseScenario baseScenario, string forcastYear, List<DownscaleR.Ozone.OzoneModel> lstDSvalue)
        {
            try
            {
                if (!(baseScenario.configuration is OzoneAnalysisConfiguration))
                {
                    return false;
                }
                OzoneAnalysisConfiguration ozoneAnalysisConfiguration = (baseScenario.configuration) as OzoneAnalysisConfiguration;
                BaseOutput baseOutput = null;
                string strFile = "";
                string dataType = "";
                DataTable dtOutMonitorControl = new DataTable();

                #region output option
                bool vnab, vnaf, evnab, evnaf, dsb, dsf;
                vnab = false;
                vnaf = false;
                evnab = false;
                evnaf = false;
                dsb = false;
                dsf = false;
                //VNA---output option----
                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimates || ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyVNA)
                {
                    vnab = true;
                    vnaf = true;
                }
                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyVNA)
                {
                    vnab = true;
                }
                //eVNA----output option-----------
                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimatesGradAdj || ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyEVNA)
                {
                    evnab = true;
                    evnaf = true;
                }
                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyEVNA)
                {
                    evnab = true;
                }
                //eVNA----output option-----------
                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doDownscaler || ozoneAnalysisConfiguration.chooseDesiredOutputO.DSFutureOnly)
                {
                    dsb = true;
                    dsf = true;
                }
                if (ozoneAnalysisConfiguration.chooseDesiredOutputO.DSBaseOnly)
                {
                    dsb = true;
                }
                #endregion

                #region modified by Yangwenwei
                dtOutMonitorControl.Columns.Add("_id");
                dtOutMonitorControl.Columns.Add("_type");
                dtOutMonitorControl.Columns.Add("lat");
                dtOutMonitorControl.Columns.Add("long");
                dtOutMonitorControl.Columns.Add("date");
                dtOutMonitorControl.Columns.Add("ga_conc");
                if (vnab) dtOutMonitorControl.Columns.Add("i_b_o3(VNA)");
                if (vnaf) dtOutMonitorControl.Columns.Add("i_f_o3(VNA)");
                if (evnab) dtOutMonitorControl.Columns.Add("i_b_o3(eVNA)");
                if (evnaf) dtOutMonitorControl.Columns.Add("i_f_o3(eVNA)");
                if (dsb) dtOutMonitorControl.Columns.Add("i_b_o3(Downscaler)");
                if (dsf) dtOutMonitorControl.Columns.Add("i_f_o3(Downscaler)");
                dtOutMonitorControl.Columns.Add("b_o3_model");
                dtOutMonitorControl.Columns.Add("f_o3_model");
                dtOutMonitorControl.Columns.Add("ppb");
                dtOutMonitorControl.Columns.Add("days");
                dtOutMonitorControl.Columns.Add("referencecell");
                dtOutMonitorControl.Columns.Add("rrf");

                for (int i = 0; i < lstOzoneModelOutput.Count; i++)
                {
                    int j = 0;
                    DataRow dr = dtOutMonitorControl.NewRow();
                    dr[j++] = lstOzoneModelOutput[i].id;
                    dr[j++] = "";//---------少了type
                    dr[j++] = lstOzoneModelOutput[i].lat;
                    dr[j++] = lstOzoneModelOutput[i].longitude;
                    dr[j++] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                    dr[j++] = Math.Round(lstOzoneModelOutput[i].ga_conc, 8);
                    if (vnab) dr[j++] = Math.Round(lstOzoneModelOutput[i].vna, 8);
                    if (vnaf) dr[j++] = Math.Round(lstOzoneModelOutput[i].vnaForcast, 8);
                    if (evnab) dr[j++] = Math.Round(lstOzoneModelOutput[i].evna, 8);
                    if (evnaf) dr[j++] = Math.Round(lstOzoneModelOutput[i].evnaForcast, 8);
                    if (dsb) dr[j++] = Math.Round(lstDSvalue[i].DS_Prediction, 8);
                    if (dsf)
                    {
                        if (lstDSvalue[i].DS_Prediction == -9 || lstOzoneModelOutput[i].rrf == -9)
                        { dr[j++] = -9; }
                        else
                        { dr[j++] = Math.Round(lstDSvalue[i].DS_Prediction * lstOzoneModelOutput[i].rrf, 8); }
                        //dr[j++] = Math.Round(lstDSvalue[i].DS_SEpred, 8);
                    }
                    dr[j++] = Math.Round(lstOzoneModelOutput[i].bO3modelForSpatialField, 8);
                    dr[j++] = (lstOzoneModelOutput[i].bO3modelForSpatialField == -9 || lstOzoneModelOutput[i].rrf == -9) ? -9 :
                        Math.Round(lstOzoneModelOutput[i].bO3modelForSpatialField * lstOzoneModelOutput[i].rrf, 8);
                    dr[j++] = lstOzoneModelOutput[i].ppb;
                    dr[j++] = lstOzoneModelOutput[i].days;
                    dr[j++] = lstOzoneModelOutput[i].referencecell;
                    dr[j++] = Math.Round(lstOzoneModelOutput[i].rrf, 8);
                    dtOutMonitorControl.Rows.Add(dr);
                }
                dataType = "Year";
                strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Spatial Field -- interpolated monitor data, temporally adjusted; gradient-adjusted monitor data, " + forcastYear + ".csv";
                #endregion
                #region
                //if ((ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimates && ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimatesGradAdj))
                //{
                //    #region 1234
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_o3");
                //    dtOutMonitorControl.Columns.Add("i_b_ga_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_ga_o3");
                //    dtOutMonitorControl.Columns.Add("ppb");
                //    dtOutMonitorControl.Columns.Add("days");
                //    dtOutMonitorControl.Columns.Add("referencecell");
                //    dtOutMonitorControl.Columns.Add("rrf");
                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.vna, 8);
                //        dr[7] = Math.Round(om.vnaForcast, 8);
                //        dr[8] = Math.Round(om.evna, 8);
                //        dr[9] = Math.Round(om.evnaForcast, 8);
                //        dr[10] = om.ppb;
                //        dr[11] = om.days;
                //        dr[12] = om.referencecell;
                //        dr[13] = Math.Round(om.rrf, 8);
                //        dtOutMonitorControl.Rows.Add(dr);
                //    }
                //    //------------修正OutPutFileName----------------
                //    dataType = "Year";
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Spatial Field -- interpolated monitor data, temporally adjusted; gradient-adjusted monitor data, " + forcastYear + ".csv";
                //    #endregion
                //}
                //else if ((ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimates && ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyEVNA))
                //{
                //    #region 123
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_o3");
                //    dtOutMonitorControl.Columns.Add("ppb");
                //    dtOutMonitorControl.Columns.Add("days");
                //    dtOutMonitorControl.Columns.Add("referencecell");
                //    dtOutMonitorControl.Columns.Add("rrf");

                //    DataTable dtGradientAdj = new DataTable();
                //    dtGradientAdj.Columns.Add("_id");
                //    dtGradientAdj.Columns.Add("_type");
                //    dtGradientAdj.Columns.Add("lat");
                //    dtGradientAdj.Columns.Add("long");
                //    dtGradientAdj.Columns.Add("date");
                //    dtGradientAdj.Columns.Add("ga_conc");
                //    dtGradientAdj.Columns.Add("i_b_o3");
                //    dtGradientAdj.Columns.Add("i_b_ga_o3");

                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.vna, 8);
                //        dr[7] = Math.Round(om.vnaForcast, 8);
                //        dr[8] = om.ppb;
                //        dr[9] = om.days;
                //        dr[10] = om.referencecell;
                //        dr[11] = Math.Round(om.rrf, 8);
                //        dtOutMonitorControl.Rows.Add(dr);

                //        DataRow drG = dtGradientAdj.NewRow();
                //        drG[0] = om.id;
                //        drG[1] = "";//---------少了type
                //        drG[2] = om.lat;
                //        drG[3] = om.longitude;
                //        drG[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        drG[5] = Math.Round(om.ga_conc, 8);
                //        drG[6] = Math.Round(om.vna, 8);
                //        drG[7] = Math.Round(om.evna, 8);
                //        dtGradientAdj.Rows.Add(drG);
                //    }
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Sptl. Fld. -- interp. monitor data, interp. grad.-adjusted monitor data.csv";
                //    dataType = "Year";
                //    CommonClass.SaveCSV(dtGradientAdj, _resultFilePath + @"\" + strFile, dataType);
                //    baseOutput = new BaseOutput();
                //    baseOutput.outputName = strFile.Replace(".csv", "");
                //    baseOutput.outputType = "Monitor Network";
                //    baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                //    if (File.Exists(_resultFilePath + @"\" + strFile))
                //    {
                //        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                //        baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                //    }
                //    else
                //        baseOutput.outputSize = 0;
                //    baseScenario.lstOutput.Add(baseOutput);

                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Spatial Field -- interpolated monitor data, temporally adjusted " + forcastYear + ".csv";
                //    #endregion
                //}
                //else if ((ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimates && ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyEVNA))
                //{
                //    #region 134
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_o3");
                //    dtOutMonitorControl.Columns.Add("i_b_ga_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_ga_o3");
                //    dtOutMonitorControl.Columns.Add("ppb");
                //    dtOutMonitorControl.Columns.Add("days");
                //    dtOutMonitorControl.Columns.Add("referencecell");
                //    dtOutMonitorControl.Columns.Add("rrf");

                //    DataTable dtGradientAdj = new DataTable();
                //    dtGradientAdj.Columns.Add("_id");
                //    dtGradientAdj.Columns.Add("_type");
                //    dtGradientAdj.Columns.Add("lat");
                //    dtGradientAdj.Columns.Add("long");
                //    dtGradientAdj.Columns.Add("date");
                //    dtGradientAdj.Columns.Add("ga_conc");
                //    dtGradientAdj.Columns.Add("i_b_o3");

                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.vna, 8);
                //        dr[7] = Math.Round(om.vnaForcast, 8);
                //        dr[8] = Math.Round(om.evna, 8);
                //        dr[9] = Math.Round(om.evnaForcast, 8);
                //        dr[10] = om.ppb;
                //        dr[11] = om.days;
                //        dr[12] = om.referencecell;
                //        dr[13] = Math.Round(om.rrf, 8);
                //        dtOutMonitorControl.Rows.Add(dr);

                //        DataRow drG = dtGradientAdj.NewRow();
                //        drG[0] = om.id;
                //        drG[1] = "";//---------少了type
                //        drG[2] = om.lat;
                //        drG[3] = om.longitude;
                //        drG[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        drG[5] = Math.Round(om.ga_conc, 8);
                //        drG[6] = Math.Round(om.vna, 8);
                //        dtGradientAdj.Rows.Add(drG);
                //    }
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Sptl. Fld. -- interp. monitor data.csv";
                //    dataType = "Year";
                //    CommonClass.SaveCSV(dtGradientAdj, _resultFilePath + @"\" + strFile, dataType);
                //    baseOutput = new BaseOutput();
                //    baseOutput.outputName = strFile.Replace(".csv", "");
                //    baseOutput.outputType = "Monitor Network";
                //    baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                //    if (File.Exists(_resultFilePath + @"\" + strFile))
                //    {
                //        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                //        baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                //    }
                //    else
                //        baseOutput.outputSize = 0;
                //    baseScenario.lstOutput.Add(baseOutput);

                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Spatial Field -- interpolated monitor data, temporally adjusted; gradient-adjusted monitor data, " + forcastYear + ".csv";
                //    #endregion
                //}
                //else if ((ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyVNA && ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimatesGradAdj))
                //{
                //    #region 234
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_o3");
                //    dtOutMonitorControl.Columns.Add("i_b_ga_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_ga_o3");
                //    dtOutMonitorControl.Columns.Add("ppb");
                //    dtOutMonitorControl.Columns.Add("days");
                //    dtOutMonitorControl.Columns.Add("referencecell");
                //    dtOutMonitorControl.Columns.Add("rrf");

                //    DataTable dtGradientAdj = new DataTable();
                //    dtGradientAdj.Columns.Add("_id");
                //    dtGradientAdj.Columns.Add("_type");
                //    dtGradientAdj.Columns.Add("lat");
                //    dtGradientAdj.Columns.Add("long");
                //    dtGradientAdj.Columns.Add("date");
                //    dtGradientAdj.Columns.Add("ga_conc");
                //    dtGradientAdj.Columns.Add("i_b_ga_o3");

                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.vna, 8);
                //        dr[7] = Math.Round(om.vnaForcast, 8);
                //        dr[8] = Math.Round(om.evna, 8);
                //        dr[9] = om.evnaForcast;
                //        dr[10] = om.ppb;
                //        dr[11] = om.days;
                //        dr[12] = om.referencecell;
                //        dr[13] = Math.Round(om.rrf, 8);
                //        dtOutMonitorControl.Rows.Add(dr);

                //        DataRow drG = dtGradientAdj.NewRow();
                //        drG[0] = om.id;
                //        drG[1] = "";//---------少了type
                //        drG[2] = om.lat;
                //        drG[3] = om.longitude;
                //        drG[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        drG[5] = Math.Round(om.ga_conc, 8);
                //        drG[6] = Math.Round(om.evna, 8);
                //        dtGradientAdj.Rows.Add(drG);
                //    }
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Sptl. Fld. -- interp. grad.-adjusted monitor data.csv";
                //    dataType = "Year";
                //    CommonClass.SaveCSV(dtGradientAdj, _resultFilePath + @"\" + strFile, dataType);
                //    baseOutput = new BaseOutput();
                //    baseOutput.outputName = strFile.Replace(".csv", "");
                //    baseOutput.outputType = "Monitor Network";
                //    baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                //    if (File.Exists(_resultFilePath + @"\" + strFile))
                //    {
                //        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                //        baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                //    }
                //    else
                //        baseOutput.outputSize = 0;
                //    baseScenario.lstOutput.Add(baseOutput);

                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Spatial Field -- interpolated monitor data, temporally adjusted; gradient-adjusted monitor data, " + forcastYear + ".csv";
                //    #endregion
                //}
                //else if ((ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyVNA && ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimatesGradAdj))
                //{
                //    #region 124
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_ga_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_ga_o3");
                //    dtOutMonitorControl.Columns.Add("ppb");
                //    dtOutMonitorControl.Columns.Add("days");
                //    dtOutMonitorControl.Columns.Add("referencecell");
                //    dtOutMonitorControl.Columns.Add("rrf");

                //    DataTable dtGradientAdj = new DataTable();
                //    dtGradientAdj.Columns.Add("_id");
                //    dtGradientAdj.Columns.Add("_type");
                //    dtGradientAdj.Columns.Add("lat");
                //    dtGradientAdj.Columns.Add("long");
                //    dtGradientAdj.Columns.Add("date");
                //    dtGradientAdj.Columns.Add("ga_conc");
                //    dtGradientAdj.Columns.Add("i_b_o3");
                //    dtGradientAdj.Columns.Add("i_b_ga_o3");

                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.evna, 8);
                //        dr[7] = Math.Round(om.evnaForcast, 8);
                //        dr[8] = om.ppb;
                //        dr[9] = om.days;
                //        dr[10] = om.referencecell;
                //        dr[11] = Math.Round(om.rrf, 8);
                //        dtOutMonitorControl.Rows.Add(dr);

                //        DataRow drG = dtGradientAdj.NewRow();
                //        drG[0] = om.id;
                //        drG[1] = "";//---------少了type
                //        drG[2] = om.lat;
                //        drG[3] = om.longitude;
                //        drG[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        drG[5] = Math.Round(om.ga_conc, 8);
                //        drG[6] = Math.Round(om.vna, 8);
                //        drG[7] = Math.Round(om.evna, 8);
                //        dtGradientAdj.Rows.Add(drG);
                //    }
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Sptl. Fld. -- interp. monitor data, interp. grad.-adjusted monitor data.csv";
                //    dataType = "Year";
                //    CommonClass.SaveCSV(dtGradientAdj, _resultFilePath + @"\" + strFile, dataType);
                //    baseOutput = new BaseOutput();
                //    baseOutput.outputName = strFile.Replace(".csv", "");
                //    baseOutput.outputType = "Monitor Network";
                //    baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                //    if (File.Exists(_resultFilePath + @"\" + strFile))
                //    {
                //        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                //        baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                //    }
                //    else
                //        baseOutput.outputSize = 0;
                //    baseScenario.lstOutput.Add(baseOutput);

                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Spatial Field -- interpolated gradient-adjusted monitor data, temporally adjusted" + forcastYear + ".csv";
                //    #endregion
                //}
                //else if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimates)
                //{
                //    #region 13
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_o3");
                //    dtOutMonitorControl.Columns.Add("ppb");
                //    dtOutMonitorControl.Columns.Add("days");
                //    dtOutMonitorControl.Columns.Add("referencecell");
                //    dtOutMonitorControl.Columns.Add("rrf");

                //    DataTable dtGradientAdj = new DataTable();
                //    dtGradientAdj.Columns.Add("_id");
                //    dtGradientAdj.Columns.Add("_type");
                //    dtGradientAdj.Columns.Add("lat");
                //    dtGradientAdj.Columns.Add("long");
                //    dtGradientAdj.Columns.Add("date");
                //    dtGradientAdj.Columns.Add("ga_conc");
                //    dtGradientAdj.Columns.Add("i_b_o3");

                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.vna, 8);
                //        dr[7] = Math.Round(om.vnaForcast, 8);
                //        dr[8] = om.ppb;
                //        dr[9] = om.days;
                //        dr[10] = om.referencecell;
                //        dr[11] = Math.Round(om.rrf, 8);
                //        dtOutMonitorControl.Rows.Add(dr);

                //        DataRow drG = dtGradientAdj.NewRow();
                //        drG[0] = om.id;
                //        drG[1] = "";//---------少了type
                //        drG[2] = om.lat;
                //        drG[3] = om.longitude;
                //        drG[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        drG[5] = Math.Round(om.ga_conc, 8);
                //        drG[6] = Math.Round(om.vna, 8);
                //        dtGradientAdj.Rows.Add(drG);
                //    }
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Sptl. Fld. -- interp. monitor data.csv";
                //    dataType = "Year";
                //    CommonClass.SaveCSV(dtGradientAdj, _resultFilePath + @"\" + strFile, dataType);
                //    baseOutput = new BaseOutput();
                //    baseOutput.outputName = strFile.Replace(".csv", "");
                //    baseOutput.outputType = "Monitor Network";
                //    baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                //    if (File.Exists(_resultFilePath + @"\" + strFile))
                //    {
                //        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                //        baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                //    }
                //    else
                //        baseOutput.outputSize = 0;
                //    baseScenario.lstOutput.Add(baseOutput);

                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Spatial Field -- interpolated monitor data, temporally adjusted " + forcastYear + ".csv";
                //    #endregion
                //}
                //else if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyVNA && ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyEVNA)
                //{
                //    #region 12
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_o3");
                //    dtOutMonitorControl.Columns.Add("i_b_ga_o3");

                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.vna, 8);
                //        dr[7] = Math.Round(om.evna, 8);
                //        dtOutMonitorControl.Rows.Add(dr);
                //    }
                //    dataType = "Year";
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Sptl Fld -- interp. monitor data, interp. grad. - adjusted monitor data.csv";
                //    #endregion
                //}
                //else if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyVNA && ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyEVNA)
                //{
                //    #region 14
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_ga_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_ga_o3");
                //    dtOutMonitorControl.Columns.Add("ppb");
                //    dtOutMonitorControl.Columns.Add("days");
                //    dtOutMonitorControl.Columns.Add("referencecell");
                //    dtOutMonitorControl.Columns.Add("rrf");

                //    DataTable dtGradientAdj = new DataTable();
                //    dtGradientAdj.Columns.Add("_id");
                //    dtGradientAdj.Columns.Add("_type");
                //    dtGradientAdj.Columns.Add("lat");
                //    dtGradientAdj.Columns.Add("long");
                //    dtGradientAdj.Columns.Add("date");
                //    dtGradientAdj.Columns.Add("ga_conc");
                //    dtGradientAdj.Columns.Add("i_b_o3");

                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.evna, 8);
                //        dr[7] = Math.Round(om.evnaForcast, 8);
                //        dr[8] = om.ppb;
                //        dr[9] = om.days;
                //        dr[10] = om.referencecell;
                //        dr[11] = Math.Round(om.rrf, 8);
                //        dtOutMonitorControl.Rows.Add(dr);

                //        DataRow drG = dtGradientAdj.NewRow();
                //        drG[0] = om.id;
                //        drG[1] = "";//---------少了type
                //        drG[2] = om.lat;
                //        drG[3] = om.longitude;
                //        drG[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        drG[5] = Math.Round(om.ga_conc, 8);
                //        drG[6] = Math.Round(om.vna, 8);
                //        dtGradientAdj.Rows.Add(drG);
                //    }
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Sptl. Fld. -- interp. monitor data.csv";
                //    dataType = "Year";
                //    CommonClass.SaveCSV(dtGradientAdj, _resultFilePath + @"\" + strFile, dataType);
                //    baseOutput = new BaseOutput();
                //    baseOutput.outputName = strFile.Replace(".csv", "");
                //    baseOutput.outputType = "Monitor Network";
                //    baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                //    if (File.Exists(_resultFilePath + @"\" + strFile))
                //    {
                //        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                //        baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                //    }
                //    else
                //        baseOutput.outputSize = 0;
                //    baseScenario.lstOutput.Add(baseOutput);

                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Spatial Field -- interpolated gradient - adjusted monitor data, temporally adjusted " + forcastYear + ".csv";
                //    #endregion
                //}
                //else if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyEVNA && ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyVNA)
                //{
                //    #region 23
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_o3");
                //    dtOutMonitorControl.Columns.Add("ppb");
                //    dtOutMonitorControl.Columns.Add("days");
                //    dtOutMonitorControl.Columns.Add("referencecell");
                //    dtOutMonitorControl.Columns.Add("rrf");

                //    DataTable dtGradientAdj = new DataTable();
                //    dtGradientAdj.Columns.Add("_id");
                //    dtGradientAdj.Columns.Add("_type");
                //    dtGradientAdj.Columns.Add("lat");
                //    dtGradientAdj.Columns.Add("long");
                //    dtGradientAdj.Columns.Add("date");
                //    dtGradientAdj.Columns.Add("ga_conc");
                //    dtGradientAdj.Columns.Add("i_b_ga_o3");

                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.vna, 8);
                //        dr[7] = Math.Round(om.vnaForcast, 8);
                //        dr[8] = om.ppb;
                //        dr[9] = om.days;
                //        dr[10] = om.referencecell;
                //        dr[11] = Math.Round(om.rrf, 8);
                //        dtOutMonitorControl.Rows.Add(dr);

                //        DataRow drG = dtGradientAdj.NewRow();
                //        drG[0] = om.id;
                //        drG[1] = "";//---------少了type
                //        drG[2] = om.lat;
                //        drG[3] = om.longitude;
                //        drG[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        drG[5] = Math.Round(om.ga_conc, 8);
                //        drG[6] = Math.Round(om.evna, 8);
                //        dtGradientAdj.Rows.Add(drG);
                //    }
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Sptl. Fld. -- interp.grad.-adjusted monitor data.csv";
                //    dataType = "Year";
                //    CommonClass.SaveCSV(dtGradientAdj, _resultFilePath + @"\" + strFile, dataType);
                //    baseOutput = new BaseOutput();
                //    baseOutput.outputName = strFile.Replace(".csv", "");
                //    baseOutput.outputType = "Monitor Network";
                //    baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                //    if (File.Exists(_resultFilePath + @"\" + strFile))
                //    {
                //        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                //        baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                //    }
                //    else
                //        baseOutput.outputSize = 0;
                //    baseScenario.lstOutput.Add(baseOutput);

                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Spatial Field -- interpolated monitor data, temporally adjusted " + forcastYear + ".csv";
                //    #endregion
                //}
                //else if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doSpatialFieldEstimatesGradAdj)
                //{
                //    #region 24
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_ga_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_ga_o3");
                //    dtOutMonitorControl.Columns.Add("ppb");
                //    dtOutMonitorControl.Columns.Add("days");
                //    dtOutMonitorControl.Columns.Add("referencecell");
                //    dtOutMonitorControl.Columns.Add("rrf");

                //    DataTable dtGradientAdj = new DataTable();
                //    dtGradientAdj.Columns.Add("_id");
                //    dtGradientAdj.Columns.Add("_type");
                //    dtGradientAdj.Columns.Add("lat");
                //    dtGradientAdj.Columns.Add("long");
                //    dtGradientAdj.Columns.Add("date");
                //    dtGradientAdj.Columns.Add("ga_conc");
                //    dtGradientAdj.Columns.Add("i_b_ga_o3");

                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.evna, 8);
                //        dr[7] = Math.Round(om.evnaForcast, 8);
                //        dr[8] = om.ppb;
                //        dr[9] = om.days;
                //        dr[10] = om.referencecell;
                //        dr[11] = Math.Round(om.rrf, 8);
                //        dtOutMonitorControl.Rows.Add(dr);

                //        DataRow drG = dtGradientAdj.NewRow();
                //        drG[0] = om.id;
                //        drG[1] = "";//---------少了type
                //        drG[2] = om.lat;
                //        drG[3] = om.longitude;
                //        drG[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        drG[5] = Math.Round(om.ga_conc, 8);
                //        drG[6] = Math.Round(om.evna, 8);
                //        dtGradientAdj.Rows.Add(drG);
                //    }
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Sptl. Fld. -- interp.grad.-adjusted monitor data.csv";
                //    dataType = "Year";
                //    CommonClass.SaveCSV(dtGradientAdj, _resultFilePath + @"\" + strFile, dataType);
                //    baseOutput = new BaseOutput();
                //    baseOutput.outputName = strFile.Replace(".csv", "");
                //    baseOutput.outputType = "Monitor Network";
                //    baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                //    if (File.Exists(_resultFilePath + @"\" + strFile))
                //    {
                //        FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                //        baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                //    }
                //    else
                //        baseOutput.outputSize = 0;
                //    baseScenario.lstOutput.Add(baseOutput);

                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Spatial Field -- interpolated gradient-adjusted monitor data, temporally adjusted " + forcastYear + ".csv";
                //    #endregion
                //}
                //else if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyEVNA && ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyVNA)
                //{
                //    #region 34
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_o3");
                //    dtOutMonitorControl.Columns.Add("i_b_ga_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_ga_o3");
                //    dtOutMonitorControl.Columns.Add("ppb");
                //    dtOutMonitorControl.Columns.Add("days");
                //    dtOutMonitorControl.Columns.Add("referencecell");
                //    dtOutMonitorControl.Columns.Add("rrf");

                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.vna, 8);
                //        dr[7] = Math.Round(om.vnaForcast, 8);
                //        dr[8] = Math.Round(om.evna, 8);
                //        dr[9] = Math.Round(om.evnaForcast, 8);
                //        dr[10] = om.ppb;
                //        dr[11] = om.days;
                //        dr[12] = om.referencecell;
                //        dr[13] = Math.Round(om.rrf, 8);
                //        dtOutMonitorControl.Rows.Add(dr);
                //    }
                //    dataType = "Year";
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Spatial Field -- interpolated monitor data, temporally adjusted; gradient-adjusted monitor data, " + forcastYear + ".csv";
                //    #endregion
                //}
                //else if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyVNA)
                //{
                //    #region 1
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_o3");
                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.vna, 8);
                //        dtOutMonitorControl.Rows.Add(dr);
                //    }
                //    dataType = "Year";
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Sptl. Fld. -- interp. monitor data.csv";
                //    #endregion
                //}
                //else if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyVNA)
                //{
                //    #region 3
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_o3");
                //    dtOutMonitorControl.Columns.Add("ppb");
                //    dtOutMonitorControl.Columns.Add("days");
                //    dtOutMonitorControl.Columns.Add("referencecell");
                //    dtOutMonitorControl.Columns.Add("rrf");
                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.vna, 8);
                //        dr[7] = Math.Round(om.vnaForcast, 8);
                //        dr[8] = om.ppb;
                //        dr[9] = om.days;
                //        dr[10] = om.referencecell;
                //        dr[11] = Math.Round(om.rrf, 8);
                //        dtOutMonitorControl.Rows.Add(dr);
                //    }
                //    dataType = "Year";
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Spatial Field -- interpolated monitor data, temporally adjusted " + forcastYear + " .csv";
                //    #endregion
                //}
                //else if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doBaseOnlyEVNA)
                //{
                //    #region 2
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_ga_o3");
                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.evna, 8);
                //        dtOutMonitorControl.Rows.Add(dr);
                //    }
                //    dataType = "Year";
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Sptl. Fld. -- interp. grad.-agjusted monitor data.csv";
                //    #endregion
                //}
                //else if (ozoneAnalysisConfiguration.chooseDesiredOutputO.doFutureOnlyEVNA)
                //{
                //    #region 4
                //    dtOutMonitorControl.Columns.Add("_id");
                //    dtOutMonitorControl.Columns.Add("_type");
                //    dtOutMonitorControl.Columns.Add("lat");
                //    dtOutMonitorControl.Columns.Add("long");
                //    dtOutMonitorControl.Columns.Add("date");
                //    dtOutMonitorControl.Columns.Add("ga_conc");
                //    dtOutMonitorControl.Columns.Add("i_b_ga_o3");
                //    dtOutMonitorControl.Columns.Add("i_f_ga_o3");
                //    dtOutMonitorControl.Columns.Add("ppb");
                //    dtOutMonitorControl.Columns.Add("days");
                //    dtOutMonitorControl.Columns.Add("referencecell");
                //    dtOutMonitorControl.Columns.Add("rrf");
                //    foreach (OzoneModelOutput om in lstOzoneModelOutput)
                //    {
                //        DataRow dr = dtOutMonitorControl.NewRow();
                //        dr[0] = om.id;
                //        dr[1] = "";//---------少了type
                //        dr[2] = om.lat;
                //        dr[3] = om.longitude;
                //        dr[4] = ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                //        dr[5] = Math.Round(om.ga_conc, 8);
                //        dr[6] = Math.Round(om.evna, 8);
                //        dr[7] = Math.Round(om.evnaForcast, 8);
                //        dr[8] = om.ppb;
                //        dr[9] = om.days;
                //        dr[10] = om.referencecell;
                //        dr[11] = Math.Round(om.rrf, 8);
                //        dtOutMonitorControl.Rows.Add(dr);
                //    }
                //    dataType = "Year";
                //    strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Spatial Field -- interpolated gradient-adjusted monitor data, temporally adjusted " + forcastYear + " .csv";
                //    #endregion
                //}
                #endregion
                CommonClass.SaveCSV(dtOutMonitorControl, _resultFilePath + @"\" + strFile, dataType);
                baseOutput = new BaseOutput();
                baseOutput.outputName = strFile.Replace(".csv", "");
                baseOutput.outputType = "Monitor Network";
                baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                if (File.Exists(_resultFilePath + @"\" + strFile))
                {
                    FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                    baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                }
                else
                    baseOutput.outputSize = 0;
                baseScenario.lstOutput.Add(baseOutput);
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// Save Ozone OutPut
        /// </summary>
        /// <param name="dicOzoneMonitorControl"></param>
        /// <param name="baseScenario"></param>
        /// <returns></returns>
        public static bool SaveDicOzoneMonitorControl(Dictionary<string, OzoneMonitorControl> dicOzoneMonitorControl, BaseScenario baseScenario, string forcastYear, string period)
        {
            //------------------OutputMonitorControl && OutputMonitorCountyHight----------
            //_id	_type	lat	long	date	b_o3_DV	f_o3_DV	referencecell	rrf	ppb	days	_state_name	_county_name
            if (!(baseScenario.configuration is OzoneAnalysisConfiguration))
            {
                return false;
            }
            try
            {
                OzoneAnalysisConfiguration ozoneAnalysisConfiguration = (baseScenario.configuration) as OzoneAnalysisConfiguration;
                DataTable dtOutMonitorControl = new DataTable();
                dtOutMonitorControl.Columns.Add("_id");
                dtOutMonitorControl.Columns.Add("_type");
                dtOutMonitorControl.Columns.Add("lat");
                dtOutMonitorControl.Columns.Add("long");
                dtOutMonitorControl.Columns.Add("date");
                dtOutMonitorControl.Columns.Add("b_o3_DV");
                dtOutMonitorControl.Columns.Add("f_o3_DV");
                dtOutMonitorControl.Columns.Add("referencecell");
                dtOutMonitorControl.Columns.Add("rrf");
                dtOutMonitorControl.Columns.Add("ppb");
                dtOutMonitorControl.Columns.Add("days");
                dtOutMonitorControl.Columns.Add("_state_name");
                dtOutMonitorControl.Columns.Add("_county_name");
                string data = period == "" ? ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4) : Convert.ToString(Convert.ToInt16(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneStartYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneStartYear.Length - 4)) + Convert.ToInt16(period.Split(' ')[1]) - 1);
                foreach (KeyValuePair<string, OzoneMonitorControl> k in dicOzoneMonitorControl)
                {
                    DataRow dr = dtOutMonitorControl.NewRow();
                    dr[0] = k.Value.id;
                    dr[1] = "";//---------少了type
                    dr[2] = k.Value.lat;
                    dr[3] = k.Value.longitude;
                    dr[4] = data;//ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                    dr[5] = Math.Round(k.Value.ozonebase, 8);
                    dr[6] = Math.Round(k.Value.ozonecontrol, 8);
                    dr[7] = k.Value.referencecell;
                    dr[8] = Math.Round(k.Value.rrf, 8);
                    dr[9] = k.Value.ppb;
                    dr[10] = k.Value.days;
                    dr[11] = k.Value.state;
                    dr[12] = k.Value.county;
                    dtOutMonitorControl.Rows.Add(dr);
                }

                //------------修正OutPutFileName----------------
                string strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Ozone Monitors -- monitor data, temporally adjusted " + forcastYear + " " + period + ".csv";

                CommonClass.SaveCSV(dtOutMonitorControl, _resultFilePath + @"\" + strFile, "Year");
                BaseOutput baseOutput = new BaseOutput();
                baseOutput.outputName = strFile.Replace(".csv", "");
                //baseOutput.outputName = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Ozone Monitors -- monitor data, temporally adjusted " + forcastYear + " " + period;
                baseOutput.outputType = "Monitor Network";
                baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                if (File.Exists(_resultFilePath + @"\" + strFile))
                {
                    FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                    baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                }
                else
                    baseOutput.outputSize = 0;
                baseScenario.lstOutput.Add(baseOutput);
                dtOutMonitorControl.Clear();
                GC.Collect();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool SaveDicOzoneMonitorControlMax(Dictionary<string, OzoneMonitorControlMax> dicOzoneMonitorControlMax, BaseScenario baseScenario, string forcastYear)
        {
            //------------------OutputMonitorControl && OutputMonitorCountyHight----------
            //_id	_type	lat	long	date	b_o3_DV	f_o3_DV	referencecell	rrf	ppb	days	_state_name	_county_name
            if (!(baseScenario.configuration is OzoneAnalysisConfiguration))
            {
                return false;
            }
            try
            {
                OzoneAnalysisConfiguration ozoneAnalysisConfiguration = (baseScenario.configuration) as OzoneAnalysisConfiguration;
                DataTable dtOutMonitorControl = new DataTable();
                dtOutMonitorControl.Columns.Add("_id");
                dtOutMonitorControl.Columns.Add("_type");
                dtOutMonitorControl.Columns.Add("lat");
                dtOutMonitorControl.Columns.Add("long");
                dtOutMonitorControl.Columns.Add("date");
                dtOutMonitorControl.Columns.Add("b_o3_DV_Max");
                dtOutMonitorControl.Columns.Add("f_o3_DV_Max");
                dtOutMonitorControl.Columns.Add("referencecell");
                dtOutMonitorControl.Columns.Add("rrf");
                dtOutMonitorControl.Columns.Add("ppb");
                dtOutMonitorControl.Columns.Add("days");
                dtOutMonitorControl.Columns.Add("_state_name");
                dtOutMonitorControl.Columns.Add("_county_name");
                foreach (KeyValuePair<string, OzoneMonitorControlMax> k in dicOzoneMonitorControlMax)
                {
                    DataRow dr = dtOutMonitorControl.NewRow();
                    dr[0] = k.Value.id;
                    dr[1] = "";//---------少了type
                    dr[2] = k.Value.lat;
                    dr[3] = k.Value.longitude;
                    dr[4] = k.Value.data;//ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                    dr[5] = Math.Round(k.Value.ozonebase, 8);
                    dr[6] = Math.Round(k.Value.ozonecontrol, 8);
                    dr[7] = k.Value.referencecell;
                    dr[8] = Math.Round(k.Value.rrf, 8);
                    dr[9] = k.Value.ppb;
                    dr[10] = k.Value.days;
                    dr[11] = k.Value.state;
                    dr[12] = k.Value.county;
                    dtOutMonitorControl.Rows.Add(dr);
                }

                //------------修正OutPutFileName----------------
                string strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Ozone Monitors_Max -- temporally adjusted " + forcastYear + ".csv";

                CommonClass.SaveCSV(dtOutMonitorControl, _resultFilePath + @"\" + strFile, "Year");
                BaseOutput baseOutput = new BaseOutput();
                baseOutput.outputName = strFile.Replace(".csv", "");
                //baseOutput.outputName = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Ozone Monitors -- monitor data, temporally adjusted " + forcastYear + " " + period;
                baseOutput.outputType = "Monitor Network";
                baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                if (File.Exists(_resultFilePath + @"\" + strFile))
                {
                    FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                    baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                }
                else
                    baseOutput.outputSize = 0;
                baseScenario.lstOutput.Add(baseOutput);
                dtOutMonitorControl.Clear();
                GC.Collect();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Save Ozone OutPut
        /// </summary>
        /// <param name="dicOzoneMonitorControl"></param>
        /// <param name="baseScenario"></param>
        /// <returns></returns>
        public static bool SaveDicOzoneMonitorControlCounty(Dictionary<string, OzoneMonitorControl> dicOzoneMonitorControl, BaseScenario baseScenario, string forcastYear, string period)
        {
            //------------------OutputMonitorControl && OutputMonitorCountyHight----------
            //_id	_type	lat	long	date	b_o3_DV	f_o3_DV	referencecell	rrf	ppb	days	_state_name	_county_name
            if (!(baseScenario.configuration is OzoneAnalysisConfiguration))
            {
                return false;
            }
            try
            {
                OzoneAnalysisConfiguration ozoneAnalysisConfiguration = (baseScenario.configuration) as OzoneAnalysisConfiguration;
                DataTable dtOutMonitorControl = new DataTable();
                dtOutMonitorControl.Columns.Add("_id");
                dtOutMonitorControl.Columns.Add("_type");
                dtOutMonitorControl.Columns.Add("lat");
                dtOutMonitorControl.Columns.Add("long");
                dtOutMonitorControl.Columns.Add("date");
                dtOutMonitorControl.Columns.Add("b_o3_DV");
                dtOutMonitorControl.Columns.Add("f_o3_DV");
                dtOutMonitorControl.Columns.Add("referencecell");
                dtOutMonitorControl.Columns.Add("rrf");
                dtOutMonitorControl.Columns.Add("ppb");
                dtOutMonitorControl.Columns.Add("days");
                dtOutMonitorControl.Columns.Add("_state_name");
                dtOutMonitorControl.Columns.Add("_county_name");
                var query = dicOzoneMonitorControl.GroupBy(p => p.Value.state + " " + p.Value.county);
                string data = period == "" ? ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4) : Convert.ToString(Convert.ToInt16(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneStartYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneStartYear.Length - 4)) + Convert.ToInt16(period.Split(' ')[1]) - 1);
                foreach (var querygroup in query)
                {
                    if (querygroup.Count() > 0)
                    {
                        KeyValuePair<string, OzoneMonitorControl> k = querygroup.OrderByDescending(p => p.Value.ozonecontrol).First();
                        DataRow dr = dtOutMonitorControl.NewRow();
                        dr[0] = k.Value.id;
                        dr[1] = "";//---------少了type
                        dr[2] = k.Value.lat;
                        dr[3] = k.Value.longitude;
                        dr[4] = data;//ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Substring(ozoneAnalysisConfiguration.filteringInterpolationO.ozoneEndYear.Length - 4);//------------得重新计算date
                        dr[5] = Math.Round(k.Value.ozonebase, 6);
                        dr[6] = Math.Round(k.Value.ozonecontrol, 6);
                        dr[7] = k.Value.referencecell;
                        dr[8] = Math.Round(k.Value.rrf, 8);
                        dr[9] = k.Value.ppb;
                        dr[10] = k.Value.days;
                        dr[11] = k.Value.state;
                        dr[12] = k.Value.county;
                        dtOutMonitorControl.Rows.Add(dr);
                    }
                }


                //------------修正OutPutFileName----------------
                string strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Ozone Monitors -- county high monitoring sites, temporally adjusted " + forcastYear + " " + period + ".csv";

                CommonClass.SaveCSV(dtOutMonitorControl, _resultFilePath + @"\" + strFile, "Year");
                BaseOutput baseOutput = new BaseOutput();
                baseOutput.outputName = strFile.Replace(".csv", "");
                baseOutput.outputType = "Monitor Network";
                baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                if (File.Exists(_resultFilePath + @"\" + strFile))
                {
                    FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                    baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                }
                else
                    baseOutput.outputSize = 0;
                baseScenario.lstOutput.Add(baseOutput);
                dtOutMonitorControl.Clear();
                GC.Collect();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// output neighbor file spatial field
        /// </summary>
        /// <param name="baseScenario"></param>
        /// <param name="dicNeighbor"></param>
        /// <returns></returns>
        public static bool SaveOzoneNeighborFileSpatialField(BaseScenario baseScenario, Dictionary<string, NeighborFileClass> dicNeighbor)
        {
            try
            {
                OzoneAnalysisConfiguration ozoneAnalysisConfiguration = baseScenario.configuration as OzoneAnalysisConfiguration;
                //------------修正OutPutFileName----------------
                string strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Neighbor File Spatial Field.csv";
                FileStream fs = new FileStream(_resultFilePath + @"\" + strFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                sw.WriteLine("Year");
                string data = "";
                data += "_id";
                data += ",";
                data += "gridcell_lat";
                data += ",";
                data += "gridcell_long";
                data += ",";
                data += "neighbor";
                data += ",";
                data += "neighbor_gridcell";
                data += ",";
                data += "distance";
                data += ",";
                data += "weightdistance";
                data += ",";
                data += "weightdistancesquared";
                sw.WriteLine(data);

                double distanceSum = 0, distanceSquaredSum = 0;
                foreach (KeyValuePair<string, NeighborFileClass> k in dicNeighbor)
                {
                    distanceSum = 0; distanceSquaredSum = 0;
                    foreach (KeyValuePair<string, NeighborInfo> kin in k.Value.dicNeighbors)
                    {
                        distanceSum += 1.0000 / kin.Value.distance;
                        distanceSquaredSum += 1.0000 / Math.Pow(kin.Value.distance, 2);
                    }
                    foreach (KeyValuePair<string, NeighborInfo> kin in k.Value.dicNeighbors)
                    {
                        data = "";
                        data += k.Value.id;
                        data += ",";
                        data += Math.Round(k.Value.monitorLat, 6);
                        data += ",";
                        data += Math.Round(k.Value.monitorLong, 6);
                        data += ",";
                        data += kin.Value.neighbor;
                        data += ",";
                        data += kin.Value.neighbor_gridcell;
                        data += ",";
                        data += Math.Round(kin.Value.distance, 8);
                        data += ",";
                        data += Math.Round(1.0000 / kin.Value.distance / distanceSum, 9);
                        data += ",";
                        data += Math.Round(Math.Pow(1.0000 / kin.Value.distance, 2) / distanceSquaredSum, 9);
                        sw.WriteLine(data);
                    }
                }
                sw.Close();
                fs.Close();
                GC.Collect();

                BaseOutput baseOutput = new BaseOutput();
                baseOutput.outputName = strFile.Replace(".csv", "");
                baseOutput.outputType = "Monitor Network";
                baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                if (File.Exists(_resultFilePath + @"\" + strFile))
                {
                    FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                    baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                }
                else
                    baseOutput.outputSize = 0;
                baseScenario.lstOutput.Add(baseOutput);
                return true;
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
                return false;
            }

        }

        public static bool SaveOzoneQuarterlyModelData(BaseScenario baseScenario, Dictionary<string, OzoneModel> dicOzoneModel, string lastYear)
        {
            if (!(baseScenario.configuration is OzoneAnalysisConfiguration))
            {
                return false;
            }
            try
            {
                OzoneAnalysisConfiguration ozoneAnalysisConfiguration = baseScenario.configuration as OzoneAnalysisConfiguration;

                DataTable dt = new DataTable();
                dt.Columns.Add("_id");
                dt.Columns.Add("_type");
                dt.Columns.Add("lat");
                dt.Columns.Add("long");
                dt.Columns.Add("b_o3_used");
                dt.Columns.Add("f_o3_used");
                dt.Columns.Add("Delta(o3_used)");
                foreach (KeyValuePair<string, OzoneModel> k in dicOzoneModel)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = k.Value.id;
                    dr[1] = k.Value.type;
                    dr[2] = Math.Round(k.Value.lat, 6);
                    dr[3] = Math.Round(k.Value.longitude, 6);
                    dr[4] = Math.Round(k.Value.ozone, 8);
                    dr[5] = Math.Round(k.Value.futureOzone, 8);
                    if (k.Value.ozone >= 0 && k.Value.futureOzone >= 0)
                        dr[6] = Math.Round(k.Value.ozone - k.Value.futureOzone, 8);
                    else
                        dr[6] = 0;

                    dt.Rows.Add(dr);
                }

                //------------修正OutPutFileName----------------
                string strFile = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Base & Future Model Data - used average.csv";

                CommonClass.SaveCSV(dt, _resultFilePath + @"\" + strFile, "Year");
                BaseOutput baseOutput = new BaseOutput();
                baseOutput.outputName = strFile.Replace(".csv", "");
                //baseOutput.outputName = ozoneAnalysisConfiguration.chooseDesiredOutputO.scenarioName + " - Ozone Monitors -- monitor data, temporally adjusted " + forcastYear + " " + period;
                baseOutput.outputType = "Monitor Network";
                baseOutput.outputFilePath = _resultFilePath + @"\" + strFile;
                if (File.Exists(_resultFilePath + @"\" + strFile))
                {
                    FileInfo fileInfo = new FileInfo(_resultFilePath + @"\" + strFile);
                    baseOutput.outputSize = Convert.ToInt32(fileInfo.Length / 1024);
                }
                else
                    baseOutput.outputSize = 0;
                baseScenario.lstOutput.Add(baseOutput);
                dt.Clear();
                GC.Collect();
                return true;
            }
            catch (Exception ex)
            {
                CommonClass.LogError(ex);
                return false;
            }

        }

        [Obsolete("输出Ozone做DS分析的监测输入数据")]
        public static void SaveDSMonitorData(Dictionary<string, OzoneMonitorControl> dicOzoneDataOutput)
        {
            try
            {
                if (dicOzoneDataOutput.Count <= 0)
                    return;
                FileStream fs;
                StreamWriter streamWriter;
                StringBuilder sb = new StringBuilder();
                string filename = "1monitor.csv";
                string filepath = @"D:\SMAT_InputData\Ozone\";
                if (!Directory.Exists(filepath))
                    Directory.CreateDirectory(filepath);
                filepath += filename;
                if (File.Exists(filepath))
                    File.Delete(filepath);
                fs = new FileStream(filepath, FileMode.Create, FileAccess.Write);
                streamWriter = new StreamWriter(fs, Encoding.Default);
                sb.Append("Site,POC,Date,Lat,Lon,Conc");
                streamWriter.WriteLine(sb.ToString());
                foreach (KeyValuePair<string, OzoneMonitorControl> kvp in dicOzoneDataOutput)
                {
                    OzoneMonitorControl monitor = kvp.Value;
                    if (monitor.ozonebase < 0.0) continue;
                    sb.Clear();
                    sb.AppendFormat("{0},{1},{2},{3},{4},{5}", new object[] { "1", "1", "2011-1-1", monitor.lat, monitor.longitude, monitor.ozonebase });
                    streamWriter.WriteLine(sb.ToString());
                }
                streamWriter.Close();
                fs.Close();
                sb.Clear();
                GC.Collect();
            }
            catch
            {

            }
        }
        [Obsolete("输出Ozone做DS分析的模型输入数据")]
        public static void SaveDSModelData(Dictionary<string, OzoneModel> dicOzoneDataOutput)
        {
            try
            {
                if (dicOzoneDataOutput.Count <= 0)
                    return;
                FileStream fs;
                StreamWriter streamWriter;
                StringBuilder sb = new StringBuilder();
                string filename = "1model.csv";
                string filepath = @"D:\SMAT_InputData\Ozone\";
                if (!Directory.Exists(filepath))
                    Directory.CreateDirectory(filepath);
                filepath += filename;
                if (File.Exists(filepath))
                    File.Delete(filepath);
                fs = new FileStream(filepath, FileMode.Create, FileAccess.Write);
                streamWriter = new StreamWriter(fs, Encoding.Default);
                sb.Append("Date,Lat,Lon,Conc,id");
                streamWriter.WriteLine(sb.ToString());
                foreach (KeyValuePair<string, OzoneModel> kvp in dicOzoneDataOutput)
                {
                    OzoneModel model = kvp.Value;
                    if (model.ozone < 0.0) continue;
                    sb.Clear();
                    sb.AppendFormat("{0},{1},{2},{3},{4}", new object[] { "2011-1-1", model.lat, model.longitude, model.ozone, model.id });
                    streamWriter.WriteLine(sb.ToString());
                }
                streamWriter.Close();
                fs.Close();
                sb.Clear();
                GC.Collect();
            }
            catch
            {

            }
        }

    }

}
