コード例 #1
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            var vector = GetVector(Matrix);

            if (vector != null)
            {
                cancelProgressHandler.Progress("Package_Tool", 10, "Calculating...");
                var dt   = _FeatureSet.DataTable;
                var type = dt.Columns[_SelectedVarIndex].DataType;
                if (vector.Length == dt.Rows.Count)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        dt.Rows[i][ValueField] = Convert.ChangeType((vector[i]), type);
                    }
                }
                cancelProgressHandler.Progress("Package_Tool", 80, "Saving...");
                _FeatureSet.Save();
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #2
0
ファイル: SFR2.cs プロジェクト: zhaowilliam/Visual-HEIFLOW
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            var dt_stream = _stream_layer.DataTable;
            var segid = from dr in dt_stream.AsEnumerable() select (dr.Field<int>(SegmentField) + 1);
            var dic = Path.GetDirectoryName(_stream_layer.FilePath);
            var out_fn = Path.Combine(dic, "sfr_cpm.shp");
            string msg="";
            Dictionary<int, ReachFeatureCollection> fea_list = new Dictionary<int, ReachFeatureCollection>();

            foreach(var id in segid)
            {
                fea_list.Add(id, new ReachFeatureCollection(id));
            }
              cancelProgressHandler.Progress("Package_Tool", 10, "Calculating...");
              if (StreamGridInctLayer != null)
                  _out_sfr_layer = StreamGridInctLayer.DataSet as FeatureSet;
              else
              {
                  _out_sfr_layer = _stream_layer.Intersection1(_grid_layer, FieldJoinType.All, null);
                  _out_sfr_layer.Projection = _stream_layer.Projection;
                  _out_sfr_layer.SaveAs(out_fn, true);
              }
            cancelProgressHandler.Progress("Package_Tool", 30, "Calculation of intersectons between Grid and Stream finished");
            PrePro(fea_list, out msg);
            cancelProgressHandler.Progress("Package_Tool", 70, "Calculation of reach parameters finished");
            if(msg != "")
                cancelProgressHandler.Progress("Package_Tool", 80, "Warnings: " + msg);
            Save2SFRFile(fea_list);

            cancelProgressHandler.Progress("Package_Tool", 90, "SFR file saved");
            return true;
        }
コード例 #3
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            int nstep    = 0;
            var xx       = _XVariable.GetData() as float[];
            var yy       = _YVariable.GetData() as float[];
            var nc_array = _SelectedVariable.GetData() as float[, , ];
            var time     = _TimeVariable.GetData() as float[];

            if (time != null)
            {
                nstep = time.Count();
            }
            else
            {
                var tt = _TimeVariable.GetData() as double[];
                if (tt != null)
                {
                    nstep = tt.Length;
                }
                else
                {
                    var t1 = _TimeVariable.GetData() as int[];
                    if (t1 != null)
                    {
                        nstep = t1.Length;
                    }
                }
            }
            int          progress   = 0;
            var          numColumns = xx.Length;
            var          numRows    = yy.Length;
            Extent       extent     = new Extent(0, -90, 360, 90);
            RasterBounds bound      = new RasterBounds(numRows, numColumns, extent);

            if (nc_array != null)
            {
                for (int t = 0; t < nstep; t++)
                {
                    var fn     = Path.Combine(OutputFolder, (t + 1) + ".tif");
                    var raster = Raster.CreateRaster(fn, string.Empty, numColumns, numRows, 1, typeof(float), new[] { string.Empty });
                    raster.Bounds     = bound;
                    raster.Projection = Projection;
                    for (int row = 0; row < numRows; row++)
                    {
                        for (int j = 0; j < numColumns; j++)
                        {
                            if (nc_array[t, row, j] > 0)
                            {
                                raster.Value[row, j] = nc_array[t, row, j];
                            }
                        }
                    }
                    raster.Save();
                    progress = t * 100 / nstep;
                    cancelProgressHandler.Progress("Package_Tool", progress, "Processing time step:" + t);
                }
            }
            return(true);
        }
コード例 #4
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            StreamReader sr   = new StreamReader(DataFileName);
            string       line = sr.ReadLine();

            line = sr.ReadLine();
            var buf      = TypeConverterEx.Split <string>(line.Trim());
            int ncell    = int.Parse(buf[1]);
            var var_name = buf[0];

            line = sr.ReadLine();
            int nstep    = 0;
            int progress = 0;
            int count    = 1;

            while (!sr.EndOfStream)
            {
                line = sr.ReadLine();
                if (!TypeConverterEx.IsNull(line))
                {
                    nstep++;
                }
            }
            sr.Close();

            var mat_out = new DataCube <float>(1, nstep, ncell);

            mat_out.Name      = OutputMatrix;
            mat_out.Variables = new string[] { var_name };
            sr = new StreamReader(DataFileName);
            mat_out.DateTimes = new DateTime[nstep];
            for (int i = 0; i < 3; i++)
            {
                sr.ReadLine();
            }

            for (int t = 0; t < nstep; t++)
            {
                line = sr.ReadLine();
                var vec = TypeConverterEx.SkipSplit <float>(line, 6);
                mat_out[0, t.ToString(), ":"] = vec;
                var dd = TypeConverterEx.Split <int>(line, 3);
                mat_out.DateTimes [t] = new DateTime(dd[0], dd[1], dd[2]);
                progress = t * 100 / nstep;
                if (progress > count)
                {
                    cancelProgressHandler.Progress("Package_Tool", progress, "Processing step:" + (t + 1));
                    count++;
                }
            }
            Workspace.Add(mat_out);
            return(true);
        }
コード例 #5
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet fs = null;

            if (!TypeConverterEx.IsNull(PointFeatureFileName) && File.Exists(PointFeatureFileName))
            {
                fs = FeatureSet.Open(PointFeatureFileName);
            }
            if (fs != null)
            {
                var          npt      = fs.NumRows();
                Coordinate[] coors    = new Coordinate[npt];
                int          progress = 0;
                for (int i = 0; i < npt; i++)
                {
                    var geo_pt = fs.GetFeature(i).Geometry;
                    coors[i] = geo_pt.Coordinate;
                }
                var time     = _TimeVariable.GetData() as float[];
                var xx       = _XVariable.GetData() as float[];
                var yy       = _YVariable.GetData() as float[];
                var nc_array = _SelectedVariable.GetData() as float[, , ];
                int nstep    = time.Count();
                var mat_out  = new DataCube <float>(1, time.Length, npt);
                mat_out.Name      = OutputMatrix;
                mat_out.Variables = new string[] { _SelectedVariableName };
                mat_out.DateTimes = new DateTime[nstep];

                var pt_index = GetIndex(xx, yy, coors);
                for (int t = 0; t < nstep; t++)
                {
                    for (int i = 0; i < npt; i++)
                    {
                        mat_out[0, t, i] = nc_array[t, pt_index[i][1], pt_index[i][0]];
                    }
                    progress = t * 100 / nstep;
                    cancelProgressHandler.Progress("Package_Tool", progress, "Processing time step:" + t);

                    mat_out.DateTimes[t] = DateTime.FromOADate(time[t]);
                }

                Workspace.Add(mat_out);
                return(true);
            }
            else
            {
                cancelProgressHandler.Progress("Package_Tool", 50, "Failed to run. The input parameters are incorrect.");
                return(false);
            }
        }
コード例 #6
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            cancelProgressHandler.Progress("Package_Tool", 10, "Begin to calculate");
            PenmanMonteithET pet = new PenmanMonteithET();
            StreamReader     sr  = new StreamReader(InputDataFile);
            List <float>     et0 = new List <float>();
            int nrow             = 0;

            sr = new StreamReader(InputDataFile);
            List <DateTime> dates = new List <DateTime>();
            List <float[]>  meto  = new List <float[]>();
            List <float>    tav   = new List <float>();

            while (!sr.EndOfStream)
            {
                var line = sr.ReadLine();
                if (!TypeConverterEx.IsNull(line))
                {
                    var strs = TypeConverterEx.Split <string>(line);
                    var date = DateTime.Parse(strs[0]);
                    var vv   = TypeConverterEx.SkipSplit <float>(line, 1);
                    dates.Add(date);
                    meto.Add(vv);
                    tav.Add(vv[0]);
                    nrow++;
                }
            }
            sr.Close();

            var ts      = new DataCube <float>(tav.ToArray(), dates.ToArray());
            var tav_mon = TimeSeriesAnalyzer.GetMonthlyMean(ts, NumericalDataType.Average);

            pet.MonthTemperature = Array.ConvertAll(tav_mon, x => (double)x);
            for (int i = 0; i < nrow; i++)
            {
                var vv = meto[i];
                et0.Add((float)pet.ET0(Latitude, Longitude, vv[0], vv[1], vv[2], vv[3], vv[4], vv[5], dates[i], CloudCover));
            }
            DataCube <float> mat_out = new DataCube <float>(1, 1, et0.Count);

            mat_out[0, "0", ":"] = et0.ToArray();
            mat_out.Name         = PET;
            cancelProgressHandler.Progress("Package_Tool", 100, "Calculated");
            Workspace.Add(mat_out);
            return(true);
        }
コード例 #7
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            int          nseg       = 0;
            string       div_out    = DiversionFileName + "_report.out";
            StreamReader sr_div     = new StreamReader(DiversionFileName);
            StreamWriter sw_div_out = new StreamWriter(div_out);

            var line = sr_div.ReadLine();

            line = sr_div.ReadLine();
            var div_buf = TypeConverterEx.Split <string>(line);

            nseg = int.Parse(div_buf[0]);

            sw_div_out.WriteLine("HRU_ID\tNHRU\tSumOfRatio");
            for (int i = 0; i < nseg; i++)
            {
                line    = sr_div.ReadLine();
                div_buf = TypeConverterEx.Split <string>(line);
                int hru_id = int.Parse(div_buf[0]);
                int nhru   = int.Parse(div_buf[1]);
                if (nhru > 0)
                {
                    line = sr_div.ReadLine();
                    line = sr_div.ReadLine();
                    var buf = TypeConverterEx.Split <double>(line);
                    var sum = buf.Sum();
                    sr_div.ReadLine();
                    sr_div.ReadLine();
                    var newline = string.Format("{0}\t{1}\t{2}", hru_id, nhru, sum);
                    sw_div_out.WriteLine(newline);
                }
                else
                {
                    var newline = string.Format("{0}\t{1}\t{2}", hru_id, nhru, 0);
                    sw_div_out.WriteLine(newline);
                }
            }
            sr_div.Close();
            sw_div_out.Close();
            cancelProgressHandler.Progress("Package_Tool", 100, "Done");
            return(true);
        }
コード例 #8
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            var          var_index = 0;
            var          mat       = Get3DMat(Source, ref var_index);
            int          progress  = 0;
            int          nstep     = mat.Size[1];
            StreamWriter sw        = new StreamWriter(OutputFileName);
            string       line      = "";

            for (int t = 0; t < nstep; t++)
            {
                var vec = mat.GetVector(var_index, t.ToString(), ":");
                line = string.Join("\t", vec);
                sw.WriteLine(line);
                progress = t * 100 / nstep;
                cancelProgressHandler.Progress("Package_Tool", progress, "Processing step:" + t);
            }
            sw.Close();
            return(true);
        }
コード例 #9
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            var dt = _FeatureSet.DataTable;
            var dv = new DataView(dt);

            dv.Sort = SortingField + " asc";
            //  dt = dv.ToTable();

            string[] fields = new string[] { "Cell_ID", "Row", "Column" };
            double   prg    = 0;

            foreach (var str in fields)
            {
                if (dt.Columns.Contains(str))
                {
                    dt.Columns.Remove(str);
                }
                DataColumn dc = new DataColumn(str, Type.GetType("System.Int64"));
                dt.Columns.Add(dc);
            }

            int index = 0;

            for (int i = 0; i < RowCount; i++)
            {
                for (int j = 0; j < ColumnCount; j++)
                {
                    var dr = dt.Rows[index];
                    dr["Cell_ID"] = index + 1;
                    dr["Row"]     = i + 1;
                    dr["Column"]  = j + 1;
                    index++;
                }
                prg = (i + 1) * 100.0 / RowCount;
                cancelProgressHandler.Progress("Package_Tool", (int)prg, "Processing Row: " + (i + 1));
            }
            _FeatureSet.Save();
            return(true);
        }
コード例 #10
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            //SaveObj();
            //return true;
            EcoDemandFile = @"E:\Project\HRB\水库调度\Process\WithDraw Input File\eco_demand_full.csv";
            int[]    mid_zone_id = new int[] { 10, 11, 12, 13, 14, 15, 16, 17, 18, 22, 23, 24, 25, 28, 29, 30, 31 };
            string[] quo_fn      = new string[] { @"E:\Project\HRB\水库调度\Process\WithDraw Input File\unit2000.txt",
                                                  @"E:\Project\HRB\水库调度\Process\WithDraw Input File\unit2007.txt",
                                                  @"E:\Project\HRB\水库调度\Process\WithDraw Input File\unit2011.txt" };
            string out_dic = @"E:\Project\HRB\水库调度\Scenario\2018-7-29\";

            string[] folders = new string[] { "SLN0", "SLN1", "SLN2", "SLN3_GW" };

            //for (int f = 0; f < 4; f++)
            //{
            int f = 3;

            EcoSolutionColIndex = 3;
            for (int k = 0; k < 3; k++)
            {
                QuotaFileName = quo_fn[k];
                if (k == 0)
                {
                    StartCycle     = 1;
                    EndCycle       = 4;
                    OutputFileName = out_dic + folders[f] + "\\HRB_wra_2000.unit";
                }
                else if (k == 1)
                {
                    StartCycle     = 5;
                    EndCycle       = 10;
                    OutputFileName = out_dic + folders[f] + "\\HRB_wra_2007.unit";
                }
                else if (k == 2)
                {
                    StartCycle     = 11;
                    EndCycle       = 13;
                    OutputFileName = out_dic + folders[f] + "\\HRB_wra_2011.unit";
                }

                bool     has_ecodemand = false;
                int      num_well_layer = 3;
                int[]    well_layer = new int[] { 1, 2, 3 };
                double[] layer_ratio = new double[] { 0.6, 0.1, 0.3 };
                int      num_irrg_obj, num_indust_obj;
                float[,] eco_demand = null;

                StreamReader sr_quota = new StreamReader(QuotaFileName);
                StreamWriter sw_out   = new StreamWriter(OutputFileName);
                string       newline  = "";

                if (TypeConverterEx.IsNotNull(EcoDemandFile))
                {
                    CSVFileStream csv = new CSVFileStream(EcoDemandFile);
                    csv.HasHeader = false;
                    eco_demand    = csv.LoadFloatMatrix();
                    has_ecodemand = true;
                }

                int nquota = 1;
                int ntime  = 36;
                var line   = sr_quota.ReadLine();

                var strs_buf = TypeConverterEx.Split <string>(line);
                nquota = int.Parse(strs_buf[0]);
                ntime  = int.Parse(strs_buf[1]);
                double[,] quota_src = new double[ntime, nquota];
                double[,] quota     = new double[366, nquota];
                int day   = 0;
                var start = new DateTime(2000, 1, 1);
                for (int i = 0; i < ntime; i++)
                {
                    line = sr_quota.ReadLine().Trim();
                    var buf  = TypeConverterEx.Split <string>(line);
                    var ss   = DateTime.Parse(buf[0]);
                    var ee   = DateTime.Parse(buf[1]);
                    var cur  = ss;
                    var step = (ee - ss).Days + 1;
                    while (cur <= ee)
                    {
                        for (int j = 0; j < nquota; j++)
                        {
                            quota[day, j] = System.Math.Round(double.Parse(buf[2 + j]) / step, 2);
                        }
                        day++;
                        cur = cur.AddDays(1);
                    }
                }

                line = sr_quota.ReadLine().Trim();
                var inttemp = TypeConverterEx.Split <int>(line.Trim());
                num_irrg_obj   = inttemp[0];
                num_indust_obj = inttemp[1];
                //ID	NAME	地表水比例  用水类型  允许降深
                line = sr_quota.ReadLine();
                irrg_obj_list.Clear();
                indust_obj_list.Clear();
                ReadObj(sr_quota, num_irrg_obj, irrg_obj_list);
                ReadObj(sr_quota, num_indust_obj, indust_obj_list);

                newline = "# Water resources allocation package " + DateTime.Now;
                sw_out.WriteLine(newline);
                newline = string.Format("{0}\t{1}\t0\t0\t # num_irrg_obj, num_indu_obj, num_doms_obj, num_ecos_obj ", num_irrg_obj, num_indust_obj);
                sw_out.WriteLine(newline);

                sw_out.WriteLine("# irrigation objects");
                for (int i = 0; i < num_irrg_obj; i++)
                {
                    var obj = irrg_obj_list[i];
                    int oid = i + 1;
                    newline = string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t#	oid, hrunum, iseg, ireach, num_well_layer, inlet_type {6}", obj.ID, obj.HRU_Num, obj.SegID, obj.ReachID, num_well_layer, obj.Inlet_Type, obj.Name);
                    sw_out.WriteLine(newline);
                    newline = string.Join("\t", obj.HRU_List);
                    sw_out.WriteLine(newline);
                    var canal_eff   = new double[obj.HRU_Num];
                    var canal_ratio = new double[obj.HRU_Num];
                    for (int j = 0; j < obj.HRU_Num; j++)
                    {
                        canal_eff[j]   = obj.Canal_Efficiency;
                        canal_ratio[j] = obj.Canal_Ratio;
                    }
                    newline = string.Join("\t", canal_eff);
                    sw_out.WriteLine(newline);
                    newline = string.Join("\t", canal_ratio);
                    sw_out.WriteLine(newline);
                    for (int j = 0; j < num_well_layer; j++)
                    {
                        newline = well_layer[j] + "\t" + layer_ratio[j] + " # well_layer layer_ratio";
                        sw_out.WriteLine(newline);
                    }
                    newline = string.Format("{0}\t#	drawdown constaint of object {1}", irrg_obj_list[i].Drawdown, oid);
                    sw_out.WriteLine(newline);
                    newline = string.Format("{0}\t{1}\t{2}\t#  inlet	min flow,  max flow and flow ratio  for object {3}", irrg_obj_list[i].Inlet_MinFlow, irrg_obj_list[i].Inlet_MaxFlow, irrg_obj_list[i].Inlet_Flow_Ratio,
                                            irrg_obj_list[i].ID);
                    sw_out.WriteLine(newline);
                }
                sw_out.WriteLine("# industrial objects");
                for (int i = 0; i < num_indust_obj; i++)
                {
                    var obj = indust_obj_list[i];
                    newline = string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t#	oid, hrunum, iseg, ireach, num_well_layer, inlet_type {6}", obj.ID, obj.HRU_Num, obj.SegID, obj.ReachID, num_well_layer,
                                            obj.Inlet_Type, obj.Name);
                    sw_out.WriteLine(newline);
                    newline = string.Format("{0}\t#	hru_id_list", string.Join(" ", obj.HRU_List));
                    sw_out.WriteLine(newline);
                    for (int j = 0; j < num_well_layer; j++)
                    {
                        newline = well_layer[j] + "\t" + layer_ratio[j] + " # well_layer layer_ratio";
                        sw_out.WriteLine(newline);
                    }
                    newline = string.Format("{0}\t#	drawdown constaint of object {1}", obj.Drawdown, obj.ID);
                    sw_out.WriteLine(newline);
                    newline = string.Format("{0}\t{1}\t{2}\t#  inlet	min flow,  max flow and flow ratio for object {3}", obj.Inlet_MinFlow, obj.Inlet_MaxFlow, obj.Inlet_Flow_Ratio, obj.ID);
                    sw_out.WriteLine(newline);
                    newline = string.Format("{0}\t#	return_ratio", 0);
                    sw_out.WriteLine(newline);
                }

                sw_out.WriteLine(StartCycle + " # cycle index");
                sw_out.WriteLine("1	#	quota_flag");

                //if (has_ecodemand)
                //{
                //    for (int i = 0; i < nquota; i++)
                //    {
                //        for (int j = 0; j < 366; j++)
                //        {
                //            if (eco_demand[j, EcoSolutionColIndex] > 0)
                //                quota[j, i] = 0;
                //        }
                //    }
                //}
                for (int i = 0; i < nquota; i++)
                {
                    newline = "";
                    for (int j = 0; j < 366; j++)
                    {
                        newline += quota[j, i].ToString("0.0") + "\t";
                    }
                    newline += "quota of object " + (i + 1);
                    sw_out.WriteLine(newline);
                }

                newline = "# irrigation objects";
                sw_out.WriteLine(newline);
                newline = "1 1	1	1	1 #	sw_ratio_flag, swctrl_factor_flag , gwctrl_factor_flag, Withdraw_type_flag,plantarea_flag";
                sw_out.WriteLine(newline);
                //地表水比例
                for (int i = 0; i < num_irrg_obj; i++)
                {
                    var ratio = irrg_obj_list[i].SW_Ratio;
                    //if (mid_zone_id.Contains(irrg_obj_list[i].ID))
                    //{
                    //    ratio = ratio * sw_scale[k];
                    //}
                    newline = "";
                    for (int j = 0; j < 366; j++)
                    {
                        newline += ratio.ToString("0.00") + "\t";
                    }
                    newline += "#SW ratio of object " + irrg_obj_list[i].ID;
                    sw_out.WriteLine(newline);
                }
                //地表引水控制系数
                for (int i = 0; i < num_irrg_obj; i++)
                {
                    if (mid_zone_id.Contains(irrg_obj_list[i].ID) && has_ecodemand)
                    {
                        string str = "";
                        for (int j = 0; j < 366; j++)
                        {
                            if (eco_demand[j, EcoSolutionColIndex] > 0)
                            {
                                str += "0\t";
                            }
                            else
                            {
                                str += "1\t";
                            }
                        }
                        newline = string.Format("{0}\t#SW control factor of object {1}", str, irrg_obj_list[i].ID);
                        sw_out.WriteLine(newline);
                    }
                    else
                    {
                        newline = string.Format("{0}\t#SW control factor of object {1}", irrg_obj_list[i].SW_Cntl_Factor, irrg_obj_list[i].ID);
                        sw_out.WriteLine(newline);
                    }
                }
                //地下引水控制系数
                for (int i = 0; i < num_irrg_obj; i++)
                {
                    newline = string.Format("{0}\t#GW control factor of object {1}", irrg_obj_list[i].GW_Cntl_Factor, irrg_obj_list[i].ID);
                    sw_out.WriteLine(newline);
                }
                //作物类型
                for (int i = 0; i < num_irrg_obj; i++)
                {
                    newline = "";
                    for (int j = 0; j < irrg_obj_list[i].HRU_Num; j++)
                    {
                        newline += irrg_obj_list[i].ObjType + "\t";
                    }
                    newline += "# Plant type of object " + (i + 1);
                    sw_out.WriteLine(newline);
                }
                //种植面积
                for (int i = 0; i < num_irrg_obj; i++)
                {
                    newline  = string.Join("\t", irrg_obj_list[i].HRU_Area);
                    newline += "\t" + "# Plant area of object " + irrg_obj_list[i].ID;
                    sw_out.WriteLine(newline);
                }

                newline = "# industrial objects";
                sw_out.WriteLine(newline);
                newline = "1 1	1	1	1 #	sw_ratio_flag, swctrl_factor_flag , gwctrl_factor_flag, Withdraw_type_flag";
                sw_out.WriteLine(newline);

                for (int i = 0; i < num_indust_obj; i++)
                {
                    newline = "";
                    var control = 1;
                    for (int j = 0; j < 366; j++)
                    {
                        newline += control + "\t";
                    }
                    newline += "# SW control factor of object " + (indust_obj_list[i].ID);
                    sw_out.WriteLine(newline);
                }

                //地表引水控制系数
                for (int i = 0; i < num_indust_obj; i++)
                {
                    newline = string.Format("{0}\t#SW control factor of object {1}", indust_obj_list[i].SW_Cntl_Factor, indust_obj_list[i].ID);
                    sw_out.WriteLine(newline);
                }

                //地下引水控制系数
                for (int i = 0; i < num_indust_obj; i++)
                {
                    newline = string.Format("{0}\t#GW control factor of object {1}", indust_obj_list[i].GW_Cntl_Factor, indust_obj_list[i].ID);
                    sw_out.WriteLine(newline);
                }

                //用水类型
                for (int i = 0; i < num_indust_obj; i++)
                {
                    var obj = indust_obj_list[i];
                    newline = string.Format("{0} # Withdraw type of object {1}", obj.ObjType, obj.ID);
                    sw_out.WriteLine(newline);
                }

                for (int i = StartCycle + 1; i <= EndCycle; i++)
                {
                    sw_out.WriteLine(i + " # cycle index");
                    sw_out.WriteLine("-1 # quota_flag");
                    sw_out.WriteLine("# irrigation objects");
                    sw_out.WriteLine("-1 -1	-1	-1	-1  #	sw_ratio_flag, swctrl_factor_flag , gwctrl_factor_flag, Withdraw_type_flag,plantarea_flag");
                    sw_out.WriteLine("# industrial objects");
                    sw_out.WriteLine("-1 -1	-1	-1	-1  #	sw_ratio_flag, swctrl_factor_flag , gwctrl_factor_flag, Withdraw_type_flag");
                }

                sr_quota.Close();
                sw_out.Close();
                cancelProgressHandler.Progress("Package_Tool", 100, "Done");
            }
            //}
            return(true);
        }
コード例 #11
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            StreamReader sr   = new StreamReader(TimeStampsFileName);
            var          line = sr.ReadLine().Trim();

            DataCubeDescriptor descriptor = new DataCubeDescriptor();
            int steps = 0;
            int ncell = 0;

            while (!sr.EndOfStream)
            {
                line = sr.ReadLine();
                if (TypeConverterEx.IsNull(line))
                {
                    break;
                }
                steps++;
            }
            sr.Close();

            descriptor.NTimeStep  = steps;
            descriptor.NVar       = this.NVar;
            descriptor.TimeStamps = new DateTime[steps];

            sr   = new StreamReader(TimeStampsFileName);
            line = sr.ReadLine();
            DateTime cur = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

            for (int i = 0; i < steps; i++)
            {
                line = sr.ReadLine().Trim();
                DateTime.TryParse(line, out cur);
                descriptor.TimeStamps[i] = cur;
                cur = cur.AddDays(i);
            }
            sr.Close();

            if (File.Exists(CoordinateFileName))
            {
                sr   = new StreamReader(CoordinateFileName);
                line = sr.ReadLine().Trim();
                var buf = TypeConverterEx.Split <string>(line);
                if (buf.Length == 2)
                {
                    while (!sr.EndOfStream)
                    {
                        line = sr.ReadLine();
                        if (TypeConverterEx.IsNull(line))
                        {
                            break;
                        }
                        ncell++;
                    }
                    sr.Close();

                    descriptor.NCell = ncell;
                    descriptor.XCoor = new double[ncell];
                    descriptor.YCoor = new double[ncell];
                    sr   = new StreamReader(CoordinateFileName);
                    line = sr.ReadLine();
                    for (int i = 0; i < ncell; i++)
                    {
                        line = sr.ReadLine().Trim();
                        var vv = TypeConverterEx.Split <double>(line);
                        descriptor.XCoor[i] = vv[0];
                        descriptor.YCoor[i] = vv[1];
                    }
                    sr.Close();
                }
            }
            DataCubeDescriptor.Serialize(DcxFileName + ".xml", descriptor);
            return(true);
        }
コード例 #12
0
 public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
 {
     return(false);
 }
コード例 #13
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            //nc_out = new NetCDFDataSet("e:\\test.nc", Microsoft.Research.Science.Data.ResourceOpenMode.Create);
            //float[] xx = new float[10];
            //float[] yy = new float[10];
            //float[] dates = new float[2];
            //var var_name = "test";
            //var mat1 = new float[2, 10, 10];

            //nc_out.AddVariable(typeof(float), "longitude", xx, new string[] { "longitude", });
            //nc_out.AddVariable(typeof(float), "latitude", yy, new string[] { "latitude" });
            //var dt = nc_out.AddVariable(typeof(float), "time", dates, new string[] { "time" });
            //var test = nc_out.AddVariable(typeof(float), var_name, mat1, new string[] { "time", "latitude", "longitude" });
            //nc_out.Commit();
            //var newmat = new float[1, 10, 10];

            //dt.Append(new float[1]);
            //test.Append(newmat);
            //nc_out.Commit();
            //    return true;

            var var_index = 0;
            var mat       = Get3DMat(Source, ref var_index);
            int progress  = 0;
            int nsteps    = mat.Size[1];

            var grid   = ProjectService.Project.Model.Grid as RegularGrid;
            var lonlat = grid.GetLonLatAxis();

            var times = new float[nsteps];

            if (mat.DateTimes != null)
            {
                for (int t = 0; t < nsteps; t++)
                {
                    times[t] = mat.DateTimes[t].ToFileTime();
                }
            }
            else
            {
                for (int t = 0; t < nsteps; t++)
                {
                    times[t] = DateTime.Now.AddDays(t).ToFileTime();
                }
            }
            var mat_step = grid.To3DMatrix <float>(mat[var_index, "0", ":"], 0);

            nc_out = new NetCDFDataSet("e:\\test.nc");
            //   nc_out = new NetCDFDataSet(OutputFileName);
            nc_out.AddVariable(typeof(float), "longitude", lonlat[0], new string[] { "longitude", });
            nc_out.AddVariable(typeof(float), "latitude", lonlat[1], new string[] { "latitude" });
            var nc_dt  = nc_out.AddVariable(typeof(float), "time", new float[] { times[0] }, new string[] { "time" });
            var nc_var = nc_out.AddVariable(typeof(float), VariableName, mat_step, new string[] { "time", "latitude", "longitude" });

            nc_out.Commit();
            for (int t = 1; t < nsteps; t++)
            {
                mat_step = grid.To3DMatrix <float>(mat[var_index, "0", ":"], t);
                nc_var.Append(mat_step);
                nc_dt.Append(new float[] { times[t] });
                nc_out.Commit();

                progress = t * 100 / nsteps;
                cancelProgressHandler.Progress("Package_Tool", progress, "Processing step:" + t);
            }
            return(true);
        }
コード例 #14
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet      fs            = FeatureSet.Open(FeatureFile);
            int              var_index     = 0;
            int              con_var_index = 0;
            var              mat           = Get3DMat(Matrix, ref var_index);
            DataCube <float> con_mat       = null;

            if (Filter != FilterMode.None)
            {
                con_mat = Get3DMat(ConMat, ref con_var_index);
            }
            if (fs != null && mat != null)
            {
                IRaster raster = Raster.Open(TemplateFile);
                raster.SaveAs(TemplateFile + ".tif");
                int          fea_count = fs.NumRows();
                Coordinate[] coors     = new Coordinate[fea_count];
                for (int i = 0; i < fea_count; i++)
                {
                    coors[i] = fs.GetFeature(i).Geometry.Coordinates[0];
                }
                var      nsteps   = mat.Size[1];
                int      progress = 0;
                string[] fns      = new string[nsteps];
                if (mat.DateTimes != null)
                {
                    for (int t = 0; t < nsteps; t++)
                    {
                        fns[t] = string.Format("{0}_{1}.tif", VariableName, mat.DateTimes[t].ToString(DateFormat));
                    }
                }
                else
                {
                    for (int t = 0; t < nsteps; t++)
                    {
                        fns[t] = string.Format("{0}_{1}.tif", VariableName, t.ToString("0000"));
                    }
                }
                if (Filter != FilterMode.None)
                {
                    for (int t = 0; t < nsteps; t++)
                    {
                        string outras = Path.Combine(Direcotry, fns[t]);
                        int    i      = 0;
                        foreach (var cor in coors)
                        {
                            var cell = raster.ProjToCell(cor);
                            var temp = mat[var_index, t, i] * Scale;

                            if (Filter == FilterMode.Maximum)
                            {
                                if (temp > con_mat[0, 0, i])
                                {
                                    temp = con_mat[0, 0, i];
                                }
                            }
                            else if (Filter == FilterMode.Minimum)
                            {
                                if (temp < con_mat[0, 0, i])
                                {
                                    temp = con_mat[0, 0, i];
                                }
                            }

                            raster.Value[cell.Row, cell.Column] = temp;
                            i++;
                        }
                        raster.SaveAs(outras);

                        progress = t * 100 / nsteps;
                        cancelProgressHandler.Progress("Package_Tool", progress, "Saving raster to:" + outras);
                    }
                }
                else
                {
                    for (int t = 0; t < nsteps; t++)
                    {
                        string outras = Path.Combine(Direcotry, fns[t]);
                        int    i      = 0;
                        foreach (var cor in coors)
                        {
                            var cell = raster.ProjToCell(cor.X - 500, cor.Y + 500);
                            var temp = mat[var_index, t, i] * Scale;
                            raster.Value[cell.Row, cell.Column] = temp;
                            i++;
                        }
                        raster.SaveAs(outras);

                        progress = t * 100 / nsteps;
                        cancelProgressHandler.Progress("Package_Tool", progress, "Saving raster to:" + outras);
                    }
                }
                return(true);
            }
            else
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "Failed to run. The input parameters are incorrect.");
                return(false);
            }
        }
コード例 #15
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            int progress = 0;
            int count    = 1;
            int ndays    = 174;

            if (senseor == 5)
            {
                ndays = 174;
            }
            else
            {
                ndays = 56;
            }
            //string lake_centroid = @"E:\Project\HRB\Badan Jarian\Data\Geospatial\mask_centroid.shp";
            string    lake_centroid    = @"E:\Project\HRB\Badan Jarian\Data\Geospatial\mask_centroid_selected.shp";
            var       lake_centroid_fs = FeatureSet.Open(lake_centroid);
            DataTable centroid_dt      = lake_centroid_fs.DataTable;
            //var lake_list = (from DataRow dr in centroid_dt.Rows where dr["Flag"].ToString() == "1" select int.Parse(dr["Id"].ToString())).ToList();
            // var lake_list = new int[] { 1,18,19,28,30,35,41,49,50,55,57,58,59,60,63,89,91,97,99,100,112,113,118,133,135,136,160,169,181,183};
            var lake_list = new int[] { 59 };
            int nlakes    = lake_list.Length;

            double [,] water_area     = new double[ndays, nlakes];
            double[,] water_bond_area = new double[ndays, nlakes];

            for (int K = 0; K < nlakes; K++)
            {
                int lake_id = lake_list[K];
                var dr_lake = (from DataRow dr in centroid_dt.Rows where dr["Id"].ToString() == lake_id.ToString() select dr).First();

                string       img_dir      = Path.Combine(FileDirectory, lake_id.ToString());
                StreamReader sr_date_list = new StreamReader(Path.Combine(img_dir, "date_list.txt"));
                int          nfile        = 0;
                while (!sr_date_list.EndOfStream)
                {
                    sr_date_list.ReadLine();
                    nfile++;
                }
                sr_date_list.Close();
                sr_date_list = new StreamReader(Path.Combine(img_dir, "date_list.txt"));
                string[] dirs = new string[nfile];
                for (int i = 0; i < nfile; i++)
                {
                    var str = sr_date_list.ReadLine();
                    dirs[i] = Path.Combine(img_dir, str + "_cmb.tif");
                }

                string       class_file_list = Path.Combine(img_dir, @"class\class_list.txt");
                StreamWriter sw_area         = new StreamWriter(Path.Combine(img_dir, "class\\area.csv"));
                FileStream   fs_class        = new FileStream(class_file_list, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader sr_class_file   = new StreamReader(fs_class);
                var          center_pt       = new Coordinate(double.Parse(dr_lake["X"].ToString()), double.Parse(dr_lake["Y"].ToString()));
                int          cell_area       = 5 * 5;
                int          date_index      = 0;
                try
                {
                    foreach (var file in dirs)
                    {
                        int     water_cell_count       = 0;
                        int     water_bound_cell_count = 0;
                        var     temp       = Path.GetFileNameWithoutExtension(file);
                        var     daystr     = temp.Remove(10);
                        var     water_file = file.Replace("_cmb", "_water");
                        IRaster raster2    = Raster.OpenFile(file);
                        raster2.SaveAs(water_file);
                        IRaster raster_water = Raster.OpenFile(water_file);

                        var class_file = sr_class_file.ReadLine();
                        var class_mat  = ReadClassFile(class_file, raster2.NumRows, raster2.NumColumns);

                        for (int i = 0; i < raster2.NumRows; i++)
                        {
                            for (int j = 0; j < raster2.NumColumns; j++)
                            {
                                if (raster2.Value[i, j] != raster2.NoDataValue)
                                {
                                    raster_water.Value[i, j] = class_mat[i][j];
                                }
                                else
                                {
                                    raster_water.Value[i, j] = raster2.NoDataValue;
                                }
                            }
                        }
                        var cell               = raster2.ProjToCell(center_pt);
                        var center_class       = raster_water.Value[cell.Row, cell.Column];
                        var center_bound_class = center_class;
                        for (int i = cell.Row + 1; i < raster2.NumRows; i++)
                        {
                            if (raster_water.Value[i, cell.Column] != center_class)
                            {
                                center_bound_class = raster_water.Value[i, cell.Column];
                                break;
                            }
                        }

                        if (center_bound_class == center_class)
                        {
                            for (int i = cell.Column + 1; i < raster2.NumColumns; i++)
                            {
                                if (raster_water.Value[cell.Row, i] != center_class)
                                {
                                    center_bound_class = raster_water.Value[cell.Row, i];
                                    break;
                                }
                            }
                        }

                        for (int i = 0; i < raster2.NumRows; i++)
                        {
                            for (int j = 0; j < raster2.NumColumns; j++)
                            {
                                if (raster2.Value[i, j] != raster2.NoDataValue)
                                {
                                    if (raster_water.Value[i, j] == center_class)
                                    {
                                        water_cell_count++;
                                    }
                                    if (raster_water.Value[i, j] == center_bound_class)
                                    {
                                        water_bound_cell_count++;
                                    }
                                }
                            }
                        }
                        water_area[date_index, K]      = water_cell_count * cell_area;
                        water_bond_area[date_index, K] = water_bound_cell_count * cell_area;
                        sw_area.WriteLine(string.Format("{0},{1},{2},{3}", daystr, water_area[date_index, K], water_bond_area[date_index, K],
                                                        water_area[date_index, K] + water_bond_area[date_index, K]));

                        raster_water.Save();
                        raster_water.Close();

                        date_index++;
                    }
                }
                catch (Exception ex)
                {
                    cancelProgressHandler.Progress("Package_Tool", 100, "Error: " + ex.Message);
                }
                finally
                {
                    sw_area.Close();
                    sr_class_file.Close();
                    sr_date_list.Close();
                }
                progress = K * 100 / nlakes;
                //if (progress > count)
                //{
                cancelProgressHandler.Progress("Package_Tool", progress, "Processing lake " + lake_id);
                count++;
                // }
            }
            string       lake_area_file      = Path.Combine(FileDirectory, "water_area.csv");
            string       lake_area_bond_file = Path.Combine(FileDirectory, "waterbond_area.csv");
            StreamWriter csv_water           = new StreamWriter(lake_area_file);
            StreamWriter csv_bond            = new StreamWriter(lake_area_bond_file);
            var          line = string.Join(",", lake_list.ToArray());

            csv_water.WriteLine(line);
            csv_bond.WriteLine(line);
            for (int t = 0; t < ndays; t++)
            {
                line = "";
                for (int j = 0; j < nlakes; j++)
                {
                    line += water_area[t, j] + ",";
                }
                line = line.TrimEnd(new char[] { ',' });
                csv_water.WriteLine(line);

                line = "";
                for (int j = 0; j < nlakes; j++)
                {
                    line += water_bond_area[t, j] + ",";
                }
                line = line.TrimEnd(new char[] { ',' });
                csv_bond.WriteLine(line);
            }

            csv_water.Close();
            csv_bond.Close();
            lake_centroid_fs.Close();
            return(true);
        }
コード例 #16
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            var fs = FeatureSet.Open(TargetFeatureFile);

            if (fs != null && File.Exists(FilenameList))
            {
                var          npt      = fs.NumRows();
                Coordinate[] coors    = new Coordinate[npt];
                int          progress = 0;
                for (int i = 0; i < npt; i++)
                {
                    var geo_pt = fs.GetFeature(i).Geometry;
                    coors[i] = geo_pt.Coordinate;
                }
                List <string> files = new List <string>();
                StreamReader  sr    = new StreamReader(FilenameList);
                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    if (TypeConverterEx.IsNotNull(line))
                    {
                        files.Add(line.Trim());
                    }
                }
                sr.Close();
                if (files != null)
                {
                    int nstep   = files.Count();
                    var mat_out = new DataCube <float>(1, nstep, npt);
                    mat_out.Name           = OutputDataCube;
                    mat_out.Variables      = new string[] { VariableName };
                    mat_out.TimeBrowsable  = true;
                    mat_out.AllowTableEdit = false;
                    for (int t = 0; t < nstep; t++)
                    {
                        IRaster raster = Raster.Open(files[t]);
                        for (int i = 0; i < npt; i++)
                        {
                            var cell = raster.ProjToCell(coors[i]);
                            if (cell != null && cell.Row > 0)
                            {
                                mat_out[0, t, i] = (float)raster.Value[cell.Row, cell.Column];
                            }
                            else
                            {
                                mat_out[0, t, i] = 0;
                            }
                        }
                        progress = t * 100 / nstep;
                        cancelProgressHandler.Progress("Package_Tool", progress, "Processing raster:" + files[t]);
                    }
                    Workspace.Add(mat_out);
                    fs.Close();
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                cancelProgressHandler.Progress("Package_Tool", 50, "Failed to run. The input parameters are incorrect.");
                return(false);
            }
        }
コード例 #17
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            List <int[]>   list_poly  = new List <int[]>();
            List <float[]> list_nodes = new List <float[]>();
            StreamReader   sr         = new StreamReader(InputFileName);
            var            line       = sr.ReadLine();

            line = sr.ReadLine();
            line = sr.ReadLine();
            while (!sr.EndOfStream)
            {
                line = sr.ReadLine();
                if (TypeConverterEx.IsNotNull(line))
                {
                    if (line.Contains("BEGPARAMDEF"))
                    {
                        break;
                    }
                    if (line.Contains("E3T"))
                    {
                        var   buf = TypeConverterEx.Split <string>(line.Trim());
                        int[] num = new int[3];
                        num[0] = int.Parse(buf[2]);
                        num[1] = int.Parse(buf[3]);
                        num[2] = int.Parse(buf[4]);
                        list_poly.Add(num);
                    }
                    else if (line.Contains("ND"))
                    {
                        var     buf = TypeConverterEx.Split <string>(line);
                        float[] num = new float[3];
                        num[0] = float.Parse(buf[2]);
                        num[1] = float.Parse(buf[3]);
                        num[2] = float.Parse(buf[4]);
                        list_nodes.Add(num);
                    }
                }
            }
            sr.Close();
            cancelProgressHandler.Progress("Package_Tool", 10, "2dm file loaded.");
            var        num_nodes = list_nodes.Count;
            var        num_polys = list_poly.Count;
            var        node_shp  = InputFileName.Replace(".2dm", "_pt.shp");
            var        poly_shp  = InputFileName.Replace(".2dm", "_poly.shp");
            FeatureSet fs_poly   = new FeatureSet(FeatureType.Polygon);

            fs_poly.Name = "Mesh_Elements";
            fs_poly.DataTable.Columns.Add(new DataColumn("ID", typeof(int)));
            fs_poly.DataTable.Columns.Add(new DataColumn("Temp", typeof(double)));
            for (int i = 0; i < num_polys; i++)
            {
                GeoAPI.Geometries.Coordinate[] vertices = new GeoAPI.Geometries.Coordinate[4];
                var temp = list_poly[i];
                vertices[0]   = new Coordinate();
                vertices[0].X = list_nodes[temp[0] - 1][0];
                vertices[0].Y = list_nodes[temp[0] - 1][1];
                vertices[0].Z = list_nodes[temp[0] - 1][2];
                vertices[1]   = new Coordinate();
                vertices[1].X = list_nodes[temp[1] - 1][0];
                vertices[1].Y = list_nodes[temp[1] - 1][1];
                vertices[1].Z = list_nodes[temp[1] - 1][2];
                vertices[2]   = new Coordinate();
                vertices[2].X = list_nodes[temp[2] - 1][0];
                vertices[2].Y = list_nodes[temp[2] - 1][1];
                vertices[2].Z = list_nodes[temp[2] - 1][2];
                vertices[3]   = new Coordinate(vertices[0]);
                GeoAPI.Geometries.ILinearRing ring = new LinearRing(vertices);
                Polygon geom = new Polygon(ring);
                DotSpatial.Data.IFeature feature = fs_poly.AddFeature(geom);
                feature.DataRow.BeginEdit();
                feature.DataRow["ID"]   = i + 1;
                feature.DataRow["Temp"] = System.Math.Round((vertices[0].Z + vertices[1].Z + vertices[2].Z) / 3, 2);
                feature.DataRow.EndEdit();
            }
            fs_poly.SaveAs(poly_shp, true);
            cancelProgressHandler.Progress("Package_Tool", 80, "Mesh elements shapefile created.");
            FeatureSet fs_pt = new FeatureSet(FeatureType.Point);

            fs_pt.Name = "Mesh_Nodes";
            fs_pt.DataTable.Columns.Add(new DataColumn("ID", typeof(int)));
            fs_pt.DataTable.Columns.Add(new DataColumn("Temp", typeof(double)));
            for (int i = 0; i < num_nodes; i++)
            {
                Point pt = new Point(list_nodes[i][0], list_nodes[i][1], list_nodes[i][2]);
                DotSpatial.Data.IFeature feature = fs_pt.AddFeature(pt);
                feature.DataRow.BeginEdit();
                feature.DataRow["ID"]   = i + 1;
                feature.DataRow["Temp"] = list_nodes[i][2];
                feature.DataRow.EndEdit();
            }
            fs_pt.SaveAs(node_shp, true);
            cancelProgressHandler.Progress("Package_Tool", 90, "Mesh nodes shapefile created.");
            cancelProgressHandler.Progress("Package_Tool", 100, "Finished.");
            return(true);
        }
コード例 #18
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            int          progress = 0;
            string       line     = "";
            float        temp     = 0;
            int          count    = 1;
            int          nstep    = 0;
            int          ncell    = 0;
            var          date     = DateTime.Now;
            StreamReader sr       = new StreamReader(DataFileName);

            if (ContainsHeader)
            {
                line = sr.ReadLine();
            }
            line = sr.ReadLine();
            var buf = TypeConverterEx.Split <string>(line.Trim());

            if (ContainsDateTime)
            {
                buf = TypeConverterEx.SkipSplit <string>(line.Trim(), 1);
            }
            ncell = buf.Length;
            nstep++;

            while (!sr.EndOfStream)
            {
                line = sr.ReadLine();
                if (!TypeConverterEx.IsNull(line))
                {
                    nstep++;
                }
            }
            sr.Close();

            sr = new StreamReader(DataFileName);
            string var_name = Path.GetFileNameWithoutExtension(DataFileName);
            var    mat_out  = new DataCube <float>(1, nstep, ncell);

            mat_out.Name           = OutputMatrix;
            mat_out.AllowTableEdit = false;
            mat_out.TimeBrowsable  = true;
            mat_out.Variables      = new string[] { var_name };
            mat_out.DateTimes      = new DateTime[nstep];
            if (ContainsHeader)
            {
                line = sr.ReadLine();
            }
            if (ContainsDateTime)
            {
                for (int t = 0; t < nstep; t++)
                {
                    line = sr.ReadLine();
                    var strs = TypeConverterEx.Split <string>(line);
                    DateTime.TryParse(strs[0], out date);
                    mat_out.DateTimes[t] = date;
                    for (int i = 0; i < ncell; i++)
                    {
                        float.TryParse(strs[i + 1], out temp);
                        mat_out[0, t, i] = temp;
                    }
                    if (progress > count)
                    {
                        progress = t * 100 / nstep;
                        cancelProgressHandler.Progress("Package_Tool", progress, "Processing step:" + (t + 1));
                    }
                }
            }
            else
            {
                for (int t = 0; t < nstep; t++)
                {
                    line = sr.ReadLine();
                    var vec = TypeConverterEx.Split <float>(line);
                    mat_out[0, t.ToString(), ":"] = vec;
                    mat_out.DateTimes[t]          = Start.AddSeconds(Interval * t);
                    if (progress > count)
                    {
                        progress = t * 100 / nstep;
                        cancelProgressHandler.Progress("Package_Tool", progress, "Processing step:" + (t + 1));
                    }
                }
            }
            Workspace.Add(mat_out);
            return(true);
        }
コード例 #19
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            //string basedir = @"E:\Heihe\HRB\DataSets\Driving Forces\PXD\";
            //AverageTemperatureFileName = basedir + "daily_tavk_11243.dcx";
            //MaxTemperatureFileName = basedir + "daily_tmaxk_11243.dcx";
            //MinTemperatureFileName = basedir + "daily_tmink_11243.dcx";
            //RelativeHumidityFileName = @"E:\Heihe\HRB\DataSets\Driving Forces\TY\rh.dcx";
            //AirPressureFileName = basedir + "daily_ap_11243.dcx";
            //WindSpeedFileName = basedir + "daily_windspeed_11243.dcx";

            IFeatureSet fs = FeatureSet.Open(PointFeatureFileName);

            string[] files = new string[] { AverageTemperatureFileName, MaxTemperatureFileName, MinTemperatureFileName, RelativeHumidityFileName,
                                            AirPressureFileName, WindSpeedFileName };
            var npt = fs.NumRows();

            Coordinate[] coors = new Coordinate[npt];
            for (int i = 0; i < npt; i++)
            {
                var geo_pt = fs.GetFeature(i).Geometry;
                coors[i] = geo_pt.Coordinate;
            }
            int nfile = files.Length;

            DataCubeStreamReader[] ass  = new DataCubeStreamReader[nfile];
            DataCube <float>[]     mats = new DataCube <float> [nfile];
            for (int i = 0; i < nfile; i++)
            {
                ass[i] = new DataCubeStreamReader(files[i]);
                ass[i].Open();
            }
            int progress         = 0;
            int nstep            = ass[0].NumTimeStep;
            int ncell            = ass[0].FeatureCount;
            PenmanMonteithET pet = new PenmanMonteithET();

            DataCubeStreamWriter sw = new DataCubeStreamWriter(OutputFileName);

            sw.WriteHeader(new string[] { "pet" }, ncell);
            DataCube <float> mat_out = new DataCube <float>(1, 1, ncell);

            mat_out.DateTimes = new DateTime[nstep];
            int count = 1;

            for (int t = 0; t < nstep; t++)
            {
                for (int i = 0; i < nfile; i++)
                {
                    mats[i] = ass[i].LoadStep();
                }
                for (int n = 0; n < ncell; n++)
                {
                    var tav  = mats[0][0, 0, n];
                    var tmax = mats[1][0, 0, n];
                    var tmin = mats[2][0, 0, n];
                    if (InputTemperatureUnit == TemperatureUnit.Fahrenheit)
                    {
                        tmax = (float)UnitConversion.Fahrenheit2Kelvin(tmax);
                        tmin = (float)UnitConversion.Fahrenheit2Kelvin(tmin);
                        tav  = (float)UnitConversion.Fahrenheit2Kelvin(tav);
                    }
                    else if (InputTemperatureUnit == TemperatureUnit.Celsius)
                    {
                        tmax = (float)UnitConversion.Celsius2Kelvin(tmax);
                        tmin = (float)UnitConversion.Celsius2Kelvin(tmin);
                        tav  = (float)UnitConversion.Celsius2Kelvin(tav);
                    }
                    double ap  = mats[4][0, 0, n] / 1000;
                    var    et0 = pet.ET0(coors[n].Y, coors[n].X, tav, tmax, tmin,
                                         mats[3][0, 0, n], ap, mats[5][0, 0, n], Start.AddDays(t), CloudCover);

                    if (OutputLengthUnit == LengthUnit.inch)
                    {
                        mat_out[0, 0, n] = (float)System.Math.Round(et0 * UnitConversion.mm2Inch, 3);
                    }
                    else
                    {
                        mat_out[0, 0, n] = (float)System.Math.Round(et0, 3);
                    }
                }
                mat_out.DateTimes[t] = Start.AddDays(1);
                sw.WriteStep(1, ncell, mat_out);
                progress = t * 100 / nstep;
                if (progress > count)
                {
                    cancelProgressHandler.Progress("Package_Tool", progress, "Processing step:" + (t + 1));
                    count++;
                }
            }

            sw.Close();
            for (int i = 0; i < nfile; i++)
            {
                ass[i].Close();
            }

            return(true);
        }
コード例 #20
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            var var_index = 0;
            var mat       = Get3DMat(Source, ref var_index);
            int progress  = 0;
            int count     = 1;

            if (mat.DateTimes != null)
            {
                int          nstep = mat.Size[1];
                int          ncell = mat.Size[2];
                StreamWriter sw    = new StreamWriter(DataFileName);
                string       line  = "Metrological File, generated by the software written by Visual Heiflow at " + DateTime.Now.ToString();
                sw.WriteLine(line);

                if (CellCount != ncell && ncell == 1)
                {
                    line = VariableName + " " + CellCount;
                    sw.WriteLine(line);
                    sw.WriteLine("######################");
                    for (int t = 0; t < nstep; t++)
                    {
                        var date   = mat.DateTimes[t];
                        var scalar = mat[var_index, t, 0];
                        line = string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t", date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);

                        for (int i = 0; i < CellCount; i++)
                        {
                            line += scalar.ToString(Format) + "\t";
                        }
                        line += scalar.ToString(Format);
                        sw.WriteLine(line);
                        progress = t * 100 / nstep;
                        if (progress > count)
                        {
                            cancelProgressHandler.Progress("Package_Tool", progress, "Processing step:" + t);
                            count++;
                        }
                    }
                }
                else
                {
                    line = VariableName + " " + ncell;
                    sw.WriteLine(line);
                    sw.WriteLine("######################");
                    for (int t = 0; t < nstep; t++)
                    {
                        var date = mat.DateTimes[t];
                        var vec  = mat[var_index, t.ToString(), ":"];
                        line = string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t", date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);

                        for (int i = 0; i < vec.Length - 1; i++)
                        {
                            line += vec[i].ToString(Format) + "\t";
                        }
                        line += vec[vec.Length - 1];
                        sw.WriteLine(line);
                        progress = t * 100 / nstep;
                        if (progress > count)
                        {
                            cancelProgressHandler.Progress("Package_Tool", progress, "Processing step:" + t);
                            count++;
                        }
                    }
                }

                sw.Close();
                return(true);
            }
            else
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "the input data cube does not contain date information");
                return(false);
            }
        }
コード例 #21
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            FileStream   fs = new FileStream(_OutputFileName, FileMode.Create, FileAccess.Write);
            BinaryWriter bw = new BinaryWriter(fs);

            var var_index = 0;
            var mat       = Get3DMat(Source, ref var_index);
            int progress  = 0;
            int nsteps    = mat.Size[1];
            var grid      = ProjectService.Project.Model.Grid as RegularGrid;

            if (grid != null)
            {
                float[][] lonlat = null;
                if (CoornidateSystem == CS.GCS)
                {
                    lonlat = grid.GetLonLatAxis();
                }
                else if (CoornidateSystem == CS.PCS)
                {
                    lonlat = grid.GetPCSAxis();
                }
                var nrow  = grid.RowCount;
                var ncol  = grid.ColumnCount;
                var times = new float[nsteps];
                if (mat.DateTimes != null)
                {
                    for (int t = 0; t < nsteps; t++)
                    {
                        times[t] = (float)mat.DateTimes[t].ToOADate();
                    }
                }
                else
                {
                    for (int t = 0; t < nsteps; t++)
                    {
                        times[t] = (float)DateTime.Now.AddDays(t).ToOADate();
                    }
                }

                bw.Write(nrow);
                bw.Write(ncol);
                bw.Write(nsteps);

                for (int i = 0; i < ncol; i++)
                {
                    bw.Write(lonlat[0][i]);
                }
                for (int i = 0; i < nrow; i++)
                {
                    bw.Write(lonlat[1][i]);
                }

                for (int t = 0; t < nsteps; t++)
                {
                    bw.Write(times[t]);
                    var vec = mat[var_index, t.ToString(), ":"];
                    bw.Write(vec.Max());
                    bw.Write(vec.Min());
                    bw.Write(vec.Average());
                    bw.Write(MyStatisticsMath.StandardDeviation(vec));
                    var mat_step = grid.ToMatrix <float>(vec, 0);
                    for (int r = 0; r < nrow; r++)
                    {
                        for (int c = 0; c < ncol; c++)
                        {
                            bw.Write(mat_step[r][c]);
                        }
                    }
                    progress = t * 100 / nsteps;
                    cancelProgressHandler.Progress("Package_Tool", progress, "Processing step:" + t);
                }

                fs.Close();
                bw.Close();
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #22
0
        public bool Execute1(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            StreamReader sr    = new StreamReader(Path.Combine(FileDirectory, "list.txt"));
            int          nfile = 0;

            while (!sr.EndOfStream)
            {
                sr.ReadLine();
                nfile++;
            }
            sr.Close();
            sr = new StreamReader(Path.Combine(FileDirectory, "list.txt"));
            string[] dirs = new string[nfile];
            for (int i = 0; i < nfile; i++)
            {
                var str = sr.ReadLine();
                dirs[i] = Path.Combine(FileDirectory, str + "_2.tif");
            }

            int[] bandlist = new int[] { 4, 3, 2 };
            //string[] dirs = Directory.GetFiles(FileDirectory, "*_2.tif");
            string        center_shp = @"E:\Project\HRB\Badan Jarian\Data\Geospatial\Center35.shp";
            StreamWriter  sw         = new StreamWriter(Path.Combine(FileDirectory, "area.csv"));
            StreamWriter  sw_alpha   = new StreamWriter(Path.Combine(FileDirectory, "alpha.txt"));
            IFeatureSet   center_fs  = FeatureSet.Open(center_shp);
            List <double> vec        = new List <double>();

            try
            {
                double cell_area = 5 * 5;

                var center_pt  = center_fs.Features[0].Geometry.Coordinate;
                var center_vec = new double[3];
                var pt_vec     = new double[3];
                int progress   = 0;
                int count      = 1;
                int t          = 0;
                vec.Clear();
                foreach (var file in dirs)
                {
                    long    wcount     = 0;
                    var     temp       = Path.GetFileNameWithoutExtension(file);
                    var     daystr     = temp.Remove(10);
                    var     water_file = file.Replace("_2", "_water");
                    IRaster raster2    = Raster.OpenFile(file);
                    raster2.SaveAs(water_file);
                    IRaster raster3      = Raster.OpenFile(file.Replace("_2", "_3"));
                    IRaster raster4      = Raster.OpenFile(file.Replace("_2", "_4"));
                    IRaster raster_water = Raster.OpenFile(water_file);
                    double[,] img = new double[raster2.NumRows, raster2.NumColumns];
                    var cell = raster2.ProjToCell(center_pt);
                    center_vec[0] = raster2.Value[cell.Row, cell.Column];
                    center_vec[1] = raster3.Value[cell.Row, cell.Column];
                    center_vec[2] = raster4.Value[cell.Row, cell.Column];
                    for (int i = 0; i < raster2.NumRows; i++)
                    {
                        for (int j = 0; j < raster2.NumColumns; j++)
                        {
                            if (raster2.Value[i, j] == raster2.NoDataValue)
                            {
                                img[i, j] = 0;
                                raster_water.Value[i, j] = 0;
                                sw_alpha.WriteLine(0);
                                vec.Add(0);
                            }
                            else
                            {
                                pt_vec[0] = raster2.Value[i, j];
                                pt_vec[1] = raster3.Value[i, j];
                                pt_vec[2] = raster4.Value[i, j];
                                var alpha = sam(pt_vec, center_vec);
                                if (alpha <= AlphaThreashhold)
                                {
                                    raster_water.Value[i, j] = 1;
                                    wcount++;
                                }
                                else
                                {
                                    raster_water.Value[i, j] = 0;
                                }
                                try
                                {
                                    raster_water.Value[i, j] = alpha;
                                }
                                catch (Exception ex)
                                {
                                    cancelProgressHandler.Progress("Package_Tool", progress, "Warning: " + ex.Message + " " + alpha);
                                    alpha = 0;
                                    raster_water.Value[i, j] = 0;
                                }
                                finally
                                {
                                    img[i, j] = alpha;
                                    vec.Add(alpha);
                                    sw_alpha.WriteLine(alpha);
                                }
                            }
                        }
                    }
                    var max   = vec.Max();
                    var min   = vec.Min();
                    var delta = max - min;
                    int k     = 0;
                    for (int i = 0; i < raster2.NumRows; i++)
                    {
                        for (int j = 0; j < raster2.NumColumns; j++)
                        {
                            img[i, j] = (vec[k] - min) / delta * 255;
                            raster_water.Value[i, j] = img[i, j];
                            k++;
                        }
                    }

                    var sobled_img = sobel(img, raster2.NumRows, raster2.NumColumns);
                    for (int i = 0; i < raster2.NumRows; i++)
                    {
                        for (int j = 0; j < raster2.NumColumns; j++)
                        {
                            raster_water.Value[i, j] = sobled_img[i, j];
                        }
                    }
                    var water_area = wcount * cell_area;
                    sw.WriteLine(daystr + "," + water_area);
                    raster2.Close();
                    raster3.Close();
                    raster4.Close();
                    raster_water.Save();
                    raster_water.Close();
                    progress = t * 100 / dirs.Length;
                    if (progress > count)
                    {
                        cancelProgressHandler.Progress("Package_Tool", progress, "Processing: " + file);
                        count++;
                    }
                    t++;
                }
            }
            catch (Exception ex)
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "Error: " + ex.Message);
            }
            finally
            {
                sw_alpha.Close();
                sr.Close();
                sw.Close();
                center_fs.Close();
            }

            return(true);
        }
コード例 #23
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            int progress = 0;
            int count    = 1;

            if (_target_layer != null)
            {
                var nrow    = _target_layer.NumRows();
                var dx      = System.Math.Sqrt(_target_layer.GetFeature(0).Geometry.Area);
                int nsample = (int)System.Math.Floor(dx / _dem_layer.CellHeight);
                var mat     = new DataCube <float>(1, 1, nrow);
                mat.Name           = Matrix;
                mat.Variables      = new string[] { Matrix };
                mat.TimeBrowsable  = false;
                mat.AllowTableEdit = true;
                List <Coordinate> list = new List <Coordinate>();
                if (_target_layer.FeatureType == FeatureType.Polygon)
                {
                    for (int i = 0; i < nrow; i++)
                    {
                        float sum_cellv = 0;
                        int   npt       = 0;
                        list.Clear();
                        var fea = _target_layer.GetFeature(i).Geometry;
                        var x0  = (from p in fea.Coordinates select p.X).Min();
                        var y0  = (from p in fea.Coordinates select p.Y).Min();
                        for (int r = 0; r <= nsample; r++)
                        {
                            var y = y0 + r * _dem_layer.CellHeight;
                            for (int c = 0; c <= nsample; c++)
                            {
                                var        x  = x0 + c * _dem_layer.CellWidth;
                                Coordinate pt = new Coordinate(x, y);
                                list.Add(pt);
                            }
                        }
                        foreach (var pt in list)
                        {
                            var cell = _dem_layer.ProjToCell(pt);
                            if (cell != null && cell.Row > 0)
                            {
                                var buf = (float)_dem_layer.Value[cell.Row, cell.Column];
                                if (buf != _dem_layer.NoDataValue)
                                {
                                    sum_cellv += buf;
                                    npt++;
                                }
                            }
                        }
                        if (npt > 0)
                        {
                            sum_cellv = sum_cellv / npt;
                        }
                        mat[0, 0, i] = sum_cellv;

                        progress = i * 100 / nrow;
                        if (progress > count)
                        {
                            cancelProgressHandler.Progress("Package_Tool", progress, "Processing polygon: " + i);
                            count++;
                        }
                    }
                }
                else
                {
                    Coordinate[] coors = new Coordinate[nrow];

                    for (int i = 0; i < nrow; i++)
                    {
                        var geo_pt = _target_layer.GetFeature(i).Geometry;
                        coors[i] = geo_pt.Coordinate;
                    }

                    for (int i = 0; i < nrow; i++)
                    {
                        var cell = _dem_layer.ProjToCell(coors[i]);
                        if (cell != null && cell.Row > 0)
                        {
                            mat[0, 0, i] = (float)_dem_layer.Value[cell.Row, cell.Column];
                        }
                        progress = i * 100 / nrow;
                        if (progress > count)
                        {
                            cancelProgressHandler.Progress("Package_Tool", progress, "Processing point: " + i);
                            count++;
                        }
                    }
                }
                Workspace.Add(mat);
                return(true);
            }
            else
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "Error message: the input layers are incorrect.");
                return(false);
            }
        }
コード例 #24
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            int num_well_layer = 3;

            int[]        well_layer = new int[] { 1, 2, 3 };
            double[]     layer_ratio = new double[] { 0.6, 0.1, 0.3 };
            int          num_irrg_obj, num_indust_obj;
            StreamReader sr_quota = new StreamReader(QuotaFileName);
            StreamWriter sw_out   = new StreamWriter(OutputFileName);
            string       newline  = "";
            int          nquota   = 1;
            int          ntime    = 36;
            var          line     = sr_quota.ReadLine();

            var strs_buf = TypeConverterEx.Split <string>(line);

            nquota = int.Parse(strs_buf[0]);
            ntime  = int.Parse(strs_buf[1]);
            double[,] quota_src = new double[ntime, nquota];
            double[,] quota     = new double[366, nquota];
            int day   = 0;
            var start = new DateTime(2000, 1, 1);

            for (int i = 0; i < ntime; i++)
            {
                line = sr_quota.ReadLine().Trim();
                var buf  = TypeConverterEx.Split <string>(line);
                var ss   = DateTime.Parse(buf[0]);
                var ee   = DateTime.Parse(buf[1]);
                var cur  = ss;
                var step = (ee - ss).Days + 1;
                while (cur <= ee)
                {
                    for (int j = 0; j < nquota; j++)
                    {
                        quota[day, j] = System.Math.Round(double.Parse(buf[2 + j]) / step, 2);
                    }
                    day++;
                    cur = cur.AddDays(1);
                }
            }

            line = sr_quota.ReadLine().Trim();
            var inttemp = TypeConverterEx.Split <int>(line.Trim());

            num_irrg_obj   = inttemp[0];
            num_indust_obj = inttemp[1];
            //ID	NAME	地表水比例  用水类型  允许降深
            line = sr_quota.ReadLine();
            irrg_obj_list.Clear();
            indust_obj_list.Clear();
            ReadObj(sr_quota, num_irrg_obj, irrg_obj_list);
            ReadObj(sr_quota, num_indust_obj, indust_obj_list);
            CalcObjPumpConstraint(irrg_obj_list, quota);

            newline = "# Water resources allocation package " + DateTime.Now;
            sw_out.WriteLine(newline);
            newline = string.Format("{0}\t{1}\t0\t0\t # num_irrg_obj, num_indu_obj, num_doms_obj, num_ecos_obj ", num_irrg_obj, num_indust_obj);
            sw_out.WriteLine(newline);

            sw_out.WriteLine("# irrigation objects");
            for (int i = 0; i < num_irrg_obj; i++)
            {
                var obj = irrg_obj_list[i];
                int oid = i + 1;
                newline = string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t#	oid, hrunum, iseg, ireach, num_well_layer, inlet_type {6}", obj.ID, obj.HRU_Num, obj.SegID, obj.ReachID, num_well_layer, obj.Inlet_Type, obj.Name);
                sw_out.WriteLine(newline);
                newline = string.Join("\t", obj.HRU_List);
                sw_out.WriteLine(newline);
                var canal_eff   = new double[obj.HRU_Num];
                var canal_ratio = new double[obj.HRU_Num];
                for (int j = 0; j < obj.HRU_Num; j++)
                {
                    canal_eff[j]   = obj.Canal_Efficiency;
                    canal_ratio[j] = obj.Canal_Ratio;
                }
                newline = string.Join("\t", canal_eff);
                sw_out.WriteLine(newline);
                newline = string.Join("\t", canal_ratio);
                sw_out.WriteLine(newline);
                for (int j = 0; j < num_well_layer; j++)
                {
                    newline = well_layer[j] + "\t" + layer_ratio[j] + " # well_layer layer_ratio";
                    sw_out.WriteLine(newline);
                }
                newline = string.Format("{0}\t#	drawdown constaint of object {1}", irrg_obj_list[i].Drawdown, oid);
                sw_out.WriteLine(newline);
                newline = string.Format("{0}\t{1}\t{2}\t#  inlet	min flow,  max flow and flow ratio  for object {3}", irrg_obj_list[i].Inlet_MinFlow, irrg_obj_list[i].Inlet_MaxFlow, irrg_obj_list[i].Inlet_Flow_Ratio,
                                        irrg_obj_list[i].ID);
                sw_out.WriteLine(newline);
            }
            sw_out.WriteLine("# industrial objects");
            for (int i = 0; i < num_indust_obj; i++)
            {
                var obj = indust_obj_list[i];
                newline = string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t#	oid, hrunum, iseg, ireach, num_well_layer, inlet_type {6}", obj.ID, obj.HRU_Num, obj.SegID, obj.ReachID, num_well_layer,
                                        obj.Inlet_Type, obj.Name);
                sw_out.WriteLine(newline);
                newline = string.Format("{0}\t#	hru_id_list", string.Join(" ", obj.HRU_List));
                sw_out.WriteLine(newline);
                for (int j = 0; j < num_well_layer; j++)
                {
                    newline = well_layer[j] + "\t" + layer_ratio[j] + " # well_layer layer_ratio";
                    sw_out.WriteLine(newline);
                }
                newline = string.Format("{0}\t#	drawdown constaint of object {1}", obj.Drawdown, obj.ID);
                sw_out.WriteLine(newline);
                newline = string.Format("{0}\t{1}\t{2}\t#  inlet	min flow,  max flow and flow ratio for object {3}", obj.Inlet_MinFlow, obj.Inlet_MaxFlow, obj.Inlet_Flow_Ratio, obj.ID);
                sw_out.WriteLine(newline);
                newline = string.Format("{0}\t#	return_ratio", 0);
                sw_out.WriteLine(newline);
            }

            sw_out.WriteLine(StartCycle + " # cycle index");
            sw_out.WriteLine("1	#	quota_flag");

            for (int i = 0; i < nquota; i++)
            {
                newline = "";
                for (int j = 0; j < 366; j++)
                {
                    newline += quota[j, i].ToString("0.0") + "\t";
                }
                newline += "quota of object " + (i + 1);
                sw_out.WriteLine(newline);
            }

            newline = "# irrigation objects";
            sw_out.WriteLine(newline);
            if (GWCompensate)
            {
                newline = "1 1	1	1	1	1	1 #	sw_ratio_flag, swctrl_factor_flag , gwctrl_factor_flag, Withdraw_type_flag,plantarea_flag,max_pump_rate_flag,max_total_pump_flag";
            }
            else
            {
                newline = "1 1	1	1	1	1	1 #	sw_ratio_flag, swctrl_factor_flag , gwctrl_factor_flag, Withdraw_type_flag,plantarea_flag";
            }
            sw_out.WriteLine(newline);
            //地表水比例
            for (int i = 0; i < num_irrg_obj; i++)
            {
                var ratio = irrg_obj_list[i].SW_Ratio;
                //if (mid_zone_id.Contains(irrg_obj_list[i].ID))
                //{
                //    ratio = ratio * sw_scale[k];
                //}
                newline = "";
                for (int j = 0; j < 366; j++)
                {
                    newline += ratio.ToString("0.00") + "\t";
                }
                newline += "#SW ratio of object " + irrg_obj_list[i].ID;
                sw_out.WriteLine(newline);
            }
            //地表引水控制系数
            for (int i = 0; i < num_irrg_obj; i++)
            {
                newline = string.Format("{0}\t#SW control factor of object {1}", irrg_obj_list[i].SW_Cntl_Factor, irrg_obj_list[i].ID);
                sw_out.WriteLine(newline);
            }
            //地下引水控制系数
            for (int i = 0; i < num_irrg_obj; i++)
            {
                newline = string.Format("{0}\t#GW control factor of object {1}", irrg_obj_list[i].GW_Cntl_Factor, irrg_obj_list[i].ID);
                sw_out.WriteLine(newline);
            }
            //作物类型
            for (int i = 0; i < num_irrg_obj; i++)
            {
                newline = "";
                for (int j = 0; j < irrg_obj_list[i].HRU_Num; j++)
                {
                    newline += irrg_obj_list[i].ObjType + "\t";
                }
                newline += "# Plant type of object " + (i + 1);
                sw_out.WriteLine(newline);
            }
            //种植面积
            for (int i = 0; i < num_irrg_obj; i++)
            {
                newline  = string.Join("\t", irrg_obj_list[i].HRU_Area);
                newline += "\t" + "# Plant area of object " + irrg_obj_list[i].ID;
                sw_out.WriteLine(newline);
            }
            if (GWCompensate)
            {
                //每个HRU的地下水抽水能力
                for (int i = 0; i < num_irrg_obj; i++)
                {
                    newline  = string.Join("\t", irrg_obj_list[i].Max_Pump_Rate);
                    newline += "\t" + "# Maximum pumping rate of object " + irrg_obj_list[i].ID;
                    sw_out.WriteLine(newline);
                }
                //每个HRU的最大地下水抽水量
                var objbuf = from ir in irrg_obj_list select ir.Max_Total_Pump;
                newline  = string.Join("\t", objbuf);
                newline += "\t" + "# Total maximum pumping amonut";
                sw_out.WriteLine(newline);
            }

            newline = "# industrial objects";
            sw_out.WriteLine(newline);
            newline = "1 1	1	1	1 #	sw_ratio_flag, swctrl_factor_flag , gwctrl_factor_flag, Withdraw_type_flag";
            sw_out.WriteLine(newline);

            for (int i = 0; i < num_indust_obj; i++)
            {
                newline = "";
                var control = 1;
                for (int j = 0; j < 366; j++)
                {
                    newline += control + "\t";
                }
                newline += "# SW control factor of object " + (indust_obj_list[i].ID);
                sw_out.WriteLine(newline);
            }

            //地表引水控制系数
            for (int i = 0; i < num_indust_obj; i++)
            {
                newline = string.Format("{0}\t#SW control factor of object {1}", indust_obj_list[i].SW_Cntl_Factor, indust_obj_list[i].ID);
                sw_out.WriteLine(newline);
            }

            //地下引水控制系数
            for (int i = 0; i < num_indust_obj; i++)
            {
                newline = string.Format("{0}\t#GW control factor of object {1}", indust_obj_list[i].GW_Cntl_Factor, indust_obj_list[i].ID);
                sw_out.WriteLine(newline);
            }

            //用水类型
            for (int i = 0; i < num_indust_obj; i++)
            {
                var obj = indust_obj_list[i];
                newline = string.Format("{0} # Withdraw type of object {1}", obj.ObjType, obj.ID);
                sw_out.WriteLine(newline);
            }

            for (int i = StartCycle + 1; i <= EndCycle; i++)
            {
                sw_out.WriteLine(i + " # cycle index");
                sw_out.WriteLine("-1 # quota_flag");
                sw_out.WriteLine("# irrigation objects");
                if (GWCompensate)
                {
                    sw_out.WriteLine("-1 -1	-1 -1 -1 -1 -1 #	sw_ratio_flag, swctrl_factor_flag , gwctrl_factor_flag, Withdraw_type_flag,plantarea_flag,max_pump_rate_flag,max_total_pump_flag");
                }
                else
                {
                    sw_out.WriteLine("-1 -1	-1 -1 -1 -1 -1 #	sw_ratio_flag, swctrl_factor_flag , gwctrl_factor_flag, Withdraw_type_flag,plantarea_flag");
                }
                sw_out.WriteLine("# industrial objects");
                sw_out.WriteLine("-1 -1	-1	-1	-1  #	sw_ratio_flag, swctrl_factor_flag , gwctrl_factor_flag, Withdraw_type_flag");
            }

            sr_quota.Close();
            sw_out.Close();

            return(true);
        }
コード例 #25
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            var           fs_source = FeatureSet.Open(SourceFeatureFile);
            var           fs_target = FeatureSet.Open(TargetFeatureFile);
            CSVFileStream csv       = new CSVFileStream(DataFileName);
            var           ts_data   = csv.Load <double>();

            cancelProgressHandler.Progress("Package_Tool", 1, "Time series at known sites loaded");
            int    nsource_sites = fs_source.DataTable.Rows.Count;
            int    ntar_sites    = fs_target.DataTable.Rows.Count;
            int    nstep         = ts_data.Size[0];
            int    nsite_data    = ts_data.Size[1];
            int    progress      = 0;
            double sumOfDis      = 0;
            double sumOfVa       = 0;

            if (nsite_data != nsource_sites)
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "the number of sites in the data file dose not match to that in the source feature file");
                return(false);
            }
            else
            {
                if (Neighbors > nsource_sites)
                {
                    Neighbors = nsource_sites;
                }
                var known_sites      = new Site[nsource_sites];
                DataCube <float> mat = new DataCube <float>(1, nstep, ntar_sites);
                mat.DateTimes      = new DateTime[nstep];
                mat.Name           = OutputMatrix;
                mat.TimeBrowsable  = true;
                mat.AllowTableEdit = false;

                double[][] xvalues = new double[nsource_sites][];
                double[]   yvalues = new double[nsource_sites];
                for (int i = 0; i < nsource_sites; i++)
                {
                    var cor = fs_source.Features[i].Geometry.Coordinate;
                    var ele = double.Parse(fs_source.Features[i].DataRow[_ValueField].ToString());
                    xvalues[i]     = new double[3];
                    known_sites[i] = new Site()
                    {
                        LocalX    = cor.X,
                        LocalY    = cor.Y,
                        ID        = i,
                        Elevation = ele
                    };
                    xvalues[i][0] = cor.X;
                    xvalues[i][1] = cor.Y;
                    xvalues[i][2] = ele;
                }
                for (int i = 0; i < nsource_sites; i++)
                {
                    var    count = 0;
                    double sum   = 0;
                    for (int t = 0; t < nstep; t++)
                    {
                        if (ts_data.GetValue(t, i) < MaximumValue)
                        {
                            sum += ts_data.GetValue(t, i);
                            count++;
                        }
                    }
                    yvalues[i] = sum / count;
                }
                MultipleLinearRegression mlineRegrsn = new MultipleLinearRegression(xvalues, yvalues, true);
                Matrix result = new Matrix();
                mlineRegrsn.ComputeFactorCoref(result);
                double[] coeffs = result[0, Matrix.mCol];
                var      cx     = coeffs[0];
                var      cy     = coeffs[1];
                var      ce     = coeffs[2];
                cancelProgressHandler.Progress("Package_Tool", 2, "Regression coefficients calculated");

                for (int i = 0; i < ntar_sites; i++)
                {
                    var cor        = fs_target.Features[i].Geometry.Coordinate;
                    var site_intep = new Site()
                    {
                        LocalX    = cor.X,
                        LocalY    = cor.Y,
                        ID        = i,
                        Elevation = double.Parse(fs_target.Features[i].DataRow[_ValueField].ToString())
                    };
                    var neighborSites = FindNeareastSites(Neighbors, known_sites, site_intep);
                    for (int j = 0; j < nstep; j++)
                    {
                        sumOfDis = 0;
                        sumOfVa  = 0;
                        foreach (var nsite in neighborSites)
                        {
                            var vv = ts_data.GetValue(j, nsite.ID);
                            if (vv < MaximumValue)
                            {
                                double temp = 1 / System.Math.Pow(nsite.Distance, Power);
                                double gd   = (site_intep.LocalX - nsite.LocalX) * cx + (site_intep.LocalY - nsite.LocalY) * cy + (site_intep.Elevation - nsite.Elevation) * ce;
                                sumOfVa  += vv * temp;
                                sumOfDis += temp;
                            }
                        }
                        if (sumOfDis != 0)
                        {
                            mat[0, j, i] = (float)(sumOfVa / sumOfDis);
                            if (!AllowNegative && mat[0, j, i] < 0)
                            {
                                mat[0, j, i] = MinmumValue;
                            }
                        }
                        else
                        {
                            mat[0, j, i] = MinmumValue;
                        }
                    }
                    progress = (i + 1) * 100 / ntar_sites;
                    cancelProgressHandler.Progress("Package_Tool", progress, "Caculating Cell: " + (i + 1));
                }
                for (int j = 0; j < nstep; j++)
                {
                    mat.DateTimes[j] = Start.AddSeconds(j * TimeStep);
                }
                cancelProgressHandler.Progress("Package_Tool", 100, "");
                Workspace.Add(mat);
                fs_source.Close();
                fs_target.Close();
                return(true);
            }
        }
コード例 #26
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            int          nseg       = 0;
            string       div_out    = DiversionFileName + ".out";
            StreamReader sr_div     = new StreamReader(DiversionFileName);
            StreamReader sr_canal   = new StreamReader(CanalFileName);
            StreamWriter sw_div_out = new StreamWriter(div_out);

            var line = sr_div.ReadLine();

            sw_div_out.WriteLine(line);
            line = sr_div.ReadLine();
            sw_div_out.WriteLine(line);
            var div_buf = TypeConverterEx.Split <string>(line);

            nseg = int.Parse(div_buf[0]);

            sr_canal.ReadLine();

            for (int i = 0; i < nseg; i++)
            {
                line = sr_div.ReadLine();
                sw_div_out.WriteLine(line);
                div_buf = TypeConverterEx.Split <string>(line);
                int nhru = int.Parse(div_buf[1]);

                if (nhru > 0)
                {
                    line = sr_div.ReadLine();
                    sw_div_out.WriteLine(line);
                    line = sr_div.ReadLine();
                    sw_div_out.WriteLine(line);
                    sr_div.ReadLine();
                    sr_div.ReadLine();

                    var   line_canal      = sr_canal.ReadLine();
                    var   buf_canal       = TypeConverterEx.Split <string>(line_canal);
                    float area_ratio      = float.Parse(buf_canal[1]);
                    float effcy_ratio     = float.Parse(buf_canal[2]);
                    var   vec_area_ratio  = new float[nhru];
                    var   vec_effcy_ratio = new float[nhru];
                    for (int j = 0; j < nhru; j++)
                    {
                        vec_area_ratio[j]  = area_ratio;
                        vec_effcy_ratio[j] = effcy_ratio;
                    }

                    line = string.Join("\t", vec_effcy_ratio);
                    sw_div_out.WriteLine(line);
                    line = string.Join("\t", vec_area_ratio);
                    sw_div_out.WriteLine(line);
                }
            }
            while (!sr_div.EndOfStream)
            {
                line = sr_div.ReadLine();
                sw_div_out.WriteLine(line);
            }

            sr_div.Close();
            sr_canal.Close();
            sw_div_out.Close();
            cancelProgressHandler.Progress("Package_Tool", 100, "Done");
            return(true);
        }
コード例 #27
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            FileStream   fs        = new FileStream(OutputFileName, FileMode.Create, FileAccess.Write);
            BinaryWriter bw        = new BinaryWriter(fs);
            StreamWriter sw        = new StreamWriter(OutputFileName + ".hdr");
            var          var_index = 0;
            var          mat       = Get3DMat(Source, ref var_index);
            int          progress  = 0;
            int          nsteps    = mat.Size[1];
            var          grid      = ProjectService.Project.Model.Grid as RegularGrid;
            var          lonlat    = grid.GetLonLatAxis();
            var          nrow      = grid.RowCount;
            var          ncol      = grid.ColumnCount;
            var          times     = new float[nsteps];

            if (mat.DateTimes != null)
            {
                for (int t = 0; t < nsteps; t++)
                {
                    times[t] = (float)mat.DateTimes[t].ToOADate();
                }
            }
            else
            {
                for (int t = 0; t < nsteps; t++)
                {
                    times[t] = (float)DateTime.Now.AddDays(t).ToOADate();
                }
            }

            sw.WriteLine(ncol + "," + nrow + "," + nsteps);
            var timestr = string.Join("\n", times);

            sw.WriteLine(timestr);
            sw.Close();

            for (int t = 0; t < nsteps; t++)
            {
                var mat_step = grid.ToMatrix <float>(mat[var_index, t.ToString(), ":"], 0);
                for (int r = 0; r < nrow; r++)
                {
                    for (int c = 0; c < ncol; c++)
                    {
                        //var bb= (byte) mat_step[r][c];
                        //byte hi = (byte)(bb >> 8);
                        //byte low = (byte)(bb - (short)(hi << 8));
                        var  a   = (int)mat_step[r][c];
                        byte hi  = (byte)(a >> 8);
                        byte low = (byte)(a - (a << 8));

                        bw.Write(low);
                        bw.Write(hi);
                    }
                }
                progress = t * 100 / nsteps;
                cancelProgressHandler.Progress("Package_Tool", progress, "Processing step:" + t);
            }

            sw.Close();
            fs.Close();
            bw.Close();
            return(true);
        }
コード例 #28
0
ファイル: PMPET7.cs プロジェクト: zhaowilliam/Visual-HEIFLOW
        public bool Execute1(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            //(double tavrg, double tmax, double tmin, double rh, double airP, double wind2, double Rnet, DateTime day)

            string[] files = new string[] { AverageTemperatureFileName, MaxTemperatureFileName, MinTemperatureFileName, RelativeHumidityFileName,
                                            AirPressureFileName, WindSpeedFileName, NetRadiationFileName };

            int nfile = files.Length;

            DataCubeStreamReader[] ass  = new DataCubeStreamReader[nfile];
            DataCube <float>[]     mats = new DataCube <float> [nfile];
            for (int i = 0; i < nfile; i++)
            {
                ass[i] = new DataCubeStreamReader(files[i]);
                ass[i].LoadDataCube();
                mats[i] = ass[i].DataCube;
            }
            int progress         = 0;
            int count            = 1;
            int nstep            = mats[0].DateTimes.Length;
            int ncell            = mats[0].Size[2];
            PenmanMonteithET pet = new PenmanMonteithET();

            var mat_out = new DataCube <float>(1, nstep, ncell);

            mat_out.Name      = "mat";
            mat_out.Variables = new string[] { "pet" };

            for (int t = 0; t < nstep; t++)
            {
                for (int i = 0; i < ncell; i++)
                {
                    var tav  = mats[0][0, t, i];
                    var tmax = mats[1][0, t, i];
                    var tmin = mats[2][0, t, i];
                    if (InputTemperatureUnit == TemperatureUnit.Fahrenheit)
                    {
                        tmax = (float)UnitConversion.Fahrenheit2Kelvin(tmax);
                        tmin = (float)UnitConversion.Fahrenheit2Kelvin(tmin);
                        tav  = (float)UnitConversion.Fahrenheit2Kelvin(tav);
                    }
                    var et0 = pet.ET0(0, 0, tav, tmax, tmin,
                                      mats[3][0, t, i], mats[4][0, t, i], mats[5][0, t, i], mats[6][0, t, i], mats[0].DateTimes[t]);
                    // var et1 = (float)pet.ET0(40, 100, tav, tmax, tmin,
                    //mats[3].Value[0][t][i], mats[4].Value[0][t][i], mats[5].Value[0][t][i], 7, mats[0].DateTimes[t], 0.1);
                    if (et0 <= 0)
                    {
                        et0 = 0.1;
                    }
                    if (OutputLengthUnit == LengthUnit.inch)
                    {
                        mat_out[0, t, i] = (float)System.Math.Round(et0 * UnitConversion.mm2Inch, 3);
                    }
                    else
                    {
                        mat_out[0, t, i] = (float)System.Math.Round(et0, 3);
                    }
                }

                progress = t * 100 / nstep;
                if (progress > count)
                {
                    cancelProgressHandler.Progress("Package_Tool", progress, "Processing step:" + (t + 1));
                    count++;
                }
            }
            mat_out.DateTimes = mats[0].DateTimes;
            Workspace.Add(mat_out);

            return(true);
        }
コード例 #29
0
ファイル: IDW.cs プロジェクト: zhaowilliam/Visual-HEIFLOW
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            IFeatureSet fs_source = null;
            IFeatureSet fs_target = null;

            if (SourceFeatureLayer != null)
            {
                fs_source = SourceFeatureLayer.DataSet as IFeatureSet;
            }
            else if (TypeConverterEx.IsNotNull(SourceFeatureFile))
            {
                fs_source = FeatureSet.Open(SourceFeatureFile);
            }

            if (TargetFeatureLayer != null)
            {
                fs_target = TargetFeatureLayer.DataSet as IFeatureSet;
            }
            else if (TypeConverterEx.IsNotNull(TargetFeatureFile))
            {
                fs_target = FeatureSet.Open(TargetFeatureFile);
            }

            if (fs_source == null || fs_target == null)
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "Failed. The inputs are invalid.");
                return(false);
            }

            CSVFileStream csv     = new CSVFileStream(DataFileName);
            var           ts_data = csv.Load <double>();

            cancelProgressHandler.Progress("Package_Tool", 1, "Time series at known sites loaded");
            int    nsource_sites = fs_source.DataTable.Rows.Count;
            int    ntar_sites    = fs_target.DataTable.Rows.Count;
            int    nstep         = ts_data.Size[0];
            int    nsite_data    = ts_data.Size[1];
            int    progress      = 0;
            int    count         = 1;
            double sumOfDis      = 0;
            double sumOfVa       = 0;

            if (nsite_data != nsource_sites)
            {
                cancelProgressHandler.Progress("Package_Tool", 100, "the number of sites in the data file dose not match to that in the source feature file");
                return(false);
            }
            else
            {
                if (Neighbors > nsource_sites)
                {
                    Neighbors = nsource_sites;
                }
                var known_sites      = new Site[nsource_sites];
                DataCube <float> mat = new DataCube <float>(1, nstep, ntar_sites);
                mat.DateTimes      = new DateTime[nstep];
                mat.Name           = OutputDataCube;
                mat.TimeBrowsable  = true;
                mat.AllowTableEdit = false;
                for (int i = 0; i < nsource_sites; i++)
                {
                    var cor = fs_source.Features[i].Geometry.Coordinate;
                    known_sites[i] = new Site()
                    {
                        LocalX = cor.X,
                        LocalY = cor.Y,
                        ID     = i
                    };
                }
                for (int i = 0; i < ntar_sites; i++)
                {
                    var cor        = fs_target.Features[i].Geometry.Coordinate;
                    var site_intep = new Site()
                    {
                        LocalX = cor.X,
                        LocalY = cor.Y,
                        ID     = i
                    };
                    var neighborSites = FindNeareastSites(Neighbors, known_sites, site_intep);
                    for (int j = 0; j < nstep; j++)
                    {
                        sumOfDis = 0;
                        sumOfVa  = 0;
                        foreach (var nsite in neighborSites)
                        {
                            var vv = ts_data.GetValue(j, nsite.ID);
                            if (vv < MaximumValue)
                            {
                                double temp = 1 / System.Math.Pow(nsite.Distance, Power);
                                sumOfVa  += vv * temp;
                                sumOfDis += temp;
                            }
                        }
                        if (sumOfDis != 0)
                        {
                            mat[0, j, i] = (float)(sumOfVa / sumOfDis);
                            if (!AllowNegative && mat[0, j, i] < 0)
                            {
                                mat[0, j, i] = MinmumValue;
                            }
                        }
                        else
                        {
                            mat[0, j, i] = MinmumValue;
                        }
                    }
                    progress = (i + 1) * 100 / ntar_sites;
                    if (progress > count)
                    {
                        cancelProgressHandler.Progress("Package_Tool", progress, "Caculating Cell: " + (i + 1));
                        count++;
                    }
                }
                for (int j = 0; j < nstep; j++)
                {
                    mat.DateTimes[j] = Start.AddSeconds(j * TimeStep);
                }
                cancelProgressHandler.Progress("Package_Tool", 100, "");
                Workspace.Add(mat);
                fs_source.Close();
                fs_target.Close();
                return(true);
            }
        }
コード例 #30
0
        public override bool Execute(DotSpatial.Data.ICancelProgressHandler cancelProgressHandler)
        {
            int    var_indexA = 0;
            var    mat        = Get3DMat(Matrix, ref var_indexA);
            double prg        = 0;
            var    dic        = GetZone();
            int    nzone      = dic.Keys.Count;


            if (BaseTimeStep >= 0 && BaseTimeStep < mat.Size[0])
            {
                var vec = mat[var_indexA, BaseTimeStep.ToString(), ":"];
                for (int c = 0; c < nzone; c++)
                {
                    var        key           = dic.Keys.ElementAt(c);
                    List <int> list_selected = new List <int>();
                    for (int i = 0; i < dic[key].Count; i++)
                    {
                        if (vec[i] != NoDataValue)
                        {
                            list_selected.Add(dic[key][i]);
                        }
                    }
                    dic[key] = list_selected;
                }
            }

            if (mat != null)
            {
                //FeatureLayer.DataSet
                int nstep = mat.Size[1];
                int ncell = mat.Size[2];


                var mat_out = new DataCube <float>(1, nstep, nzone);
                mat_out.Name      = Output;
                mat_out.Variables = new string[] { "Mean" };
                for (int t = 0; t < nstep; t++)
                {
                    for (int c = 0; c < nzone; c++)
                    {
                        var   sub_id  = dic[dic.Keys.ElementAt(c)];
                        int   nsub_id = sub_id.Count;
                        float sum     = 0;
                        int   len     = 0;
                        for (int j = 0; j < nsub_id; j++)
                        {
                            if (mat[var_indexA, t, sub_id[j]] != NoDataValue)
                            {
                                sum += mat[var_indexA, t, sub_id[j]];
                                len++;
                            }
                        }
                        if (len > 0)
                        {
                            mat_out[0, t, c] = sum / len;
                        }
                        else
                        {
                            mat_out[0, t, c] = 0;
                        }
                    }
                    prg = (t + 1) * 100.0 / nstep;
                    if (prg % 10 == 0)
                    {
                        cancelProgressHandler.Progress("Package_Tool", (int)prg, "Caculating Step: " + (t + 1));
                    }
                }
                Workspace.Add(mat_out);
                return(true);
            }
            else
            {
                return(false);
            }
        }