예제 #1
0
        public void Add(string[] cbttPcodeList, DateTime t1, DateTime t2,
            HydrometHost svr = HydrometHost.PN, TimeInterval interval = TimeInterval.Monthly, int back=0)
        {
            // make cbttPcodeList unique.
            List<string> lst = new List<string>(cbttPcodeList);
            cbttPcodeList =  lst.Distinct().ToArray();

            //minT = t1;
            //maxT = t2;
            m_interval = interval;

            string query = String.Join(",",cbttPcodeList);

            if (query.Length >0)
            {
                DataTable m_table = new DataTable();
                if (interval == TimeInterval.Monthly)
                {
                    m_table = HydrometDataUtility.MPollTable(svr, query, t1, t2);
                }
                else if (interval == TimeInterval.Daily)
                {
                    m_table = HydrometDataUtility.ArchiveTable(svr, query, t1, t2,back);
                }
                else if (interval == TimeInterval.Irregular)
                {
                    m_table = HydrometDataUtility.DayFilesTable(svr, query, t1, t2,back);
                }
                m_table.ExtendedProperties.Add("interval", interval.ToString());
                s_counter++;
                m_table.TableName = svr.ToString()+"_"+interval.ToString() + s_counter;
                m_dataSet.Tables.Add(m_table);
            }
        }
예제 #2
0
        public static DataTable DayFilesTable(HydrometHost svr, string query, DateTime t1, DateTime t2, int back = 0, int interval = 0)
        {
            query = HydrometInfoUtility.ExpandQuery(query, TimeInterval.Irregular);

            string cgiUrl = ReclamationURL.GetUrlToDataCgi(svr, TimeInterval.Irregular);

            var rval = Table(cgiUrl, query, t1, t2, back);

            if (interval != 0 && rval.Rows.Count > 0)
            {// put nulls in table as needed.
                rval.PrimaryKey = new DataColumn[] { rval.Columns[0] };
                DateTime next = Convert.ToDateTime(rval.Rows[0][0]).AddMinutes(interval); ;

                for (int i = 1; i < rval.Rows.Count; i++)
                {
                    DateTime t = Convert.ToDateTime(rval.Rows[i][0]);

                    if (t > next)
                    {// insert new row
                        var row = rval.NewRow();
                        row[0] = next;
                        next = next.AddMinutes(interval);
                        rval.Rows.InsertAt(row, i);
                    }
                    else
                    {
                        next = t.AddMinutes(interval);
                    }
                }
            }
            rval.PrimaryKey = null;
            return rval;
        }
예제 #3
0
        public static DataTable ArchiveTable(HydrometHost server, string query, DateTime t1, DateTime t2,int back=0)
        {
            query =  HydrometInfoUtility.ExpandQuery(query, TimeInterval.Daily);

            string cgiUrl = ReclamationURL.GetUrlToDataCgi(server, TimeInterval.Daily);

            return Table(cgiUrl, query, t1, t2, back);
        }
예제 #4
0
파일: HydrometDMI.cs 프로젝트: usbr/Pisces
 /// <summary>
 /// 
 /// </summary>
 /// <param name="server">either pnhyd0 or yakhyd</param>
 /// <param name="controlFilename">riverware control file</param>
 /// <param name="startDate">riverware simulation start date</param>
 public HydrometDMI(HydrometHost server, string controlFilename, 
     DateTime startDate, DateTime endDate)
 {
     controlFile1 = new ControlFile(controlFilename);
     this.startDate = startDate;
     this.endDate = endDate;
     this.server = server;
 }
예제 #5
0
        private void ReadDaily(DateTime t1, DateTime t2, HydrometHost svr)
        {
            qu = new HydrometDailySeries(controlPoint.StationQU, "QU", svr);
            qd = new HydrometDailySeries(controlPoint.StationQD, "QD", svr);

            qu.Read(t1, t2);
            qd.Read(t1, t2);

            qu.Name = "QU";
            qd.Name = "QD";
            for (int i = 0; i < reservoirNames.Length; i++)
            {
                Series s = new HydrometDailySeries(reservoirNames[i], "AF");
                s.Read(t1.AddDays(-reservoirLags[i]), t2);
                s.Name = reservoirNames[i];
                if (reservoirLags[i] != 0)
                {
                    s = Reclamation.TimeSeries.Math.Shift(s, reservoirLags[i]);
                }
                reservoirs.Add(s);
            }
        }
예제 #6
0
 public FcPlotUI()
 {
     InitializeComponent();
     optionalPercents = new int[] { };
     // Show targets by default from Jan-Jul
     if (DateTime.Now.Month <= 7)
     {
         this.showTarget.Checked = true;
     }
     if (compilePublic)
     {
         this.checkBoxDashed.Visible           = false;
         this.checkBoxOverrideFcast.Visible    = false;
         this.showTarget.Visible               = false;
         this.showGreenLines.Visible           = false;
         this.textBoxOverrideFcast.Visible     = false;
         this.textBoxTargetPercentages.Visible = false;
         this.buttonOpsMenu.Visible            = false;
         this.tabControl1.Controls.Remove(this.tabPageReport);
     }
     HydrometServer = HydrometInfoUtility.HydrometServerFromPreferences();
 }
예제 #7
0
파일: Program.cs 프로젝트: woohn/Pisces
        /// <summary>
        /// Imports instant data from Hydromet into TimeSeriesDatabase
        /// </summary>
        /// <param name="db"></param>
        private static void ImportHydrometInstant(HydrometHost host, TimeSeriesDatabase db, DateTime start,
                                                  DateTime end, string filter, string propertyFilter)
        {
            // TO DO.. the outer loop of Date ranges  (t,t3) could
            // be generated as a separate task.
            Console.WriteLine("ImportHydrometInstant");
            TimeRange timeRange = new TimeRange(start, end);

            foreach (TimeRange item in timeRange.Split(365))
            {
                int block = 1;
                foreach (string query in GetBlockOfQueries(db, TimeInterval.Irregular, filter, propertyFilter))
                {
                    Console.WriteLine("Reading " + item.StartDate + " to " + item.EndDate);
                    var table = HydrometDataUtility.DayFilesTable(host, query, item.StartDate, item.EndDate, 0);
                    Console.WriteLine("Block " + block + " has " + table.Rows.Count + " rows ");
                    Console.WriteLine(query);
                    SaveTableToSeries(db, table, TimeInterval.Irregular);
                    block++;
                }
            }

            Console.WriteLine("Finished importing 15-minute data");
        }
예제 #8
0
        internal static TimeSeriesDatabase DB()
        {
            HydrometHost h = HydrometInfoUtility.HydrometServerFromPreferences();

            var dbname = UserPreference.Lookup("TimeSeriesDatabaseName");

            if (File.Exists(dbname))
            { // local sqlite
                Logger.WriteLine("reading: " + dbname);
                var x = TryLocalDatabase(dbname, h);
                if (x != null)
                {
                    return(x);
                }
            }

            if (s_db == null || s_db.Server.Name != dbname ||
                HydrometHostDiffers(h))
            {
                if (IsPasswordBlank())
                {
                    return(null);
                }

                BasicDBServer svr = GetServer(dbname);
                if (svr == null)
                {
                    return(null);
                }
                s_db = new TimeSeriesDatabase(svr, LookupOption.TableName, false);
                s_db.Parser.VariableResolver = new HydrometVariableResolver(h);
                s_db.Parser.VariableResolver.LookupOption = LookupOption.TableName;
            }

            return(s_db);
        }
예제 #9
0
        private static bool HydrometHostDiffers(HydrometHost h)
        {
            var vr = s_db.Parser.VariableResolver as HydrometVariableResolver;

            return(h != vr.Server);
        }
예제 #10
0
파일: Program.cs 프로젝트: woohn/Pisces
        static void Main(string[] argList)
        {
            var ver = AssemblyUtility.GetVersion();

            Console.Write("HydrometServer " + ver + " " + AssemblyUtility.CreationDate() + "   System Time = " + DateTime.Now);
            Console.WriteLine();
            if (argList.Length == 0)
            {
                ShowHelp();
                return;
            }

            Arguments args = new Arguments(argList);


            string      errorFileName = "errors.txt";
            Performance perf          = new Performance();
            //   try
            {
                if (args.Contains("debug"))
                {
                    Logger.EnableLogger();
                    Reclamation.TimeSeries.Parser.SeriesExpressionParser.Debug = true;
                }

                if (args.Contains("import-rating-tables"))
                {// --import-rating-tables=site_list.csv  [--generateNewTables]     : updates usgs,idahopower, and owrd rating tables
                    ApplicationTrustPolicy.TrustAll();
                    var cfg = args["import-rating-tables"];
                    if (File.Exists(cfg))
                    {
                        RatingTableDownload.UpdateRatingTables(cfg, args.Contains("generateNewTables"));
                    }
                    else
                    {
                        Console.WriteLine("Error: File not found: " + cfg);
                    }
                    return;
                }

                if (args.Contains("run-crop-charts"))
                {
                    var str_yr = args["run-crop-charts"].Trim();
                    int year   = DateTime.Now.Year;
                    if (str_yr != "")
                    {
                        year = Convert.ToInt32(str_yr);
                    }

                    var server = PostgreSQL.GetPostgresServer("agrimet", "", "agrimet");
                    CropDatesDataSet.DB = server;
                    string dir = CropDatesDataSet.GetCropOutputDirectory(year);
                    Logger.WriteLine("output dir = " + dir);

                    CropChartGenerator.CreateCropReports(year, dir, HydrometHost.PNLinux);
                    return;
                }



                var db = TimeSeriesDatabase.InitDatabase(args);

                if (args.Contains("cli"))
                {
                    TimeInterval interval = TimeInterval.Irregular;
                    if (args["cli"] == "daily")
                    {
                        interval = TimeInterval.Daily;
                    }

                    Console.WriteLine();
                    HydrometServer.CommandLine.PiscesCommandLine cmd = new CommandLine.PiscesCommandLine(db, interval);
                    cmd.PiscesPrompt();

                    return;
                }


                if (args.Contains("processAlarms"))
                {
                    try
                    {
                        Logger.EnableLogger();
                        Logger.WriteLine("Checking for new or unconfirmed Alarms ");
                        var aq = new AlarmManager(db);
                        Logger.WriteLine("Processing Alarms");
                        aq.ProcessAlarms();
                    }
                    catch (Exception e)
                    {
                        Logger.WriteLine(e.Message);
                    }
                    return;
                }


                if (args.Contains("error-log"))
                {
                    errorFileName = args["error-log"];
                    File.AppendAllText(errorFileName, "HydrometServer.exe:  Started " + DateTime.Now.ToString() + "\n");
                }

                string propertyFilter = "";
                if (args.Contains("property-filter"))
                {
                    propertyFilter = args["property-filter"];
                }

                string filter = "";
                if (args.Contains("filter"))
                {
                    filter = args["filter"];
                }

                if (args.Contains("inventory"))
                {
                    db.Inventory();
                }



                if (args.Contains("import")) // import and process data from files
                {
                    bool computeDependencies    = args.Contains("computeDependencies");
                    bool computeDailyOnMidnight = args.Contains("computeDailyOnMidnight");


                    string searchPattern = args["import"];

                    if (searchPattern == "")
                    {
                        searchPattern = "*";
                    }

                    string       incomingPath = ConfigurationManager.AppSettings["incoming"];
                    FileImporter importer     = new FileImporter(db, DatabaseSaveOptions.Upsert);
                    importer.Import(incomingPath, computeDependencies, computeDailyOnMidnight, searchPattern);
                }



                DateTime t1;
                DateTime t2;

                SetupDates(args, out t1, out t2);

                if (args.Contains("import-hydromet-instant"))
                {
                    HydrometHost host = HydrometHost.PN;
                    if (args["import-hydromet-instant"] != "")
                    {
                        host = (HydrometHost)Enum.Parse(typeof(HydrometHost), args["import-hydromet-instant"]);
                    }

                    File.AppendAllText(errorFileName, "begin: import-hydromet-instant " + DateTime.Now.ToString() + "\n");
                    ImportHydrometInstant(host, db, t1.AddDays(-2), t2.AddDays(1), filter, propertyFilter);
                }

                if (args.Contains("import-hydromet-daily"))
                {
                    HydrometHost host = HydrometHost.PN;
                    if (args["import-hydromet-daily"] != "")
                    {
                        host = (HydrometHost)Enum.Parse(typeof(HydrometHost), args["import-hydromet-daily"]);
                    }

                    File.AppendAllText(errorFileName, "begin: import-hydromet-daily " + DateTime.Now.ToString() + "\n");
                    ImportHydrometDaily(host, db, t1, t2, filter, propertyFilter);
                }

                if (args.Contains("import-hydromet-monthly"))
                {
                    File.AppendAllText(errorFileName, "begin: import-hydromet-monthly " + DateTime.Now.ToString() + "\n");
                    ImportHydrometMonthly(db, t1.AddYears(-5), t2.AddDays(1), filter, propertyFilter);
                }


                if (args.Contains("calculate-daily"))
                {
                    DailyTimeSeriesCalculator calc = new DailyTimeSeriesCalculator(db, TimeInterval.Daily,
                                                                                   filter, propertyFilter);
                    File.AppendAllText(errorFileName, "begin: calculate-daily " + DateTime.Now.ToString() + "\n");
                    calc.ComputeDailyValues(t1, t2, errorFileName);
                }

                if (args.Contains("calculate-monthly"))
                {
                    MonthlyTimeSeriesCalculator calc = new MonthlyTimeSeriesCalculator(db, TimeInterval.Monthly,
                                                                                       filter, propertyFilter);
                    File.AppendAllText(errorFileName, "begin: calculate-monthly " + DateTime.Now.ToString() + "\n");
                    //calc.ComputeDailyValues(t1, t2, errorFileName);
                    calc.ComputeMonthlyValues(t1, t2, errorFileName);
                }


                if (args.Contains("copy-daily"))
                {
                    var tablename = args["copy-daily"];

                    if (tablename == "" || args["source"] == "")
                    {
                        Console.WriteLine("Error: --copy-daily=tablename requires tablename, and requires --source=connectionString");
                        ShowHelp();
                        return;
                    }
                    bool   compare          = args.Contains("compare");
                    string connectionString = args["source"];

                    Copy(TimeInterval.Daily, connectionString, tablename, (PostgreSQL)db.Server, t1, t2, compare);
                    return;
                }


                if (args.Contains("update-period-of-record"))
                {
                    var sc = db.GetSeriesCatalog("isfolder=0");

                    var prop = db.GetSeriesProperties(true);
                    for (int i = 0; i < sc.Count; i++)
                    {
                        var s   = db.GetSeries(sc[i].id);
                        var por = s.GetPeriodOfRecord();

                        s.Properties.Set("count", por.Count.ToString());

                        if (por.Count == 0)
                        {
                            s.Properties.Set("t1", "");
                            s.Properties.Set("t2", "");
                        }
                        else
                        {
                            s.Properties.Set("t1", por.T1.ToString("yyyy-MM-dd"));
                            s.Properties.Set("t2", por.T2.ToString("yyyy-MM-dd"));
                        }
                        Console.WriteLine(s.Name);
                    }
                    db.Server.SaveTable(prop);
                }

                db.Server.Cleanup();


                File.AppendAllText(errorFileName, "HydrometServer.exe:  Completed " + DateTime.Now.ToString() + "\n");
            }
            //catch (Exception e )
            //{
            //    Logger.WriteLine(e.Message);
            //    File.AppendAllText(errorFileName, "Error: HydrometServer.exe: \n"+e.Message);
            //    // Console.ReadLine();
            //    throw e;
            //}

            var  mem = GC.GetTotalMemory(true);
            long mb  = mem / 1024 / 1024;

            Console.WriteLine("Memory Usage: " + mb.ToString() + " Mb");
            perf.Report("HydrometServer: finished ");
        }
예제 #11
0
 public HydrometVariableResolver(HydrometHost h= HydrometHost.PN)
     : base()
 {
     svr = h;
 }
예제 #12
0
 public HydrometVariableResolver(HydrometHost h = HydrometHost.PN) : base()
 {
     svr = h;
 }
예제 #13
0
        public static Series Read(string cbtt, string pcode, DateTime t1, DateTime t2,
            TimeInterval interval, HydrometHost hydrometServer)
        {
            Series s = new Series();

            if (interval == TimeInterval.Daily)
            {
                s = HydrometDailySeries.Read(cbtt, pcode, t1, t2, hydrometServer);
            }
            else if (interval == TimeInterval.Irregular)
            {
                s = HydrometInstantSeries.Read(cbtt, pcode, t1, t2, hydrometServer);
            }
            else if (interval == TimeInterval.Monthly)
            {
                s = new HydrometMonthlySeries(cbtt, pcode,hydrometServer);
                s.Read(t1, t2);
            }
            else
            {
                throw new ArgumentException("Undefined TimeInterval", interval.ToString());
            }

            return s;
        }
예제 #14
0
        private void UpdateTabs()
        {
            if (tabControl1.SelectedTab == tabPageAdvanced && advanced == null)
            {
                if (Login.AdminPasswordIsValid())
                {
                    advanced        = new AdvancedControl();
                    advanced.Parent = tabPageAdvanced;
                    advanced.Dock   = DockStyle.Fill;
                }
            }

            if (tabControl1.SelectedTab == tabPageArc && arcEditor == null)
            {
                arcEditor        = new TimeSeriesEditor(TimeInterval.Daily);
                arcEditor.Parent = tabPageArc;
                arcEditor.Dock   = DockStyle.Fill;
            }
            else
            if (tabControl1.SelectedTab == tabPageDay && dayEditor == null)
            {
                dayEditor        = new TimeSeriesEditor(TimeInterval.Irregular);
                dayEditor.Parent = tabPageDay;
                dayEditor.Dock   = DockStyle.Fill;
            }
            else
            if (tabControl1.SelectedTab == tabPageMPoll && mpollEditor == null)
            {
                HydrometHost svr = HydrometInfoUtility.HydrometServerFromPreferences();

                mpollEditor        = new TimeSeriesEditor(TimeInterval.Monthly);
                mpollEditor.Parent = tabPageMPoll;
                mpollEditor.Dock   = DockStyle.Fill;
            }
            else if (tabControl1.SelectedTab == tabPageSetup)
            {
                if (setup1 == null)
                {
                    setup1        = new Settings();
                    setup1.Parent = tabPageSetup;
                    setup1.Dock   = DockStyle.Fill;
                }
                setup1.ReadUserPref();
            }
            //else if( tabControl1.SelectedTab == tabPageGraphTool && graphTabs == null)
            //{
            //    graphTabs = new Graphing.GraphingTabs();
            //    graphTabs.Parent = tabPageGraphTool;
            //    graphTabs.Dock = DockStyle.Fill;
            //}
            else if (tabControl1.SelectedTab == tabPageHydrographEditor && hydroEditor == null)
            {
                hydroEditor        = new TimeSeriesHydrographEditor(TimeInterval.Daily);
                hydroEditor.Parent = tabPageHydrographEditor;
                hydroEditor.Dock   = DockStyle.Fill;
            }
            else if (tabControl1.SelectedTab == tabPageFcplot && fcUi == null)
            {
                fcUi        = new FcPlot.FcPlotUI();
                fcUi.Parent = tabPageFcplot;
                fcUi.Dock   = DockStyle.Fill;
            }
            else if (tabControl1.SelectedTab == tabPageStats && statsControl1 == null)
            {
                statsControl1        = new Stats.StatsControl();
                statsControl1.Parent = tabPageStats;
                statsControl1.Dock   = DockStyle.Fill;
            }
            else if (tabControl1.SelectedTab == tabPageReports && reportControl1 == null)
            {
                reportControl1        = new Reports.Reports(); //new Reports.YakimaStatus();
                reportControl1.Parent = tabPageReports;
                reportControl1.Dock   = DockStyle.Fill;
            }
            else if (tabControl1.SelectedTab == tabPageSnowGG && snowGG1 == null)
            {
                snowGG1        = new SnowGG.SnowGG();
                snowGG1.Parent = tabPageSnowGG;
                snowGG1.Dock   = DockStyle.Fill;
            }
            else if (tabControl1.SelectedTab == tabPageUpdater && import1 == null)
            {
                import1        = new ImportDaily();
                import1.Parent = tabPageDailyImport;
                import1.Dock   = DockStyle.Fill;

                var fdr = new Import.ImportFDRTemperature();
                fdr.Parent = tabPageFdrImport;
                fdr.Dock   = DockStyle.Fill;
            }
            else if (tabControl1.SelectedTab == tabPageRecords && records == null)
            {
                records        = new DailyRecordWorkup();
                records.Parent = tabPageRecords;
                records.Dock   = DockStyle.Fill;
            }

            if (tabControl1.SelectedTab == tabPageShifts && shifts == null)
            {
                shifts        = new Shift.ShiftInput();
                shifts.Parent = tabPageShifts;
                shifts.Dock   = DockStyle.Fill;
            }

            if (tabPageFcplot == null)
            {
                if (FcPlotDataSet.HasRuleCurves())
                {
                    fcUi        = new FcPlot.FcPlotUI();
                    fcUi.Parent = tabPageFloodControl;
                    fcUi.Dock   = DockStyle.Fill;
                }
                else
                {
                    this.tabControl1.TabPages.Remove(tabPageFcplot);
                }
            }
        }
예제 #15
0
 public static DataTable MPollTable(HydrometHost server, string query, DateTime t1, DateTime t2)
 {
     query = HydrometInfoUtility.ExpandQuery(query, TimeInterval.Monthly);
     string cgiUrl = ReclamationURL.GetUrlToDataCgi(server, TimeInterval.Monthly);
     Logger.WriteLine("url:" + cgiUrl);
     return Table(cgiUrl, query, t1, t2, endOfMonth: true);
 }
예제 #16
0
        static void Main(string[] args)
        {
            if (args.Length < 4 || args.Length > 5)
            {
                Console.WriteLine("Usage:");
                Console.WriteLine("30_year_avg creates 30 year average pisces database");
                Console.WriteLine("Usage:  30_year_avg  config.csv group|all  output.db boise|yakima [hmet.txt]");
                Console.WriteLine("config.csv example below:\n");
                Console.WriteLine("group,station,daily_pcode,title,ylabel");
                Console.WriteLine("Boise Payette,plei,qd,\"Payette River near Letha, ID\",Discharge - cfs");
                Console.WriteLine(" Boise Payette,emm,qd,\"Payette River near Emmett, ID\",Discharge - cfs");
                Console.WriteLine("\ngroup is used to filter specific parts of config file.  enter all to disable filtering");
                Console.WriteLine("output.db is the name of a pisces database that will be created.");
                Console.WriteLine("boise|yakima specifiy which hydromet server to read data from");
                Console.WriteLine("hmet.txt is an optional output with hydromet daily format");
                return;
            }

            string fn = args[2];

            if (File.Exists(fn))
            {
                Console.WriteLine("Deleting existing database ");
                File.Delete(fn);
            }
            var svr = new SQLiteServer(fn);
            var db  = new TimeSeriesDatabase(svr);

            HydrometHost host = HydrometHost.PN;

            if (args[3] == "yakima")
            {
                host = HydrometHost.Yakima;
            }


            DataTable config = new CsvFile(args[0]);

            if (args[1] != "all")
            {      // filter out specific group
                config = DataTableUtility.Select(config, "group = '" + args[1] + "'", "");
            }

            if (args.Length == 5 && File.Exists(args[4]))
            {
                Console.WriteLine("deleting " + args[4]);
                File.Delete(args[4]);
            }

            var prevFolderName = Guid.NewGuid().ToString();

            PiscesFolder folder = null;

            for (int x = 0; x < config.Rows.Count; x++)
            {
                var    row        = config.Rows[x];
                string folderName = row["group"].ToString();

                if (prevFolderName != folderName)
                {
                    prevFolderName = folderName;
                    folder         = db.AddFolder(folderName);
                }
                string CBTT  = row["station"].ToString();
                string Pcode = row["daily_pcode"].ToString();
                Console.WriteLine(CBTT + " " + Pcode);
                Series s = new HydrometDailySeries(CBTT, Pcode, host);
                // Data ranges collected
                var t1 = new DateTime(1980, 10, 1);
                var t2 = new DateTime(2010, 9, 30);
                s.Read(t1, t2);
                var s7100 = LabelAndSave30Year(db, 7100, CBTT, Pcode, folder, host);
                var s8110 = LabelAndSave30Year(db, 8110, CBTT, Pcode, folder, host);
                var s6190 = LabelAndSave30Year(db, 6190, CBTT, Pcode, folder, host);

                //Creates thirty-year average from raw data and adds to database
                var avg = Reclamation.TimeSeries.Math.MultiYearDailyAverage(s, 10);
                avg.Name            = "avg 1981-2010 " + CBTT + " " + Pcode;
                avg.Table.TableName = "avg_1981_2010" + CBTT + "" + Pcode;
                db.AddSeries(avg, folder);
                avg = Reclamation.TimeSeries.Math.ShiftToYear(avg, 8109);
                if (args.Length == 5)
                {
                    HydrometDailySeries.WriteToArcImportFile(avg, CBTT, Pcode, args[4], true);
                }
            }
        }
예제 #17
0
 public HydrometDailySeries(string cbtt, string pcode, HydrometHost server)
 {
     Init(cbtt, pcode, server);
 }
예제 #18
0
        private static void DrawTeacup(HydrometHost HServer, DateTime date, Bitmap bmp, ConfigLine cfg)
        {
            string number = "";
            string Percent;
            double percent;
            double value = ReadHydrometValue(cfg.cbtt, cfg.pcode, date, HServer);

            //Determine the percent full

            if (value == 998877)
            {
                percent = 0;
            }
            else
            {
                percent = value / cfg.capacity;
            }

            if (percent >= 1)
            {
                percent = 1;
            }
            else if (percent <= 0)
            {
                percent = 0;
            }

            double area = 400 * cfg.size * cfg.size + 3200 * cfg.size * cfg.size * percent;

            area = Math.Sqrt(area) - 20 * cfg.size;
            area = area / (40 * cfg.size);
            if (area >= 1.000)
            {
                area = 1.000;
            }
            if (area <= 0.000)
            {
                area = 0.000;
            }
            Int32 full = Convert.ToInt32(area * 100);

            //check for missing values and set the output number of digits to report
            if (value == 998877)
            {
                number  = "MISSING";
                Percent = "MISSING";
            }
            else
            {
                number  = value.ToString("F0");
                Percent = (percent * 100).ToString("F0");
            }
            //Create Isosceles trapizoid
            string Text     = cfg.ResName + "\n" + number + "/" + cfg.capacity + "\n" + Percent + "% Full";
            Point  Location = new Point(cfg.col, cfg.row);
            //Line color and size
            Pen bluePen = new Pen(Color.RoyalBlue, 2);
            //Fill Color for background
            SolidBrush whiteBrush = new SolidBrush(Color.White);
            SolidBrush blueBrush  = new SolidBrush(Color.RoyalBlue);
            //Setting the points of the trapezoid
            Point point1 = new Point(cfg.col, cfg.row);                                 //lower left
            Point point2 = new Point(cfg.col + 10 * cfg.size, cfg.row);                 //lower right
            Point point3 = new Point(cfg.col + 20 * cfg.size, cfg.row - 20 * cfg.size); //upper right
            Point point4 = new Point(cfg.col - 10 * cfg.size, cfg.row - 20 * cfg.size); //upper left

            Point[] curvePoints = { point1, point2, point3, point4 };
            //setting points of percent full
            Point point1f = new Point(cfg.col, cfg.row);                                                                           //lower left
            Point point2f = new Point(cfg.col + 10 * cfg.size, cfg.row);                                                           //lower right
            Point point3f = new Point(cfg.col + 10 * cfg.size + cfg.size * full * 10 / 100, cfg.row - 20 * cfg.size * full / 100); //upper right
            Point point4f = new Point(cfg.col - 10 * cfg.size * full / 100, cfg.row - 20 * cfg.size * full / 100);                 //upper left

            Point[] fullPoints = { point1f, point2f, point3f, point4f };
            //Create Graphics
            using (Graphics graphics = Graphics.FromImage(bmp))
            {
                using (Font arialFont = new Font("Arial", 8))
                {
                    graphics.FillPolygon(whiteBrush, curvePoints);
                    graphics.DrawPolygon(bluePen, curvePoints);
                    graphics.DrawString(Text, arialFont, Brushes.Red, Location);
                    graphics.FillPolygon(blueBrush, fullPoints);
                }
            }
        }
예제 #19
0
        /// <summary>
        /// Creates Daily and Summary Crop Reports
        /// </summary>
        /// <param name="cbttList">list of cbtt to create charts for</param>
        /// <param name="year">year used to filter database of crop dates</param>
        /// <param name="date">terminate date (or if null use etr terminate date)</param>
        public static void CreateCropReports(int year, string outputDirectory, HydrometHost host = HydrometHost.PNLinux)
        {
            s_host = host;
            CropDatesDataSet.CropDatesDataTable cropTable = new CropDatesDataSet.CropDatesDataTable();

            cropTable = CropDatesDataSet.GetCropDataTable(year, false);

            var cbttList = (from row in cropTable.AsEnumerable() // get list of cbtt
                            select row.cbtt).Distinct().ToArray();

            if (cbttList.Length > 1)
            {// for performance query hydromet only once.
                DateTime t1 = new DateTime(year, 1, 1);
                DateTime t2 = new DateTime(year, 12, 31);
                if (t2 > DateTime.Now.Date)
                {
                    t2 = DateTime.Now.Date;
                }

                AddToCache(host, cbttList, "ETRS", t1, t2);

                var pcode = new string[] { "MX", "MN", "PP", "TA", "UA", "WG" };
                for (int i = 0; i < pcode.Length; i++)
                { // without 192 seconds., with = 21 seconds
                    AddToCache(host, cbttList, pcode[i], t1, t2);
                }
            }

            DateTime t = DateTime.Now.Date;

            for (int i = 0; i < cbttList.Length; i++)
            {
                var cropDates = cropTable.Where(x => x.cbtt == cbttList[i] &&
                                                !x.IsterminatedateNull() &&
                                                !x.IsstartdateNull() &&
                                                !x.IsfullcoverdateNull()).ToArray();

                if (cropDates.Length == 0)
                {
                    continue;
                }

                ValidateCropDates(cbttList[i], cropDates);

                var terminateDate = TerminateDate(cbttList[i], cropDates);

                if (terminateDate < DateTime.Now)
                {
                    t = terminateDate.AddDays(1);     // daily is read in one more day
                }
                else
                {
                    t = DateTime.Now.Date;
                }

                // Generates Daily and Summary Crop Charts
                var dailyTxtChart  = CreateDailyUglyTextReport(cbttList[i], t, cropDates);
                var dailyHtmlChart = CreateDailyHTMLReport(cbttList[i], t, cropDates);
                var sumChart       = CreateSummaryReport(cbttList[i], terminateDate, cropDates);

                CreateDailyHTMLWebReport(cbttList[i], t, cropDates); // for emails

                //string header = "AgriMet is excited to announce a partnership with Washington State University to icorporate AgriMet data into WSU's Irrigation Scheduler. To customize crop consumptive water use specific to your field or fields, visit http://weather.wsu.edu/is/";


                var fnDaily     = Path.Combine(outputDirectory, cbttList[i].ToLower() + "ch.txt");
                var fnDailyHtml = Path.Combine(outputDirectory, cbttList[i].ToLower() + "_crop_summary.html");
                var fnSum       = Path.Combine(outputDirectory, cbttList[i].ToLower() + terminateDate.Year.ToString().Substring(2) + "et.txt");

                File.WriteAllLines(fnDailyHtml, dailyHtmlChart.ToArray());

                WriteCropFile(dailyTxtChart, fnDaily);
                WriteCropFile(sumChart, fnSum);
            }
            Console.WriteLine(" Daily and Summary Crop Charts Saved for " + cbttList.Length + " sites");
        }
예제 #20
0
        private static double ReadHydrometValue(string cbtt, string pcode, DateTime date, HydrometHost server)
        {
            //Get hydromet data
            HydrometDailySeries s = new HydrometDailySeries(cbtt, pcode, server);

            s.Read(date, date);
            double value = 998877;

            if (s.Count > 0 && !s[0].IsMissing)
            {
                value = s[0].Value;
            }

            return(value);
        }
예제 #21
0
 internal static void ParseConnectionString(string connectionString, out HydrometHost svr, out string cbtt, out string pcode)
 {
     string str = ConnectionStringUtility.GetToken(connectionString, "server","");
     svr = (HydrometHost)Enum.Parse(typeof(HydrometHost), str);
     cbtt = ConnectionStringUtility.GetToken(connectionString, "cbtt","");
     pcode = ConnectionStringUtility.GetToken(connectionString, "pcode","");
 }
예제 #22
0
        private DataTable GetTimeSeries()
        {
            HydrometHost svr = HydrometInfoUtility.HydrometServerFromPreferences();

            string query = comboBoxInputs.Text.Trim();

            if (m_db == TimeInterval.Daily)
            {
                if (CbttOnly(query))
                {
                    string[] pcodes = HydrometInfoUtility.ArchiveParameters(query);
                    if (pcodes.Length > 0)
                    {
                        query = query + " " + String.Join(",", pcodes);
                    }
                }
                string[] tokens = query.Split(' ');
                if (tokens.Length != 2)
                {
                    return(new DataTable());
                }

                string cbtt  = tokens[0];
                string pcode = tokens[1];
                Series s     = new HydrometDailySeries(cbtt, pcode, HydrometInfoUtility.HydrometServerFromPreferences());
                var    sl    = new SeriesList();
                sl.Add(s);

                int beginningMonth = 1;
                if (checkBoxWaterYear.Checked)
                {
                    beginningMonth = 10;
                }

                var wyList = PiscesAnalysis.WaterYears(sl, this.yearSelector1.SelectedYears, false, beginningMonth, true);

                if (checkBoxCelsius.Checked)
                {
                    for (int i = 0; i < wyList.Count; i++)
                    {
                        s = wyList[i];
                        if (s.Units.ToLower() == "degrees f")
                        {
                            Reclamation.TimeSeries.Math.ConvertUnits(s, "degrees C");
                        }
                    }
                }

                // remove months outside selected range
                var list = FilterBySelectedRange(this.monthRangePicker1.MonthDayRange, wyList);


                return(list.ToDataTable(true));
                // return HydrometUtility.ArchiveTable(svr,query, T1, T2);
            }
            //else
            //    if (m_db == HydrometDataBase.Dayfiles)
            //    {

            //        if (CbttOnly(query))
            //        {
            //            string[] pcodes = Hydromet.DayfileParameters(query);
            //            if (pcodes.Length > 0)
            //            {
            //                query = query + " " + String.Join(",", pcodes);
            //            }
            //        }
            //        return HydrometUtility.DayFilesTable(svr,query, T1, T2);
            //    }
            //    else
            //        if (m_db == HydrometDataBase.MPoll)
            //        {

            //            return HydrometUtility.MPollTable(svr,query, T1, T2);
            //        }

            return(new DataTable());
        }
예제 #23
0
        private void refresh()
        {
            try
            {
                updateStatus("Reading Data...");

                Cursor = Cursors.WaitCursor;
                Sync();
                Application.DoEvents();
                DateTime t1 = this.timeSelectorBeginEnd1.T1;
                DateTime t2 = this.timeSelectorBeginEnd1.T2;

                Application.DoEvents();

                HydrometHost svr = HydrometInfoUtility.HydrometServerFromPreferences();
                hmet = new HydrometDailySeries(textBoxcbtt.Text.Trim(),
                                               textBoxPcode.Text.Trim(), svr);
                hmet.Read(t1, t2);
                int hmetCount = hmet.Count - hmet.CountMissing();

                ReadDailyExternalData(t1, t2);

                updateStatus("Found " + externalSeries.Count + " record(s) in " + GetSourceType().ToString() + " and " + hmetCount + " record(s) in hydromet");

                Application.DoEvents();
                SeriesList list = new SeriesList();
                list.Add(externalSeries);
                list.Add(hmet);

                this.teeChartExplorerView1.SeriesList = list;
                this.teeChartExplorerView1.SeriesList[0].Appearance.Color = "black";
                this.teeChartExplorerView1.SeriesList[1].Appearance.Color = "blue";
                //this.timeSeriesGraph1.Series = list;
                this.teeChartExplorerView1.Draw();
                //this.timeSeriesGraph1.Draw(true);

                if (externalSeries.Count == 0)
                {
                    updateStatus("Online data source not found or has no data...", true);
                }
                else if (hmetCount == 0)
                {
                    updateStatus("No Hydromet data...", true);
                }
                else
                {
                    Series        diff      = hmet - externalSeries;
                    List <double> diffVals  = new List <double>(diff.Values);
                    int           diffCount = diffVals.Count(v => System.Math.Abs(v) > 0.05);
                    if (diffCount > 0)
                    {
                        updateStatus("Found " + externalSeries.Count + " record(s) in " + GetSourceType().ToString() +
                                     " and " + hmetCount + " record(s) in hydromet - " + diffCount + " record(s) need updates...", true);
                    }
                    else
                    {
                        updateStatus("Found " + externalSeries.Count + " record(s) in " + GetSourceType().ToString() +
                                     " and " + hmetCount + " record(s) in hydromet.");
                    }

                    SeriesList list2 = new SeriesList();
                    list2.Add(diff);
                    timeSeriesGraph2.Series = list2;
                    timeSeriesGraph2.Series[0].Appearance.Color = "red";
                    timeSeriesGraph2.Draw(true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " \n" + ex.StackTrace);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
예제 #24
0
 public HydrometInstantSeries(string cbtt, string pcode, HydrometHost server)
 {
     Init(cbtt, pcode, server);
 }