private static void AddForecastSeries(string period, string scenario, TimeSeriesDatabase dbVic, string name, int thruMonth, string vicName) { string fn = period + scenario + ".pdb"; SQLiteServer svr = new SQLiteServer(fn); TimeSeriesDatabase db = new TimeSeriesDatabase(svr); Series sVic = dbVic.GetSeriesFromName(vicName + period + scenario); sVic.Read(); Series s = new Series(name + "_Forecast"); s.TimeInterval = TimeInterval.Monthly; s.TimeSeriesDatabase = db; s.Units = "acre-feet"; //initial model data start date and value s.Add(sVic[0].DateTime, sVic[0].Value * 1.98347 * sVic[0].DateTime.EndOfMonth().Day); for (int i = 0; i < sVic.Count; i++) { int month = sVic[i].DateTime.Month; if (month <= 6) { Point pt = new Point(); pt.DateTime = sVic[i].DateTime; pt.Value = SumThruMonthToAcreFt(sVic, pt.DateTime, thruMonth); s.Add(pt); } } db.AddSeries(s); SetSeriesDatesToBeginningOfMonth(s); ConsolePrintSeriesNameAndCount(s); }
public void AboveOrRising() { var ds = db.Alarms; ds.AddNewAlarmGroup("uny"); ds.alarm_definition.Addalarm_definitionRow(true, "uny", "uny", "pc", "above 300 or rising 1", "", 10); ds.SaveTable(ds.alarm_definition); ds.alarm_recipient.Addalarm_recipientRow("uny", 4, "5272", "office", "*****@*****.**"); ds.SaveTable(ds.alarm_recipient); Series s = new Series(); s.Parameter = "pc"; s.SiteID = "uny"; s.Add(DateTime.Parse("2016-11-21 02:00"), 38002.12); s.Add(DateTime.Parse("2016-11-21 02:15"), 38005.02); s.Add(DateTime.Parse("2016-11-21 02:30"), 38002.02); s.Add(DateTime.Parse("2016-11-21 02:45"), 38002.02); ds.Check(s); var queue = ds.GetAlarmQueue(); string sql = "list = 'uny' AND siteid = 'uny' " + "AND parameter = 'pc' AND status = 'new'"; Assert.IsTrue(queue.Select(sql).Length == 1); }
public void ReservoirContentsWithDatabase() { Logger.EnableLogger(); var fn = FileUtility.GetTempFileName(".pdb"); System.IO.File.Delete(fn); SQLiteServer svr = new SQLiteServer(fn); var db = new TimeSeriesDatabase(svr, Reclamation.TimeSeries.Parser.LookupOption.TableName,false); var c = new CalculationSeries("instant_karl_af"); var path = Path.Combine(Globals.TestDataPath, "rating_tables"); path = Path.Combine(path, "karl_af.txt"); c.Expression = "FileRatingTable(instant_karl_fb,\""+path+"\")"; c.TimeInterval = TimeInterval.Irregular; db.AddSeries(c); var fb = new Series("instant_karl_fb"); fb.TimeInterval = TimeInterval.Irregular; db.AddSeries(fb); fb.Add("1-1-2013", 1); fb.Add("1-2-2013", 2); fb.Add("1-3-2013", 3); fb.Add("1-4-2013", 4); TimeSeriesImporter ti = new TimeSeriesImporter(db); ti.Import(fb,computeDependencies:true);// this should force a calculation... var af = db.GetSeriesFromTableName("instant_karl_af"); Assert.NotNull(af, "Series not created"); af.Read(); Assert.AreEqual(4, af.Count); Assert.AreEqual(300, af[2].Value); }
public void Below() { var ds = db.Alarms; ds.AddNewAlarmGroup("lucky"); ds.alarm_definition.Addalarm_definitionRow(true, "lucky", "luc", "fb", "below 5525", "", 10); ds.SaveTable(ds.alarm_definition); ds.alarm_recipient.Addalarm_recipientRow("lucky", 4, "5272", "office", "*****@*****.**"); ds.SaveTable(ds.alarm_recipient); Series s = new Series(); s.Parameter = "fb"; s.SiteID = "luc"; s.Add(DateTime.Parse("2016-11-21 02:00"), 5520.12); s.Add(DateTime.Parse("2016-11-21 02:15"), 5520.12); s.Add(DateTime.Parse("2016-11-21 02:30"), 5520.12); s.Add(DateTime.Parse("2016-11-21 02:45"), 5520.12); ds.Check(s); var queue = ds.GetAlarmQueue(); string sql = "list = 'lucky' AND siteid = 'luc' " + "AND parameter = 'fb' AND status = 'new'"; Assert.IsTrue(queue.Select(sql).Length == 1); }
// Checks hourly ANTO flow against hourly ANTO canal flows private static void CheckANTOFlowRampingRate(Series antoQ, Series antoQC, out Series sOut_Down, out Series sOut_Up) { sOut_Down = new Series(); sOut_Up = new Series(); sOut_Down.Name = "ANTO_DailyDownRampingCheck"; sOut_Down.Provider = "Series"; sOut_Up.Name = "ANTO_DailyUpRampingCheck"; sOut_Up.Provider = "Series"; for (int i = 0; i < antoQ.Count - 24; i++) { DateTime t1 = antoQ[i].DateTime; DateTime t2 = t1.AddHours(23); // Calculate GILO change within a 24 hour period double ithQ = antoQ[t1].Value; double jthQ = antoQ[t2].Value; double rampQ = jthQ - ithQ; // Calculate total change in SLBO and DICO flows within the same period double ithQ1 = 0.0; double jthQ1 = 0.0; if (antoQC.IndexOf(t1) > 0) double.TryParse(antoQC[t1].Value.ToString(), out ithQ1); if (antoQC.IndexOf(t2) > 0) double.TryParse(antoQC[t2].Value.ToString(), out jthQ1); double rampImpact = jthQ1 - ithQ1; // Check if ANTO Q increase is more than 100% if (jthQ > 2.0 * ithQ && rampImpact < 0.0 && ithQ > 1.0 && jthQ > 1.0) { if (System.Math.Abs(rampImpact) < rampQ) sOut_Up.Add(t2, -50.0); // Assigns -50 if GILO increase is not due to decrease in DICO and SLBO operations else sOut_Up.Add(t2, -99.99); // Assigns a -99 if increase is due to change in DICO and SLBO operations } else { // Assigns a 0 if GILO flow did not increase in the last 24 hours sOut_Up.Add(t2, 0.0); } // Check if ANTO Q decrease is more than 50%; same comments as above if-then conditionals if (jthQ < 0.5 * ithQ && rampImpact > 0.0 && ithQ > 1.0 && jthQ > 1.0) { if (System.Math.Abs(rampQ) > rampImpact) sOut_Down.Add(t2, -50.0); else sOut_Down.Add(t2, -99.99); } else { sOut_Down.Add(t2, 0.0); } } }
public void Feb29Bug() { Series s = new Series(); s.Add("1-1-1921", 0); s.Add("1921-06-25", 364); var shifted = Reclamation.TimeSeries.Math.ShiftToYear(s, 2000); Assert.AreEqual(25, shifted[1].DateTime.Day); shifted.WriteToConsole(); }
public void AverageWithFlags() { Series s = new Series(); s.Add(DateTime.Parse("1/1/2013 12:30"), -55,"-"); s.Add(DateTime.Parse("1/1/2013 13:00"), 1); s.Add(DateTime.Parse("1/1/2013 13:15"), 1); s.Add(DateTime.Parse("1/1/2013 14:01"), 500,"+"); var avg = Math.DailyAverage(s,2); avg.WriteToConsole(); Assert.AreEqual(1, avg.Count); Assert.AreEqual(1, avg[0].Value,0.01); }
public void HourlyAverage() { Series s = new Series(); s.Add("1/1/2013 12:30", 55); s.Add("1/1/2013 13:00", 1); s.Add("1/1/2013 13:15", 1); s.Add("1/1/2013 14:01", 500); var avg = Math.Average(s, TimeInterval.Hourly); avg.WriteToConsole(); Assert.AreEqual(55, avg["1/1/2013 12:00:00"].Value); Assert.AreEqual(1, avg["1/1/2013 13:00:00"].Value); Assert.AreEqual(500, avg["1/1/2013 14:00:00"].Value); }
public static Series DailyEtAscePenmanMontieth(Series mm, Series mn, Series mx, Series ym, Series wr, double windHeight,Series sr, double latitude, double elevation, double Cd, double Cn) { Series rval = new Series(); rval.TimeInterval = TimeInterval.Daily; if (mn.Count == 0) { Console.WriteLine("Error: DailyEtAscePenmanMontieth -- input series mn has no data"); return rval; } DateTime t = mn[0].DateTime.Date; DateTime t2 = mn[mn.Count - 1].DateTime.Date; if (t2 > DateTime.Now.Date.AddDays(-1)) t2 = DateTime.Now.Date.AddDays(-1); while (t <= t2) { var pt = Hydromet.AsceEtCalculator.Calculate(t, mm, mn, mx, ym, wr, windHeight, sr, latitude, elevation, Cd, Cn); rval.Add(pt); t = t.AddDays(1); } return rval; }
private static Series GetSerieData(Folder folder) { var s = new Series(); s.TimeInterval = TimeInterval.Daily; foreach (var msg in folder.Messages) { var txt = msg.Body.Text; var exp = @"Pump Station Average Flow:(\s*\d{1,10}(\.){0,1}\d{0,3})\s*cfs"; Regex re = new Regex(exp); var m = Regex.Match(txt, exp); if (m.Success) { double d = Convert.ToDouble(m.Groups[1].Value); var t = Reclamation.TimeSeries.Math.RoundToNearestHour(msg.Date.Value); if (s.IndexOf(t) < 0) { s.Add(t, d); //msg.Flags.Add(ImapX.Flags.MessageFlags.Seen); msg.Flags.Add(ImapX.Flags.MessageFlags.Deleted); Console.WriteLine(t.ToString() + " " + d.ToString("F2")); } } } return s; }
public static Series FileLookupInterpolate2D(Series s1, Series s2, string fileName) { var rval = new Series(); if (s1.IsEmpty || s2.IsEmpty) { Logger.WriteLine("FileLookupInterpolate2D - input series empty"); return rval; } if (!File.Exists(fileName)) { Logger.WriteLine("FileLookupInterpolate2D - input fileName, file not found"); return rval; } CsvFile csv = new CsvFile(fileName, CsvFile.FieldTypes.AllText); foreach (var pt in s1) { Point point = pt; var s2_idx = s2.IndexOf(pt.DateTime); if (s2_idx < 0) { point.Value = Point.MissingValueFlag; } else { point.Value = Interpoloate2D(csv, pt.Value, s2[s2_idx].Value); } rval.Add(point); } return rval; }
private static void ReadDataIntoSeries(FixedWidthTextFile tf, Series s, int firstRowIndex, int columnIndex,DateTime fileDate) { for (int r = firstRowIndex; r < tf.RowCount; r++) { int hr; if (tf[r, 0].Trim() == "" || !int.TryParse(tf[r,0].Trim(),out hr)) continue; hr = Convert.ToInt32(tf[r, 0].Trim()); DateTime t = fileDate; if (hr == 24) t = t.AddDays(1);// use hour zero else t = t.AddHours(hr); var val = tf[r, columnIndex]; double d; if (!double.TryParse(val, out d)) { Logger.WriteLine("Error: parsing '" + val + "' as a number"); continue; } s.Add(t, d); } }
public void LookupIndex() { Series s = new Series(); s.Add("2006-01-01", 0); s.Add("2006-01-02", 1); s.Add("2006-01-03", 2); s.Add("2006-01-04", 3); s.Add("2006-01-05", 4); int i = s.LookupIndex(DateTime.Parse("2006-01-03 12:22 AM")); Assert.AreEqual(3, i); i = s.LookupIndex(DateTime.Parse("2006-01-03 12:22 AM"),true); Assert.AreEqual(2, i); }
public void FileRatingTable() { Series s = new Series(); s.Add(DateTime.Now.Date, 1281.95); var path = Path.Combine(Globals.TestDataPath, "rating_tables", "gcl_af.txt"); var af = TimeSeriesDatabaseDataSet.RatingTableDataTable.ComputeSeries(s, path); var x = af[0].Value; Assert.AreEqual(4543763, x, .01); }
public void PolynomialRatingEquation() { //simple equation to test ( y = 2*x ) PolynomialEquation eq = new PolynomialEquation( new double[]{0, 2.0},10, 50,"test equation"); Series s = new Series(null,"cfs",TimeInterval.Daily); s.Add(DateTime.Parse("2005-01-01"),10); s.Add(DateTime.Parse("2005-01-02"),20); s.Add(DateTime.Parse("2005-01-03"),50); s.Add(DateTime.Parse("2005-01-04"),60); s.Add(DateTime.Parse("2005-01-05"),2); Console.WriteLine("--- input series ----"); s.WriteToConsole(true); Series sp = Math.Polynomial(s,eq, DateTime.Parse("2005-01-02"), DateTime.Parse("2006-01-01")); Console.WriteLine(eq.ToString()); Console.WriteLine("--- polynomial computed series ----"); sp.WriteToConsole(true); Assert.AreEqual(4,sp.Count); // should have 4 return values double v = sp.Lookup(DateTime.Parse("2005-01-02")); Assert.AreEqual(40,v,0.00001); v = sp.Lookup(DateTime.Parse("2005-01-03")); Assert.AreEqual(sp[sp.LookupIndex(DateTime.Parse("2005-01-03"))].Flag,PointFlag.Computed); Assert.AreEqual(100,v,0.00001); // should return missing (null) for jan 4 and jan 6 v = sp.Lookup(DateTime.Parse("2005-01-04")); Assert.AreEqual(Point.MissingValueFlag,v,0.00001); v = sp.Lookup(DateTime.Parse("2005-01-05")); Assert.AreEqual(Point.MissingValueFlag,v,0.00001); }
public void EqualLengths() { var pu = new Series("daily_wrdo_pu"); pu.TimeInterval = TimeInterval.Daily; pu.Add("10-1-2014", 0); pu.Add("10-2-2014", 1); pu.Add("10-3-2014", 2); pu.Add("10-4-2014", 3); pu.Add("10-5-2014", 4); pu.Add("10-6-2014", 5); var pp = new Series("daily_wrdo_pp"); pp.TimeInterval = TimeInterval.Daily; pp.Add("10-1-2014", 0); pp.Add("10-2-2014", 1); pp.Add("10-3-2014", 1); pp.Add("10-4-2014", 1); pp.Add("10-5-2014", 1); pp.Add("10-6-2014", 1); var puNew = Reclamation.TimeSeries.Math.DailyWaterYearRunningTotal(pp, pu); for (int i = 0; i < pu.Count; i++) { Assert.AreEqual(puNew[i].Value, pu[i].Value); } }
public void ExtraCumulative() { var pu = new Series("daily_wrdo_pu"); pu.TimeInterval = TimeInterval.Daily; pu.Add("10-1-2014", 0); pu.Add("10-2-2014", 0); pu.Add("10-3-2014", 0); pu.Add("10-4-2014", 0); pu.Add("10-5-2014", 0); pu.Add("10-6-2014", 0); var pp = new Series("daily_wrdo_pp"); pp.TimeInterval = TimeInterval.Daily; pp.Add("10-5-2014", 0); pp.Add("10-6-2014", 0); var x = Reclamation.TimeSeries.Math.DailyWaterYearRunningTotal(pp, pu); x.WriteToConsole(); Console.WriteLine(x["2014-10-6"]); Assert.AreEqual(0,x["2014-10-6"].Value,"PU "); }
public void Empty() { Series pp = new Series(); pp.TimeInterval = TimeInterval.Daily; Series pu = new Series(); pu.TimeInterval = TimeInterval.Daily; pu.Add(DateTime.Now, System.Math.PI); var x = Math.DailyWaterYearRunningTotal(pp, pu); Assert.AreEqual(0, x.Count); }
public void PrimeCalculationCumulative() { var t = new DateTime(2015, 10, 1); var t2 = new DateTime(2015, 10, 5); Series s = new Series("", TimeInterval.Daily); Series cu = new Series("", TimeInterval.Daily); cu.Add(t, 100); cu.Add(t.AddDays(3), 5000); // this should be ignored. while (t <= t2) { s.Add(t, 1); t = t.AddDays(1).Date; } var rval = Math.DailyCalendarYearRunningTotal(s, cu); Assert.AreEqual(100, rval[0].Value); Assert.AreEqual(101, rval[1].Value); Assert.AreEqual(102, rval[2].Value); Assert.AreEqual(103, rval[3].Value); Assert.AreEqual(104, rval[4].Value); }
public void Negative() { Series s = new Series(); s.Add("1/6/2006", -1); s.Add("1/7/2006", -40); s.Add("1/8/2006", -50); s.Add("1/9/2006", -30); DateTime t1 = DateTime.Parse("1/6/2006"); DateTime t2 = DateTime.Parse("1/9/2006"); SeriesRange sr = new SeriesRange(s, t1, t2); double d = sr.ComputeSum(1.0); Assert.AreEqual(-44.5, d,.01, " summed using 1 as guess for midpoint"); sr.SmoothPreservingSum(); Assert.AreEqual(-50,sr.MidPointValue, 0.001); Assert.AreEqual(-1, s[0].Value,0.0001); Assert.AreEqual(-50, s[1].Value, 0.0001); Assert.AreEqual(-40, s[2].Value, 0.0001); Assert.AreEqual(-30, s[3].Value, 0.0001); }
public void EntiatRiver() { Series s = new Series(); DateTime t = new DateTime(2006, 5, 24); for (int i = 0; i < 365; i++) { s.Add(t, i); t = t.AddDays(1); } Series w = Math.ShiftToYear(s, 2000); Assert.AreEqual(2000, w[0].DateTime.Year); Assert.AreEqual(5,w[0].DateTime.Month); Assert.AreEqual(24,w[0].DateTime.Day); }
private static Series AddTwoSeriesWithDifferentLengths(Series s1, Series s2, ref DateTime t) { for (int i = 0; i < 10; i++) { s1.Add(t, 1); if (i > 5 && i < 8) { s2.Add(t, 2); } t = t.AddDays(1); } s1.WriteToConsole(); s2.WriteToConsole(); Series s3 = s1 + s2; return s3; }
public void CalendarYearCumulative() { var t = new DateTime(2015, 12, 12); var t2 = new DateTime(2016, 2, 28); Series s = new Series("", TimeInterval.Daily); Series cu = new Series("", TimeInterval.Daily); while (t <= t2) { s.Add(t, 1); t = t.AddDays(1).Date; } var rval = Math.DailyCalendarYearRunningTotal(s, cu); rval.RemoveMissing(); Assert.AreEqual(59, rval.Count); }
public void MonthlySumAndAverage() { Series s = new Series(); DateTime t = DateTime.Parse("01-01-2000"); while (t.Month == 1) { s.Add(t, t.Day); t = t.AddDays(1); } var m = Reclamation.TimeSeries.Math.MonthlySum(s); Assert.AreEqual(1, m.Count); Assert.AreEqual(496, m[0].Value, .001); m = Reclamation.TimeSeries.Math.MonthlyAverage(s); Assert.AreEqual(1, m.Count); Assert.AreEqual(16, m[0].Value, .001); }
public void Basic() { Reclamation.TimeSeries.Series s = new Series(); DateTime t = DateTime.Now.Date; for (int i = 1; i < 10; i++) { s.Add(t, i); t = t.AddHours(1); } var ma = Reclamation.TimeSeries.Math.MovingAvearge(s, 2); //s.WriteToConsole(); //ma.WriteToConsole(); /* 2007-05-22 00:00:00.00 1.00 2007-05-22 01:00:00.00 2.00 2007-05-22 02:00:00.00 3.00 2007-05-22 03:00:00.00 4.00 2007-05-22 04:00:00.00 5.00 2007-05-22 05:00:00.00 6.00 2007-05-22 06:00:00.00 7.00 2007-05-22 07:00:00.00 8.00 2007-05-22 08:00:00.00 9.00 Name: 2 hour average ScenarioName SeriesType: Irregular units: 2007-05-22 02:00:00.00 2.00 2007-05-22 03:00:00.00 3.00 2007-05-22 04:00:00.00 4.00 2007-05-22 05:00:00.00 5.00 2007-05-22 06:00:00.00 6.00 2007-05-22 07:00:00.00 7.00 2007-05-22 08:00:00.00 8.00 */ Assert.AreEqual(7, ma.Count); Assert.AreEqual(2, ma[0].Value,"2 hr moving avg"); Assert.AreEqual(3, ma[1].Value, "2 hr moving avg"); Assert.AreEqual(4, ma[2].Value, "2 hr moving avg"); Assert.AreEqual(5, ma[3].Value, "2 hr moving avg"); Assert.AreEqual(6, ma[4].Value, "2 hr moving avg"); Assert.AreEqual(7, ma[5].Value, "2 hr moving avg"); Assert.AreEqual(8, ma[6].Value, "2 hr moving avg"); }
public void ExistingDailyCumulativeBug() { var t = new DateTime(2015, 12, 12); var t2 = new DateTime(2016, 2, 28); Series s = new Series("", TimeInterval.Daily); Series cu = new Series("", TimeInterval.Daily); while (t <= t2) { s.Add(t, 1); if( t > DateTime.Parse("2016-2-1")) cu.Add(t, 1000); t = t.AddDays(1).Date; } var rval = Math.DailyCalendarYearRunningTotal(s, cu); rval.RemoveMissing(); Assert.AreEqual(27, rval.Count); Assert.AreEqual(1026, rval["2016-02-28"].Value); }
public void Merge() { Series observed = new Series(); observed.Name = "observed"; observed.TimeInterval = TimeInterval.Daily; Series estimated = new Series(); estimated.Name = "estimated"; estimated.TimeInterval = TimeInterval.Daily; DateTime t = new DateTime(2000,1,1); for (int i = 1; i <= 10; i++) { estimated.Add(t, i, PointFlag.Estimated); if( i >=5 && i <=8 ) // create observed data time steps 5,6,7,8 observed.Add(t, 100,PointFlag.None); t = t.AddDays(1).Date; } observed.WriteToConsole(true); estimated.WriteToConsole(true); var m = Math.Merge(observed, estimated); m.WriteToConsole(true); for (int i = 0; i < m.Count; i++) { var pt = m[i]; if (pt.Value > 90) Assert.IsTrue(pt.Flag == PointFlag.None); else Assert.IsTrue(pt.Flag == PointFlag.Estimated); } }
internal Series ConvertToDaily() { Series estimatedDaily = new Series(); estimatedDaily.HasFlags = true; estimatedDaily.TimeInterval = TimeInterval.Daily; if (FillMissingWithZero) { daily = Math.FillMissingWithZero(daily, daily.MinDateTime, daily.MaxDateTime); } else { daily.RemoveMissing(); } //daily.RemoveMissing(); //int[] levels = {5,10,20,30,40,50,60,70,80,90,95}; //int[] levels = {10,20,30,40,50,60,70,80,90}; List <int> levels = new List <int>(); if (MedianOnly) { levels.Add(50); } else { for (int i = 5; i <= 95; i += 2) { levels.Add(i); } } var sHydrograph = Math.SummaryHydrograph(daily, levels.ToArray(), new DateTime(2008, 1, 1), false, false, false, false);//, false); var summaryHydrographTable = sHydrograph.ToDataTable(true); for (int i = 1; i < summaryHydrographTable.Columns.Count; i++) { summaryHydrographTable.Columns[i].ColumnName = levels[i - 1].ToString(); } //DataTableOutput.Write(summaryHydrographTable, @"c:\temp\junk.csv", false); SeriesList monthlySum = new SeriesList(); for (int i = 0; i < sHydrograph.Count; i++) { Series sum = Math.MonthlyValues(sHydrograph[i], Math.Sum); sum.Name = levels[i].ToString(); monthlySum.Add(sum); } var monthlyExceedanceSums = monthlySum.ToDataTable(true); if (monthlySum.Count == 1 && levels.Count == 1) { monthlyExceedanceSums.Columns[1].ColumnName = levels[0].ToString(); } var monthlyTable = monthly.Table; DateTime t = monthly.MinDateTime; DateTime t2 = monthly.MaxDateTime; t2 = new DateTime(t2.Year, t2.Month, DateTime.DaysInMonth(t2.Year, t2.Month)); while (t < t2) { var tm = new DateTime(t.Year, t.Month, 1); if (monthly.IndexOf(tm) < 0) { estimatedDaily.AddMissing(t); } else { double mv = monthly[tm].Value; double mvcfsdays = mv / 1.98347; double exceedanceValue = 0; int exceedancePercent = LookupExceedance(monthlyExceedanceSums, t, mvcfsdays, out exceedanceValue); double ratio = 0; if (exceedanceValue != 0) { ratio = mvcfsdays / exceedanceValue; } else { ratio = 0; } double shcfs = LookupSummaryHydrograph(summaryHydrographTable, t, exceedancePercent); estimatedDaily.Add(t, shcfs * ratio, "scaled with " + exceedancePercent + "%"); } t = t.AddDays(1); } VerifyWithMonthlyVolume(monthly, estimatedDaily); // SmoothSpikes(monthly, daily, estimatedDaily); return(estimatedDaily); }
public RelativeStrengthIndex() { Name = "Relative Strength Index"; IsOverlay = false; Series.Add(new Series("Main")); }
private void timer_Tick(object sender, EventArgs e) { var x = DateTime.Now.Ticks; var tcpc = IPHelper.GetAllConnections(true) .Where(co => co.State == ConnectionStatus.ESTABLISHED && !co.IsLoopback && co.OwnerModule != null) //.AsParallel() .Select(c => new MonitoredConnection(c)) .ToList(); //) co.RemoteAddress != "::" && co.RemoteAddress != "0.0.0.0" Func <MonitoredConnection, string> groupFn; if (_isSingleMode) { groupFn = (c) => c.Owner + c.LocalPort; } else { groupFn = (c) => c.ProcName; } var groups = tcpc.GroupBy(c => groupFn(c)).ToList(); // OwnerModule.ModuleName).ToList(); int ic = 0; foreach (var grp in groups) { var existing = GroupedConnections.FirstOrDefault(s => s.Name == grp.Key); if (existing is null) { ic = (ic + 1) % LineChart.ColorsDic.Count; var br = new SolidColorBrush(LineChart.ColorsDic[ic]); existing = new GroupedView { Name = grp.Key }; existing.Brush = br; // Adding a watcher to retrieve the icon when ready (wasn't working anymore following async Icon retrieval optim) var firstInGroup = grp.First(); firstInGroup.PropertyChanged += (sender, e) => { if (e.PropertyName == nameof(Connection.Icon)) { existing.Icon = firstInGroup.Icon; } }; // Note: Icon's retrieval still has to be triggered first through a call to Connection.Icon's getter (or it will never update) existing.Icon = firstInGroup.Icon; existing.SeriesIn = new LineChart.Series() { Name = grp.Key + "_IN", Brush = br }; Series.Add(existing.SeriesIn); var color = new SolidColorBrush(LineChart.ColorsDic[ic]) { Opacity = 0.6 }; existing.SeriesOut = new LineChart.Series() { Name = grp.Key + "_OUT", Brush = color }; Series.Add(existing.SeriesOut); GroupedConnections.Add(existing); } bool iserror = false; var totalized = grp.AsParallel() .Select(realconn => { try { return(realconn.EstimateBandwidth()); } catch { iserror = true; return(new TCPHelper.TCP_ESTATS_BANDWIDTH_ROD_v0 { InboundBandwidth = 0, OutboundBandwidth = 0 }); } }) .Select(co => new { In = co.InboundBandwidth / 8, Out = co.OutboundBandwidth / 8 }) .Aggregate((ci, co) => new { In = ci.In + co.In, Out = ci.Out + co.Out }); existing.Count = grp.Count(); existing.LastIn = ResourcesLoader.FormatBytes(totalized.In, "ps"); existing.LastOut = ResourcesLoader.FormatBytes(totalized.Out, "ps"); existing.SeriesOut.Points.Add(new Point(x, totalized.Out)); existing.SeriesIn.Points.Add(new Point(x, totalized.In)); existing.IsAccessDenied = iserror; existing.LastSeen = DateTime.Now; //foreach (var realconn in grp) //{ // cnt++; // try // { // var r = realconn.EstimateBandwidth(); // sumIn += r.InboundBandwidth / 8.0; // sumOut += r.OutboundBandwidth / 8.0; // } // catch (Exception exc) // { // lastError = exc.Message; // accessDenied = true; // } //} //existing.LastError = lastError; //existing.IsAccessDenied = accessDenied; //existing.ConnectionsCount = cnt; } var removableGr = GroupedConnections.Where(gr => DateTime.Now.Subtract(gr.LastSeen).TotalMilliseconds > GroupTimeoutRemove).ToList(); foreach (var g in removableGr) { g.LastIn = "-"; g.LastOut = "-"; g.Count = 0; g.Brush = new SolidColorBrush(Colors.LightGray); GroupedConnections.Remove(g); } }
public void AddSerie(Serie serie) { Series.Add(serie); SaveChanges(); }
public void GenerateChart() { try { Chart chart = new Chart(ChartType.Column2D); Series series = null; string dataFileName = GetDataFileName(); if (string.IsNullOrEmpty(dataFileName)) { this.Error = " Empty File Name "; return; } var daraSeries = GetRenderingData(dataFileName); if (daraSeries != null) { foreach (string key in daraSeries.Keys) { series = chart.SeriesCollection.AddSeries(); series.Name = key; series.Add(new double[] { Convert.ToDouble(daraSeries[key][Params.IndexOf(ParamName)]) }); } } // chart.XAxis.TickLabels.Format = "00"; chart.XAxis.MajorTickMark = TickMarkType.Outside; chart.XAxis.Title.Caption = Path.GetFileNameWithoutExtension(DataFileName); chart.YAxis.MajorTickMark = TickMarkType.Outside; chart.YAxis.HasMajorGridlines = true; chart.PlotArea.LineFormat.Color = XColors.DarkGray; chart.PlotArea.LineFormat.Width = 1; chart.PlotArea.LineFormat.Visible = true; chart.Legend.Docking = DockingType.Right; chart.DataLabel.Type = DataLabelType.Value; chart.DataLabel.Position = DataLabelPosition.OutsideEnd; string filename = System.IO.Path.Combine(SolutionFolder, @"Documents\", Guid.NewGuid().ToString().ToUpper() + ".pdf"); PdfDocument document = new PdfDocument(filename); chartFrame.Location = new XPoint(30, 30); chartFrame.Size = new XSize(500, 600); chartFrame.Add(chart); PdfPage page = document.AddPage(); page.Size = PageSize.Letter; XGraphics gfx = XGraphics.FromPdfPage(page); chartFrame.Draw(gfx); document.Close(); Process.Start(filename); } catch { this.Error = "Something went wrong when generating the PDF reports"; } }
/// <summary> /// Main Streamflow Disaggregation script /// Follows procedures laid out by UofI's A.Acharya and Dr.Ryu /// We programmed a monthly-to-daily-disaggregation method in 2012 initially /// based on some research by University of Idaho academics; the paper that the /// program is based can be found in the links below. We've since made several /// modifications to the program mainly to make it more robust in the sense that /// it handles more cases that would have resulted in errors and to /// make the mass-balancing more appropriate. /// /// Published Journal Article - http://ascelibrary.org/doi/abs/10.1061/(ASCE)HE.1943-5584.0000818 ///Article Manuscript - http://water.cals.uidaho.edu/publications/SimpleDisaggregation_Acharya_2013.pdf /// </summary> /// <param name="daily">daily series (cfs)</param> /// <param name="monthly">monthly series (cfs or acre-feet)</param> /// <returns></returns> public static Series RMSEInterp(Series daily, Series monthly) { // Generates the monthly totals for the RMS calculations in cu.ft/month Series SSmonthTot = MonthSum(MonthlyAverage(daily)); Series TSmonthTot = MonthSum(ConvertAcreFeetToCfs(monthly)); // Builds a Series to keep track of the corresponding year with the minimum RMSe Series TSrms = RMSEGenerateMatchList(SSmonthTot, TSmonthTot); // New series for the estimated daily value Series TSdaily = new Series(); // Loop to calculate the daily estimate for (int i = 0; i < TSrms.Count; i++) { int targetYear = Convert.ToInt16(TSrms[i].Value); int sourceYear = TSrms[i].DateTime.Year; // Leap Years are fun! Catch leap/non-leap year mismatches. // If the target is a leap year, this leaves 2-29 empty DateTime tLookup; if (TSrms[i].DateTime.Month == 2 && (DateTime.IsLeapYear(targetYear) ^ DateTime.IsLeapYear(sourceYear))) { tLookup = new DateTime(targetYear, TSrms[i].DateTime.Month, 28); } else { tLookup = new DateTime(targetYear, TSrms[i].DateTime.Month, TSrms[i].DateTime.Day); } // Calculates daily ratio of the monthly total for the SS double SSmatchMonthly = SSmonthTot.Lookup(tLookup); DateTime tStart = new DateTime(targetYear, TSrms[i].DateTime.Month, 1); Series SSmatchDaily = TimeSeries.Math.FillMissingWithZero(daily.Subset(tStart, tLookup)); Series SSratioTemp = SSmatchDaily / SSmatchMonthly; // Catches NaN values if the SS monthly data is zero and leap day mass balance problems Series SSratio = new Series(); double leapDayRatio = 0.0; for (int x = 0; x < SSratioTemp.Count; x++) { Point ptX = SSratioTemp[x]; if (ptX.Value.ToString() == "NaN" || SSmatchMonthly == 0.0) { SSratio.Add(ptX.DateTime, 0.0); continue; } // Catches TS leap years and ensures that mass balance is preserved with Feb-29th if (DateTime.IsLeapYear(sourceYear) && !DateTime.IsLeapYear(targetYear) && SSratio.MinDateTime.Month == 2) { leapDayRatio = leapDayRatio + (ptX.Value / 28.0); SSratio.Add(ptX.DateTime, ptX.Value - (ptX.Value / 28.0)); } else if (!DateTime.IsLeapYear(sourceYear) && DateTime.IsLeapYear(targetYear) && SSratio.MinDateTime.Month == 2) { leapDayRatio = daily[new DateTime(SSratioTemp.MaxDateTime.Year, 2, 29)].Value / SSmatchMonthly; SSratio.Add(ptX.DateTime, ptX.Value + (leapDayRatio / 27.0)); } else { SSratio.Add(ptX); } } // Calculates the estimated daily for the TS given the monthly total and SS ratio TSdaily = RMSEGenerateDaily(TSdaily, TSmonthTot.Lookup(TSrms[i].DateTime.Date), SSmatchDaily, SSratio, targetYear, sourceYear, leapDayRatio); } return(TSdaily); }
public CommodityChannelIndex() { Name = "Commodity Channel Index"; Series.Add(new Series("Main")); }
/// <summary> /// Build a SeriesList with the trace exceedances /// </summary> /// <param name="sListIn"></param> /// <param name="excLevels"></param> /// <param name="xtraTraceCheck"></param> /// <param name="xtraTrace"></param> /// <returns></returns> private SeriesList getTraceExceedances(SeriesList sListIn, int[] excLevels, bool xtraTraceCheck, string xtraTrace, bool plotMinTrace, bool plotAvgTrace, bool plotMaxTrace) { SeriesList traceAnalysisList = new SeriesList(); // Define the index numbers from the serieslist wrt the selected exceedance level List <int> sExcIdxs = new List <int>(); foreach (var item in excLevels) { var sNew = new Series(); sNew.TimeInterval = sListIn[0].TimeInterval; sNew.Units = sListIn[0].Units; sNew.ScenarioName = item + "%Exceedance"; traceAnalysisList.Add(sNew); int excIdx; if (item > 50) { excIdx = Convert.ToInt16(System.Math.Ceiling(sListIn.Count * (100.0 - Convert.ToDouble(item)) / 100.0)); } else { excIdx = Convert.ToInt16(System.Math.Floor(sListIn.Count * (100.0 - Convert.ToDouble(item)) / 100.0)); } sExcIdxs.Add(excIdx); } // Add min trace if selected if (plotMinTrace) { var sNew = new Series(); sNew.TimeInterval = sListIn[0].TimeInterval; sNew.Units = sListIn[0].Units; sNew.ScenarioName = "Min"; traceAnalysisList.Add(sNew); sExcIdxs.Add(0); } // Add max trace if selected if (plotMaxTrace) { var sNew = new Series(); sNew.TimeInterval = sListIn[0].TimeInterval; sNew.Units = sListIn[0].Units; sNew.ScenarioName = "Max"; traceAnalysisList.Add(sNew); sExcIdxs.Add(sListIn.Count - 1); } // Define average trace container var sAvg = new Series(); sAvg.TimeInterval = sListIn[0].TimeInterval; sAvg.Units = sListIn[0].Units; sAvg.ScenarioName = "Avg"; // Populate the output serieslist with the exceddance curves var dTab = sListIn.ToDataTable(true); for (int i = 0; i < dTab.Rows.Count; i++) { var dRow = dTab.Rows[i]; DateTime t = DateTime.Parse(dRow[0].ToString()); var values = dRow.ItemArray; // Put the ith timestep values in a C# List and sort by ascending var valList = new List <double>(); var valSum = 0.0; for (int j = 1; j < values.Length; j++) { valList.Add(Convert.ToDouble(values[j].ToString())); valSum += Convert.ToDouble(values[j].ToString()); } valList.Sort(); // Grab the index corresponding to the selected exceedance level and populate the output serieslist for (int j = 0; j < sExcIdxs.Count; j++) { traceAnalysisList[j].Add(t, valList[sExcIdxs[j]], "interpolated"); } // Populate the average trace series if (plotAvgTrace) { sAvg.Add(t, valSum / valList.Count, "interpolated"); } } // Add average trace if selected if (plotAvgTrace) { traceAnalysisList.Add(sAvg); } // Add an extra reference trace if defined if (xtraTraceCheck) { //xtraTrace contains the run name "Name" var scenarioTable = Explorer.Database.GetSelectedScenarios(); var selectedScenarioRow = scenarioTable.Select("[Name] = '" + xtraTrace + "'")[0]; int selectedIdx = scenarioTable.Rows.IndexOf(selectedScenarioRow); //scenariosTable.Rows.IndexOf( if (xtraTrace == "") { throw new Exception("Select an additional trace that is between 1 and the total number of traces"); } else { traceAnalysisList.Add(sListIn[selectedIdx]); } } return(traceAnalysisList); }
public override IExplorerView Run() { Logger.WriteLine("SummaryHydrographAnalysis.Run()"); SeriesList list = Explorer.CreateSelectedSeries(); ReadSeriesList(list); if (Explorer.SelectedSeries.Length == 1 && Explorer.MergeSelected) { // merge single Year Traces. list.RemoveMissing(); var s = list.MergeYearlyScenarios(); list = new SeriesList(); list.Add(s); } view.Messages.Add(list.MissingRecordsMessage); string title = list.Text.TitleText(); string subTitle = list.MissingRecordsMessage; SeriesList myList = new SeriesList(); list.RemoveMissing(); if (Explorer.AlsoPlotYear && list.Count == 1) { int[] yearsToPlot = Explorer.PlotYear; int xtraYearCount = 0; DateTime tSumHyd1 = DateTime.Now; DateTime tSumHyd2 = DateTime.Now; foreach (var year in yearsToPlot) { YearRange yearRng = new YearRange(year, Explorer.BeginningMonth); DateTime t1 = yearRng.DateTime1; DateTime t2 = yearRng.DateTime2; Series s = Math.Subset(list[0], t1, t2); if (xtraYearCount == 0)//first series { s.Appearance.LegendText = yearRng.Year.ToString(); view.Messages.Add(yearRng.Year.ToString() + " included as separate series "); myList.Add(s); if (yearsToPlot.Length == 1) { myList.Add(list.SummaryHydrograph(Explorer.ExceedanceLevels, t1, Explorer.PlotMax, Explorer.PlotMin, Explorer.PlotAvg, true)); } else { myList.Add(list.SummaryHydrograph(new int[] { }, t1, false, false, false, true)); } tSumHyd1 = t1; tSumHyd2 = t2; } else//every series { Series sDummy = new Series(); foreach (Point pt in s) { if (!(pt.DateTime.Month == 2 && pt.DateTime.Day == 29)) //sigh... leap days... { sDummy.Add(pt.DateTime.AddYears(tSumHyd1.Year - t1.Year), pt.Value); } } sDummy.TimeInterval = s.TimeInterval; sDummy.Name = s.Name; sDummy.Units = s.Units; sDummy.Parameter = s.Parameter; sDummy.Appearance.LegendText = yearRng.Year.ToString();; view.Messages.Add(yearRng.Year.ToString() + " included as separate series "); myList.Add(sDummy); if (xtraYearCount == yearsToPlot.Length - 1)//last series { myList.Add(list.SummaryHydrograph(Explorer.ExceedanceLevels, tSumHyd1, Explorer.PlotMax, Explorer.PlotMin, Explorer.PlotAvg, true)); } else { myList.Add(list.SummaryHydrograph(new int[] { }, tSumHyd1, false, false, false, true)); } } xtraYearCount++; } } else { DateTime t = new DateTime(DateTime.Now.Year, Explorer.BeginningMonth, 1); myList = list.SummaryHydrograph(Explorer.ExceedanceLevels, t, Explorer.PlotMax, Explorer.PlotMin, Explorer.PlotAvg, true);//,true); } Explorer.WriteProgressMessage("drawing graph", 80); view.Title = title; view.SubTitle = subTitle; view.SeriesList = myList; view.DataTable = myList.ToDataTable(true); //view.Draw(); return(view); }
private static Series DailyCumulative(Series incremental, Series cumulative, int resetMonth, int resetDay) { //cumulative.Normalize(); //incremental.Normalize(); DateTime t; Series rval = new Series(); rval.TimeInterval = TimeInterval.Daily; if (incremental.Count == 0) { Console.WriteLine("there is no data "); return(rval); } if (incremental.TimeInterval != TimeInterval.Daily || cumulative.TimeInterval != TimeInterval.Daily) { throw new ArgumentException("Error: arguments must both have daily interval"); } double sum = 0.0; bool missing = false; bool primed = false; int index = 0; t = GetRunningTotalStartDate(incremental, cumulative); if (cumulative.IndexOf(t) >= 0 && !cumulative[t].IsMissing) { sum = cumulative[t].Value; rval.Add(cumulative[t]); primed = true; index = incremental.IndexOf(t) + 1; } else { index = incremental.IndexOf(t); } for ( ; index < incremental.Count; index++) { var t2 = incremental[index].DateTime; if (t2.Month == resetMonth && t2.Day == resetDay) { sum = 0.0; primed = true; missing = false; } if (primed && !missing && !incremental[index].IsMissing) { sum += incremental[index].Value; rval.Add(incremental[index].DateTime, sum); } else { rval.AddMissing(incremental[index].DateTime); Console.WriteLine("Missing data: incremental: " + incremental[index].ToString()); missing = true; } } return(rval); }
public PL() { Name = "PL"; Series.Add(new Series("Main")); }
public Momentum() { Name = "Momentum"; Series.Add(new Series("Main")); }
public void SetSeries(List <WaterLevelData> list) { try { // Init axes Axes.Clear(); Axes.Add(new LinearAxis() { Title = "meters", Position = AxisPosition.Left, Minimum = MinLevel, Maximum = MaxLevel, IsPanEnabled = false, IsZoomEnabled = false, MajorGridlineColor = OxyColor.Parse("#dddddd"), MajorGridlineThickness = 2, MajorGridlineStyle = LineStyle.Solid, MinorGridlineColor = OxyColor.Parse("#dddddd"), MinorGridlineThickness = 1, MinorGridlineStyle = LineStyle.Solid }); Axes.Add(new DateTimeAxis() { Position = AxisPosition.Bottom, Minimum = GetMinDateInDouble(), Maximum = GetMaxDateInDouble(), IsPanEnabled = false, IsZoomEnabled = false, MajorGridlineColor = OxyColor.Parse("#dddddd"), MajorGridlineThickness = 2, MajorGridlineStyle = LineStyle.Solid, Angle = 90 }); // Set alert line AlertLine.Points.Clear(); AlertLine.Points.Add(new DataPoint(GetMinDateInDouble(), AlertLineValue)); AlertLine.Points.Add(new DataPoint(GetMaxDateInDouble(), AlertLineValue)); // Create series with new values list.Sort((x, y) => x.Timestamp.CompareTo(y.Timestamp)); LineSeries series = new LineSeries { Color = OxyColor.Parse("#0000ff") }; foreach (WaterLevelData data in list) { series.Points.Add(new DataPoint(DateTimeAxis.ToDouble(data.Timestamp), data.WaterLevel)); } // Update series Series.Clear(); Series.Add(series); Series.Add(AlertLine); } catch (Exception e) { Debug.WriteLine("Error: " + e.ToString()); } // Update graph UI try { InvalidatePlot(true); } catch (Exception e) { Debug.WriteLine(e.Message + "\nReinitializing model"); } }
public virtual void AddSerie(Serie serie) { serie.StrengthTrainingItem = this; Series.Add(serie); }
/// <summary> /// Method to perform operations given an inflow and an outflow /// [JR] Need to refactor this code! Maybe make a new class like FloodOperation? something like SimulationOperation? /// </summary> /// <param name="ui"></param> internal void FcOps(FcPlotUI ui, FloodControlPoint pt, FcOpsMenu opsUI) { opsUI.toolStripStatusLabel1.Text = "Performing operations simulation..."; // Get required variables from the available resources string inflowCode = opsUI.textBoxInflowCode.Text; string outflowCode = opsUI.textBoxOutflowCode.Text; string inflowYear = opsUI.numericUpDownInflowYear.Value.ToString(); string outflowYear = opsUI.numericUpDownOutflowYear.Value.ToString(); string[] resCodes = pt.UpstreamReservoirs; double maxSpace = pt.TotalUpstreamActiveSpace; decimal inflowShift = opsUI.numericUpDownInflowShift.Value; decimal outflowShift = opsUI.numericUpDownOutflowShift.Value; string inflowScale = opsUI.textBoxInflowScale.Text; string outflowScale = opsUI.textBoxOutflowScale.Text; // redraw the main graph if (opsUI.checkBoxRedrawGraph.Checked) { ui.GraphData(); } PlotCurrentData(ui, inflowCode, outflowCode); var sOutflow = new Reclamation.TimeSeries.Hydromet.HydrometDailySeries("", ""); var sOutflowShifted = new Series(); var sInflow = new Reclamation.TimeSeries.Hydromet.HydrometDailySeries("", ""); var sInflowShifted = new Series(); DateTime t1, t2; int yr; // Get observed storage contents // [JR] we only need the last value so we can streamline this code... // or keep it as is and allow the user to start the simulation from a past date... var ithStorage = new Reclamation.TimeSeries.Hydromet.HydrometDailySeries(resCodes[0], "AF"); t1 = DateTime.Now; t2 = DateTime.Now; yr = Convert.ToInt32(ui.textBoxWaterYear.Text); ui.SetupDates(yr, ref t1, ref t2, false); ithStorage.Read(t1, t2); Series sStorage = new Series(ithStorage.Table, "content", TimeInterval.Daily); for (int i = 1; i < resCodes.Count(); i++) { ithStorage = new Reclamation.TimeSeries.Hydromet.HydrometDailySeries(resCodes[i], "AF"); t1 = DateTime.Now; t2 = DateTime.Now; yr = Convert.ToInt32(ui.textBoxWaterYear.Text); ui.SetupDates(yr, ref t1, ref t2, false); ithStorage.Read(t1, t2); Series sStorageTemp = new Series(ithStorage.Table, "content", TimeInterval.Daily); sStorage = sStorage + sStorageTemp; } //Reclamation.TimeSeries.Point lastPt = sStorage[sStorage.Count() - 1]; // could potentially start simulation from any past date... Reclamation.TimeSeries.Point lastPt = sStorage[opsUI.dateTimePickerSimStart.Value.AddDays(-1)]; // Process simulation outflow curve double outflowScaleValue; try { outflowScaleValue = Convert.ToDouble(outflowScale); } catch { outflowScaleValue = 1.0; } sOutflow = new Reclamation.TimeSeries.Hydromet.HydrometDailySeries(outflowCode.Split(' ')[0], outflowCode.Split(' ')[1]); t1 = DateTime.Now; t2 = DateTime.Now; yr = Convert.ToInt32(outflowYear); ui.SetupDates(yr, ref t1, ref t2, false); sOutflow.Read(t1, t2); sOutflowShifted = Reclamation.TimeSeries.Math.ShiftToYear(sOutflow, Convert.ToInt16(ui.textBoxWaterYear.Text) - 1); t1 = sOutflowShifted.MinDateTime; t2 = sOutflowShifted.MaxDateTime; sOutflowShifted = Reclamation.TimeSeries.Math.Shift(sOutflowShifted, Convert.ToInt32(outflowShift)); sOutflowShifted = sOutflowShifted.Subset(t1, t2); sOutflowShifted = sOutflowShifted * outflowScaleValue; if (opsUI.checkBoxUseCustomOutflow.Checked) //apply custom outflow { DateTime customT1 = opsUI.dateTimePickerCustomOutflow1.Value; DateTime customT2 = opsUI.dateTimePickerCustomOutflow2.Value; DateTime customT3 = opsUI.dateTimePickerCustomOutflow3.Value; var customV1 = Convert.ToInt32(opsUI.textBoxCustomOutflow1.Text); var customV2 = Convert.ToInt32(opsUI.textBoxCustomOutflow2.Text); Series rval = sOutflowShifted.Clone(); foreach (var item in sOutflowShifted) { DateTime sDate1 = new DateTime(customT1.Year, customT1.Month, customT1.Day); DateTime sDate2 = new DateTime(customT2.Year, customT2.Month, customT2.Day); DateTime sDate3 = new DateTime(customT3.Year, customT3.Month, customT3.Day); var ithDate = item.DateTime; if (ithDate >= sDate1 && ithDate < sDate2 && customV1 >= 0) { rval.Add(ithDate, customV1); } else if (ithDate >= sDate2 && ithDate < sDate3 && customV2 >= 0) { rval.Add(ithDate, customV2); } else { rval.Add(item); } } sOutflowShifted = rval; } CreateSeries(System.Drawing.Color.Plum, outflowYear + "-Outflow", sOutflowShifted, "right", true); // Process simulation inflow curve double inflowScaleValue; try { inflowScaleValue = Convert.ToDouble(inflowScale); } catch { inflowScaleValue = 1.0; } if (opsUI.checkBoxUseCustomInflow.Checked && opsUI.yearList.Count() > 0) { var sItem = opsUI.comboBoxEspTraces.SelectedItem; var selIndex = opsUI.yearList.IndexOf(sItem.ToString()); var s = opsUI.espList[selIndex - 1]; inflowYear = (sItem.ToString()); sInflow.Table = s.Table; sInflowShifted = Reclamation.TimeSeries.Math.Shift(sInflow, Convert.ToInt32(inflowShift)); sInflowShifted = sInflowShifted.Subset(sOutflowShifted.MinDateTime, sOutflowShifted.MaxDateTime); sInflowShifted = sInflowShifted * inflowScaleValue; CreateSeries(System.Drawing.Color.LawnGreen, inflowYear + "-ESP Inflow", sInflowShifted, "right", true); } else { sInflow = new Reclamation.TimeSeries.Hydromet.HydrometDailySeries(inflowCode.Split(' ')[0], inflowCode.Split(' ')[1]); t1 = DateTime.Now; t2 = DateTime.Now; yr = Convert.ToInt32(inflowYear); ui.SetupDates(yr, ref t1, ref t2, false); sInflow.Read(t1, t2); sInflowShifted = Reclamation.TimeSeries.Math.ShiftToYear(sInflow, Convert.ToInt16(ui.textBoxWaterYear.Text) - 1); t1 = sInflowShifted.MinDateTime; t2 = sInflowShifted.MaxDateTime; sInflowShifted = Reclamation.TimeSeries.Math.Shift(sInflowShifted, Convert.ToInt32(inflowShift)); sInflowShifted = sInflowShifted.Subset(t1, t2); sInflowShifted = sInflowShifted * inflowScaleValue; CreateSeries(System.Drawing.Color.LawnGreen, inflowYear + "-Inflow", sInflowShifted, "right", true); } // Process simulated storage curve and run storage simulation forward DateTime minDate = new DateTime(System.Math.Min(sOutflowShifted.MaxDateTime.Ticks, sInflowShifted.MaxDateTime.Ticks)); //day-shifting misaligns the max-dates of each series if (lastPt.DateTime < minDate) { var t = lastPt.DateTime; var stor = lastPt.Value; var simStorage = new Series(); var simSpill = new Series(); var simShort = new Series(); simStorage.Add(lastPt); while (t < minDate) { t = t.AddDays(1); var volIn = (sInflowShifted[t].Value * 86400.0 / 43560.0); var volOut = (sOutflowShifted[t].Value * 86400.0 / 43560.0); var tempStor = stor + volIn - volOut; if (tempStor >= maxSpace) { var spill = (tempStor - maxSpace) * 43560.0 / 86400.0; simSpill.Add(t, spill); stor = maxSpace; } else if (tempStor <= 0) { var shrt = (0 - tempStor) * 43560.0 / 86400.0; simShort.Add(t, shrt); stor = 0; } else { stor = tempStor; } simStorage.Add(t, stor); } // Add series items to chart CreateSeries(System.Drawing.Color.DodgerBlue, "Simulated Storage (" + inflowYear + "-Qin | " + outflowYear + "-Qout)", simStorage, "left", true); if (simSpill.Count() > 0) { CreateSeries(System.Drawing.Color.OrangeRed, "Simulated Spill (" + inflowYear + "-Qin | " + outflowYear + "-Qout)", simSpill, "right", true); } if (simShort.Count() > 0) { CreateSeries(System.Drawing.Color.Cyan, "Simulated Shortage (" + inflowYear + "-Qin | " + outflowYear + "-Qout)", simShort, "right", true); } } tChart1.Axes.Right.Grid.Visible = false; tChart1.Axes.Right.Title.Caption = "Flow (cfs)"; tChart1.Axes.Right.FixedLabelSize = false; SetupTChartTools(); opsUI.toolStripStatusLabel1.Text = "Showing results for (" + inflowYear + "-Qin | " + outflowYear + "-Qout)"; }
public void Interpolate2DWithDatabase() { Logger.EnableLogger(); var fn = FileUtility.GetTempFileName(".pdb"); File.Delete(fn); SQLiteServer svr = new SQLiteServer(fn); var db = new TimeSeriesDatabase(svr); var c = new CalculationSeries("rir_q"); var path = Path.Combine(Globals.TestDataPath, "rating_tables"); path = Path.Combine(path, "rir_q.txt"); c.Expression = "FileLookupInterpolate2D(rir_fb, rir_ra, \"" + path + "\")" + " + FileLookupInterpolate2D(rir_fb, rir_rb, \"" + path + "\")"; c.TimeInterval = TimeInterval.Irregular; db.AddSeries(c); var fb = new Series("rir_fb"); fb.TimeInterval = TimeInterval.Irregular; db.AddSeries(fb); fb.Add("6-1-2011", 5110.99); fb.Add("6-2-2011", 5111.31); fb.Add("6-3-2011", 5111.71); fb.Add("6-4-2011", 5112.09); var ra = new Series("rir_ra"); ra.TimeInterval = TimeInterval.Irregular; ra.Add("6-1-2011", 2.1); ra.Add("6-2-2011", 1.29); ra.Add("6-3-2011", 1.29); ra.Add("6-4-2011", 1.29); db.AddSeries(ra); var rb = new Series("rir_rb"); rb.TimeInterval = TimeInterval.Irregular; rb.Add("6-1-2011", 2.1); rb.Add("6-2-2011", 1.28); rb.Add("6-3-2011", 1.28); rb.Add("6-4-2011", 1.28); db.AddSeries(rb); TimeSeriesImporter ti = new TimeSeriesImporter(db); ti.Import(fb, computeDependencies: true);// this should force a calculation... var q = db.GetSeriesFromTableName("rir_q"); Assert.NotNull(q, "Series not created"); q.Read(); /* * Flows from Hydromet * 6-1-2011, 1009.87 * 6-2-2011, 602.24 * 6-3-2011, 603.32 * 6-4-2011, 604.34 */ Assert.AreEqual(4, q.Count); Assert.AreEqual(1009.87, System.Math.Round(q[0].Value, 2)); Assert.AreEqual(603.32, System.Math.Round(q[2].Value, 2)); }
public void AddSerie(SerieDTO set) { Series.Add(set); set.StrengthTrainingItem = this; }
/// <summary> /// Method to call the data download API, get the JSON reponse, and convert to Series() /// </summary> /// <param name="station"></param> /// <param name="parameter"></param> /// <param name="t1"></param> /// <param name="t2"></param> /// <returns></returns> private Series IdwrApiDownload(string station, string parameter, DateTime t1, DateTime t2) { var rval = new Series(); var yearlist = YearsToQuery(station, t1, t2); try { var pars = parameter.Split('.'); if (pars.Count() > 1) { if (pars[0].ToLower() != "hst") { dataType = DataType.ALC; } parameter = pars[1]; } if (dataType == DataType.HST) { var jsonResponse = IdwrApiQuerySiteDataHST(station, yearlist); foreach (var item in jsonResponse) { var t = DateTime.Parse(item.Date); if (t >= t1 && t <= t2) { string value = ""; switch (parameter) { case ("GH"): value = item.GH; break; case ("FB"): value = item.FB; break; case ("AF"): value = item.AF; break; case ("QD"): value = item.QD; break; default: value = "NaN"; break; } if (value == "NaN") { rval.AddMissing(t); } else { rval.Add(item.Date, Convert.ToDouble(value)); } } } } else { var jsonResponse = IdwrApiQuerySiteDataALC(station, yearlist); foreach (var item in jsonResponse) { var t = DateTime.Parse(item.Date); if (t >= t1 && t <= t2) { string value = ""; switch (parameter) { case ("NATQ"): value = item.NATQ; break; case ("ACTQ"): value = item.ACTQ; break; case ("STRQ"): value = item.STRQ; break; case ("GANQ"): value = item.GANQ; break; case ("EVAP"): value = item.EVAP; break; case ("TOTEVAP"): value = item.TOTEVAP; break; case ("STORACC"): value = item.STORACC; break; case ("TOTACC"): value = item.TOTACC; break; case ("CURSTOR"): value = item.CURSTOR; break; case ("DIV"): value = item.DIV; break; case ("TOTDIVVOL"): value = item.TOTDIVVOL; break; case ("STORDIV"): value = item.STORDIV; break; case ("STORDIVVOL"): value = item.STORDIVVOL; break; case ("STORBAL"): value = item.STORBAL; break; default: value = "NaN"; break; } if (value == "NaN") { rval.AddMissing(t); } else { rval.Add(item.Date, Convert.ToDouble(value)); } } } } } catch { return(rval); } return(rval); }
/// <summary> /// Creates a list of Series , one subset for each day /// used for math functions that need subset by day /// </summary> /// <param name="s"></param> /// <returns></returns> private static Series DailySubsetCalculatorValue(Series s, Func<Series,double> func, int requiredNumberOfPoints = 0) { Series rval = new Series(); rval.TimeInterval = TimeInterval.Daily; DateTime t; if (s.Count > 0) { t = s[0].DateTime.Date; // midnight } else { return rval; } while (t < s.MaxDateTime) { var subset = Math.Subset(s, new DateRange(t, t.AddDays(1)), false); subset.RemoveMissing(true); if (subset.Count < requiredNumberOfPoints) { Logger.WriteLine("Error: not enough data points "+s.Name); Logger.WriteLine("expected "+requiredNumberOfPoints+" points, but had only "+subset.Count); rval.AddMissing(t); } else if (subset.Count > 0) { double d = func(subset); rval.Add(t, d, PointFlag.Computed); } t = t.AddDays(1).Date; } return rval; }
internal void RefreshData(CombinationofTheftTrommelAreaMonth input) { var trommelBars = new BarSeries { Title = "Hoeveelheid trommels", FillColor = OxyColors.Orange, StrokeColor = OxyColors.Orange, StrokeThickness = 1 }; var theftBars = new BarSeries { Title = "Hoeveelheid diefstallen", FillColor = OxyColors.Green, StrokeColor = OxyColors.Green, StrokeThickness = 1 }; for (int i = 0; i < 48; i++) { if (input.Rows.Count() > i) { theftBars.Items.Add(new BarItem { Value = input.Rows.ElementAt(i).Thefts, Color = OxyPlot.OxyColors.Green }); theftBars.Items.Add(new BarItem { Value = 0 }); } else { theftBars.Items.Add(new BarItem { Value = 0 }); theftBars.Items.Add(new BarItem { Value = 0 }); } if (input.Rows.Count() > i) { trommelBars.Items.Add(new BarItem { Value = 0 }); trommelBars.Items.Add(new BarItem { Value = input.Rows.ElementAt(i).Trommels, Color = OxyPlot.OxyColors.Orange }); } else { trommelBars.Items.Add(new BarItem { Value = 0 }); trommelBars.Items.Add(new BarItem { Value = 0 }); } } Series.Clear(); Series.Add(theftBars); Series.Add(trommelBars); InvalidatePlot(true); }
private Chart GenerateOneEquityChart(List <VMDynamics> lstVMDyn, DateTime dtBegin, DateTime dtEnd) { Chart chart = new Chart(); chart.XAxis.MajorTick = 10; chart.Left = 0; chart.Width = Unit.FromCentimeter(19); chart.Height = Unit.FromCentimeter(8); Series series = chart.SeriesCollection.AddSeries(); series.ChartType = ChartType.Line; series.HasDataLabel = true; XSeries xseries = chart.XValues.AddXSeries(); List <string> lstDt = new List <string>(); // DateTime dtBegin = ((DateTime) _reportData.DataStockExchResultsTable["DtBegin"]); //DateTime dtBegin = new DateTime(2016, 9, 22, 10, 0, 0); // DateTime dtEnd = new DateTime(2016, 9, 22, 18, 45, 0); CVMDynDataTraceGenerator vmproc = new CVMDynDataTraceGenerator(_reportData.ListVMDynamics); List <string> lstOutX; List <double> lstOutY; vmproc.GetVMTrendList(dtBegin, dtEnd, 10, 0, out lstOutX, out lstOutY); series.Add(lstOutY.ToArray()); xseries.Add(lstOutX.ToArray()); //int[] arr = new string[] { "10:00", 5, 10, 15, 21 }; // xseries.Add(arr); //xseries.Add(new string[] { new DateTime(2016, 9, 1,0,0,0).ToString("HH:mm") , new DateTime(2016, 9, 1, 0,10,0).ToString("HH:mm") }); // chart.XAxis.MajorTickMark = TickMarkType.Outside; chart.XAxis.HasMajorGridlines = true; chart.XAxis.HasMinorGridlines = true; chart.SeriesCollection[0].MarkerSize = 2; chart.SeriesCollection[0].LineFormat.Width = 1.0; chart.YAxis.MajorTickMark = TickMarkType.Outside; chart.YAxis.HasMinorGridlines = true; chart.YAxis.HasMajorGridlines = true; chart.PlotArea.LineFormat.Color = Colors.DarkGray; chart.PlotArea.LineFormat.Width = 1; return(chart); }
public IList <double> Execute(IList <double> source1, IList <double> source2) { return(Series.Add(source1, source2, Context)); }
static Series ParseXmlData(XPathDocument doc, string siteID, string inel_element, DateTime t) { Series s = new Series(); var nav = doc.CreateNavigator(); DateTime inlTime = t.Date; // used to increment each 5 minutes TimeZoneInfo mst; TimeZoneInfo mdt; if (LinuxUtility.IsLinux()) { //var c = TimeZoneInfo.GetSystemTimeZones(); //foreach (var item in c) //{ // Console.WriteLine(item); //} mst = TimeZoneInfo.FindSystemTimeZoneById("US/Arizona"); // no daylight shift mdt = TimeZoneInfo.FindSystemTimeZoneById("US/Mountain"); // with daylight shifting } else { mst = TimeZoneInfo.FindSystemTimeZoneById("US Mountain Standard Time"); // no daylight shift mdt = TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"); // with daylight shifting } string ts = ""; do { ts = inlTime.ToString("HH:mm"); var query = "mesonet/Time[@time=\"" + ts + "\"]/tower[@id=\"" + siteID + "\"]"; // /spd"; var nodeName = inel_element; var tag = ""; int idx = inel_element.IndexOf("."); if (idx > 0) { tag = inel_element.Substring(0, idx); query += "/" + tag; nodeName = inel_element.Substring(idx + 1); } var nodes = nav.Select(query); while (nodes.MoveNext()) { //Console.WriteLine(ts+ "id=" + nodes.Current.GetAttribute("id", "")); if (nodes.Current.HasChildren) { var children = nodes.Current.SelectChildren(XPathNodeType.All); while (children.MoveNext()) { var n = children.Current; if (n.LocalName == nodeName) { // Console.WriteLine(n.LocalName + " = " + n.Value); double val = 0; if (double.TryParse(n.Value, out val)) { //s.Add(t.Date.AddHours(time.Hour).AddMinutes(time.Minute), val, "inl"); DateTimeWithZone td = new DateTimeWithZone(inlTime, mst); DateTime hydrometDateTime; if (td.TryConvertToTimeZone(mdt, out hydrometDateTime)) { if (s.IndexOf(hydrometDateTime) < 0) {// in November time change, we have duplicate dates.. s.Add(hydrometDateTime, val, "inl"); } else { Console.WriteLine("skipping dateTime " + hydrometDateTime.ToString()); } } } } else if (n.LocalName == inel_element) { } } } } inlTime = inlTime.AddMinutes(5); } while (ts != "23:55"); Console.WriteLine("Read " + s.Count + " data points "); return(s); }
internal void Fcplot(Series actual, Series required, Series alternateRequiredContent, Series alternateActualContent, SeriesList ruleCurves, DateTime[] labelDates, String RequiredLegend, SeriesList userInput, bool greenLines, bool dashed, bool useFB = false) { tChart1.Zoom.Undo(); this.tChart1.Series.RemoveAllSeries(); this.tChart1.Tools.Clear(); tChart1.Axes.Bottom.Labels.Style = Steema.TeeChart.AxisLabelStyle.Value; if (labelDates.Length != ruleCurves.Count) { throw new Exception("Error: The number of label dates " + labelDates.Length + " must match the number of forecast levels " + ruleCurves.Count); } //add green lines if (greenLines && !useFB) { AddRuleCurves(ruleCurves, labelDates, dashed); } Color[] colors = { Color.DodgerBlue, Color.DarkOrange, Color.DarkKhaki, Color.Teal, Color.Aqua, Color.Olive, Color.BurlyWood, Color.MediumSpringGreen, Color.CadetBlue, Color.Chartreuse, Color.Chocolate, Color.Coral, Color.CornflowerBlue }; for (int i = 0; i < userInput.Count; i++) { if (i <= colors.Length) { var s = Reclamation.TimeSeries.Math.ShiftToYear(userInput[i], required[0].DateTime.Year); CreateSeries(colors[i], userInput[i].Name, s, "right"); } else { var s = Reclamation.TimeSeries.Math.ShiftToYear(userInput[i], required[0].DateTime.Year); CreateSeries(colors[i - colors.Length], userInput[i].Name, s, "right"); } } //add alternative lines if (alternateRequiredContent.Count > 0) //&& required.Count >0) { var s = new Series(); if (!useFB) { s = Reclamation.TimeSeries.Math.ShiftToYear(alternateRequiredContent, required[0].DateTime.Year); CreateSeries(Color.BlueViolet, alternateRequiredContent.Name + " " + RequiredLegend, s, "left"); } s = Reclamation.TimeSeries.Math.ShiftToYear(alternateActualContent, required[0].DateTime.Year); CreateSeries(Color.LightSkyBlue, alternateActualContent.Name, s, "left"); } //add lines if (!useFB) { CreateSeries(Color.Red, required.Name + " " + RequiredLegend, required, "left", true, 2); CreateSeries(Color.Blue, actual.Name + " Storage", actual, "left", false, 2); } else { CreateSeries(Color.Blue, actual.Name + " Elevation", actual, "left", false, 2); var sDummy = new Series(); for (DateTime i = actual.MinDateTime; i < ruleCurves[0].MaxDateTime; i = i.AddDays(1)) { sDummy.Add(i, actual.Values.Average()); } CreateSeries(Color.Transparent, "Dummy", sDummy, "left", false, 0); } // zoom out a little.. double min = 0, max = 0; tChart1.Axes.Left.Automatic = true; tChart1.Axes.Left.CalcMinMax(ref min, ref max); if (useFB) { tChart1.Axes.Left.Maximum = max + (max - min) * 0.1; tChart1.Axes.Left.Minimum = min - (max - min) * 0.1; } else { tChart1.Axes.Left.Maximum = max * 1.01; tChart1.Axes.Left.Minimum = 0;// min - 1000; } tChart1.Axes.Left.Automatic = false; //tChart1.Axes.Bottom.in //tChart1.Zoom.ZoomPercent(10); // format nearest point for (int i = 0; i < tChart1.Series.Count; i++) { if (tChart1.Series[i].ToString().Any(x => char.IsLetter(x))) { Steema.TeeChart.Tools.NearestPoint nearestPoint1 = new Steema.TeeChart.Tools.NearestPoint(tChart1[i]); nearestPoint1.Direction = Steema.TeeChart.Tools.NearestPointDirection.Horizontal; nearestPoint1.Pen.Color = tChart1[i].Color; nearestPoint1.Brush.Color = tChart1[i].Color; nearestPoint1.Size = 5; nearestPoint1.Style = Steema.TeeChart.Tools.NearestPointStyles.Circle; nearestPoint1.DrawLine = false; tChart1.Tools.Add(nearestPoint1); // set tool-tip text tChart1[i].GetSeriesMark += Form1_GetSeriesMark; } } // Add point tooltips Steema.TeeChart.Tools.MarksTip marksTip1 = new Steema.TeeChart.Tools.MarksTip(tChart1.Chart); marksTip1.Style = Steema.TeeChart.Styles.MarksStyles.XY; marksTip1.Active = true; marksTip1.MouseDelay = 0; marksTip1.HideDelay = 999999; marksTip1.MouseAction = Steema.TeeChart.Tools.MarksTipMouseAction.Move; marksTip1.BackColor = Color.LightSteelBlue; marksTip1.ForeColor = Color.Black; tChart1.Tools.Add(marksTip1); }
void MapObject(SeriesCollection seriesCollection, DocumentObjectModel.Shapes.Charts.SeriesCollection domSeriesCollection) { foreach (DocumentObjectModel.Shapes.Charts.Series domSeries in domSeriesCollection) { Series series = seriesCollection.AddSeries(); series.Name = domSeries.Name; if (domSeries.IsNull("ChartType")) { DocumentObjectModel.Shapes.Charts.Chart chart = (DocumentObjectModel.Shapes.Charts.Chart)DocumentObjectModel.DocumentRelations.GetParentOfType(domSeries, typeof(DocumentObjectModel.Shapes.Charts.Chart)); series.ChartType = (ChartType)chart.Type; } else { series.ChartType = (ChartType)domSeries.ChartType; } if (!domSeries.IsNull("DataLabel")) { DataLabelMapper.Map(series.DataLabel, domSeries.DataLabel); } if (!domSeries.IsNull("LineFormat")) { LineFormatMapper.Map(series.LineFormat, domSeries.LineFormat); } if (!domSeries.IsNull("FillFormat")) { FillFormatMapper.Map(series.FillFormat, domSeries.FillFormat); } series.HasDataLabel = domSeries.HasDataLabel; if (domSeries.MarkerBackgroundColor.IsEmpty) { series.MarkerBackgroundColor = XColor.Empty; } else { #if noCMYK series.MarkerBackgroundColor = XColor.FromArgb(domSeries.MarkerBackgroundColor.Argb); #else series.MarkerBackgroundColor = ColorHelper.ToXColor(domSeries.MarkerBackgroundColor, domSeries.Document.UseCmykColor); #endif } if (domSeries.MarkerForegroundColor.IsEmpty) { series.MarkerForegroundColor = XColor.Empty; } else { #if noCMYK series.MarkerForegroundColor = XColor.FromArgb(domSeries.MarkerForegroundColor.Argb); #else series.MarkerForegroundColor = ColorHelper.ToXColor(domSeries.MarkerForegroundColor, domSeries.Document.UseCmykColor); #endif } series.MarkerSize = domSeries.MarkerSize.Point; if (!domSeries.IsNull("MarkerStyle")) { series.MarkerStyle = (MarkerStyle)domSeries.MarkerStyle; } foreach (DocumentObjectModel.Shapes.Charts.Point domPoint in domSeries.Elements) { if (domPoint != null) { Point point = series.Add(domPoint.Value); FillFormatMapper.Map(point.FillFormat, domPoint.FillFormat); LineFormatMapper.Map(point.LineFormat, domPoint.LineFormat); } else { series.Add(double.NaN); } } } }
private Series ReadMonth(DateTime t) { t = new DateTime(t.Year, t.Month, 1); string url = "http://www.wrh.noaa.gov/otx/climate/coop/get_coop.php?form_test=true&station=Davenport&monthname=April&ob_norm=Observed+Data&year=2007&.submit=Submit+Query"; url = url.Replace("&station=Davenport&", "&station=" + m_station + "&"); url = url.Replace("&monthname=April&", "&monthname=" + t.ToString("MMMM") + "&"); url = url.Replace("&year=2007&", "&year=" + t.Year + "&"); Series s = new Series(); TextFile tf = new TextFile(Web.GetPage(url, true)); // tf.SaveAs(@"C:\temp\test.txt"); //[472] = "<font face=\"Arial, Helvetica, sans-serif\"><h3><b>Observed Data for Davenport November 2005</b></h3></font>" string spaceSeparatedStation = m_station.Replace("_", " "); string findMe = "Observed Data for " + spaceSeparatedStation + " " + t.ToString("MMMM") + " " + t.Year; int idx = tf.IndexOf(findMe); if (idx < 0) { Logger.WriteLine("No data found matching '" + findMe + "'"); return(s); } string header = tf[idx + 1]; header = header.Replace("<b>", ""); header = header.Replace("</b>", ""); string[] columnNames = Regex.Split(header, @"\s+"); int idxParameter = Array.IndexOf(columnNames, m_parameter); if (idxParameter < 0) { throw new Exception("could not find parameter '" + m_parameter + "'" + "\nin " + tf[idx + 1]); } for (int i = idx + 2; i < tf.Length; i++) { if (tf[i].IndexOf("___________") == 0) { break; // done } string[] tokens = Regex.Split(tf[i].Replace("<b>", "").Trim().Replace("</b>", ""), @"\s+"); if (tokens.Length <= idxParameter) { Logger.WriteLine("Error: wrong number of columns?"); break; } int day = -1; if (!int.TryParse(tokens[0], out day)) { Logger.WriteLine("Error:invalid day at " + tf[i]); break; } if (day != t.Day) { Logger.WriteLine("Dates out of sync.."); break; } string strValue = tokens[idxParameter]; double value = Point.MissingValueFlag; if (strValue.IndexOf("T") >= 0) { s.Add(t, 0); } else if (double.TryParse(strValue, out value)) { s.Add(t, value); } else { s.Add(t, Point.MissingValueFlag); } t = t.AddDays(1); } return(s); }
/// <summary> /// If Decodes software is installed locally /// DECODE raw data for a single parameter /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AdvancedRawData_Click(object sender, EventArgs e) { // determine siteid (cbtt) and pcode SpreadsheetRange r = new SpreadsheetRange(wbView.RangeSelection); var col = r.SelectedRangeColumnNames[0]; var tokens = col.Trim().Split(' '); if (tokens.Length != 2) { return; } var cbtt = tokens[0].ToLower(); var pcode = tokens[1].ToLower(); // find date range that is selected. var t = r.SelectedDateRange; // account for timezone offset and transmission time delay // summer UTC-6h // winter UTC-7h var t1 = t.DateTime1.AddHours(-24); var t2 = t.DateTime2.AddHours(+24); var svr = Database.GetServer("hydromet_opendcs"); if (svr == null) { MessageBox.Show("Error connecting to the database. Please check your password"); return; } var fn = FileUtility.GetSimpleTempFileName(".txt"); var log = FileUtility.GetSimpleTempFileName(".txt"); // run DECODES to create output file DecodesUtility.RunDecodesRoutingSpec(svr, "hydromet-tools", t1, t2, cbtt, fn, log); //Don't Go Karl! foreach (var item in File.ReadAllLines(log)) { Logger.WriteLine(item); } foreach (var item in File.ReadAllLines(fn)) { Logger.WriteLine(item); } TextFile tf = new TextFile(fn); if (!HydrometInstantSeries.IsValidDMS3(tf)) { MessageBox.Show("Error reading Decodes output"); return; } // Read Decodes output var sl = HydrometInstantSeries.HydrometDMS3DataToSeriesList(tf); // filter by cbtt and pcode var s = sl.Find(x => x.Table.TableName == "instant_" + cbtt + "_" + pcode); if (s == null) { Logger.WriteLine("Error: could not find decoded data for " + cbtt + "/" + pcode); return; } // use dataview for sorted data // filter by date range Series decoded = s.Clone(); for (int i = 0; i < s.Count; i++) { var pt = s[i]; if (pt.DateTime >= t.DateTime1 && pt.DateTime <= t.DateTime2) { decoded.Add(pt); } } // put values into hydromet tools r.InsertSeriesValues(decoded); }
public WPercentRange() { Name = "W percent range"; Series.Add(new Series("Main")); }
/// <summary> /// Residual is forecast minus QU /// </summary> private void ComputeResidualAndRequiredSpace() { SpaceRequired.Clear(); SpaceRequired.Name = "Space Required"; Residual.Clear(); Residual.Name = "Residual"; DateTime t = _t1; double resid = 0; // 998877; int wy = t.Year; if (t.Month > 9) { wy++; } m_ruleCurve = RuleCurveFactory.Create(controlPoint, wy); while (t <= _t2) { if (controlPoint.FillType == FillType.Variable) { resid = ResetResidualBasedOnForecast(t, resid); if (resid != HydrometRuleCurve.MissingValue && t <= qu.MaxDateTime) { var quTemp = qu[t].Value; if (quTemp < 0) { quTemp = 0; } resid = resid - quTemp * 1.98347; if (resid < 0) { resid = 0; } Residual.Add(t, resid); } else { Residual.AddMissing(t); } } else { resid = HydrometRuleCurve.MissingValue; } var t2 = t; if (t.Month == 2 && t.Day == 29) { t2 = t.AddDays(-1); } string flag = ""; double req = 0; req = m_ruleCurve.LookupRequiredSpace(t2, resid, out flag); if (req == HydrometRuleCurve.MissingValue) { SpaceRequired.AddMissing(t); } else { req = req * controlPoint.PercentSpace / 100.0; if (req < 0) { req = 0; } SpaceRequired.Add(t, req); } flags.Add(flag); t = t.AddDays(1); } }
/// <summary> /// Creates a list of Series , one subset for each day /// used for math functions that need subset by day /// </summary> /// <param name="s"></param> /// <returns></returns> private static Series DailySubsetCalculatorPoint(Series s, Func<Series, Point> func) { Series rval = new Series(); rval.TimeInterval = TimeInterval.Daily; DateTime t; if (s.Count > 0) { t = s[0].DateTime.Date; // midnight } else { return rval; } while (t < s.MaxDateTime) { var subset = Math.Subset(s, new DateRange(t, t.AddDays(1)), false); subset.RemoveMissing(); if (subset.Count > 0) { Point pt = func(subset); rval.Add(t, pt.Value, PointFlag.Computed); } t = t.AddDays(1).Date; } return rval; }
private void AddSeriesOnClick(object sender, RoutedEventArgs e) { Series.Add(new LineSeries { Values = new ChartValues <WeatherViewModel>(), PointRadius = 0 }); }
/// <summary> /// Calls a function for each day returning a Daily Series /// Uses with calculations that can also perform subset of Series by day /// </summary> /// <param name="s"></param> /// <param name="fun"></param> /// <returns></returns> private static Series DailyValues(Series s, Func<Series,DateTime,int,Point> fun, int requiredNumberOfPoints ) { //Console.WriteLine("Calling Generic DailyValues with "+fun.ToString()); Series rval = new Series(s.Units, TimeInterval.Daily); rval.HasFlags = true; DateTime t; if (s.Count > 0) { t = s[0].DateTime.Date; // midnight } else return rval; while (t < s.MaxDateTime) { Point pt = fun(s,t,requiredNumberOfPoints); rval.Add(pt); t = t.AddDays(1); } return rval; }
/// <summary> /// Defines what happens when the page is navigated on. /// </summary> /// <param name="parameter">parameter.</param> /// <param name="mode">navigation mode.</param> /// <param name="state">state.</param> public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state) { //Deciding if the character is searched by id or name. int intParam = 0; if (int.TryParse(parameter.ToString(), out intParam)) { var characterId = (int)parameter; var service = new CharacterService(); Character = await service.GetCharacterAsync(characterId); } else { var characterName = (string)parameter; var service = new CharacterService(); var characterList = await service.GetCharacterAsync(characterName); foreach (var item in characterList) { Character = item; } } //If no such character is found, navigate the user to the not found page. if (Character == null) { NavigateToNotFoundPage(); return; } await base.OnNavigatedToAsync(parameter, mode, state); //Fill the lists on the UI, transforming uris if needed. foreach (string title in Character.titles) { Titles.Add(new Models.Attribute(title)); } foreach (string alias in Character.aliases) { Aliases.Add(new Models.Attribute(alias)); } foreach (string serie in Character.tvSeries) { Series.Add(new Models.Attribute(serie)); } foreach (string actor in Character.playedBy) { Actors.Add(new Models.Attribute(actor)); } foreach (string houseUri in Character.allegiances) { TransformUriToHouse(houseUri, Allegiances); } foreach (string characterUri in Character.books) { TransformUriToBook(characterUri, Books); } foreach (string characterUri in Character.povBooks) { TransformUriToBook(characterUri, PoVBooks); } TransformUriToCharacter(Character.father, Father); TransformUriToCharacter(Character.mother, Mother); TransformUriToCharacter(Character.spouse, Spouse); await base.OnNavigatedToAsync(parameter, mode, state); }