public void EarliestInputTime() { gwModelLC.Prepare(); DateTime earliestInputTime = CalendarConverter.ModifiedJulian2Gregorian(gwModelLC.EarliestInputTime.ModifiedJulianDay); Assert.AreEqual(new DateTime(1990, 1, 2, 0, 0, 0), earliestInputTime); }
/// <summary> /// Calculates the potential evapotranspiration using the Hargreaves-Samani method /// </summary> /// <param name="T">Averaged daily temperature</param> /// <param name="Tmin">Minimum daily temperature</param> /// <param name="Tmax">Maximum daily temperature</param> /// <param name="e">element index</param> /// <returns>PET in mm/day</returns> public double CalculatePET(double T, double Tmin, double Tmax, int eid) { //calc Ra from http://www.civil.uwaterloo.ca/watflood/Manual/02_03_2.htm //---- calculate the relative distance between the earth and sun //-- get julien day TimeStamp ts = (TimeStamp)this.GetCurrentTime(); DateTime dt = CalendarConverter.ModifiedJulian2Gregorian(ts.ModifiedJulianDay); int j = dt.DayOfYear; double dr = 1 + 0.033 * Math.Cos((2 * Math.PI * j) / 365); //---- calculate the solar declination double d = 0.4093 * Math.Sin((2 * Math.PI * j) / 365 - 1.405); //---- calculate the sunset hour angle //-- get latitude in degrees ElementSet es = (ElementSet)this.GetInputExchangeItem(0).ElementSet; Element e = es.GetElement(eid); double p = e.GetVertex(0).y *Math.PI / 180; //-- calc ws double ws = Math.Acos(-1 * Math.Tan(p) * Math.Tan(d)); //---- calculate the total incoming extra terrestrial solar radiation (tested against http://www.engr.scu.edu/~emaurer/tools/calc_solar_cgi.pl) double Ra = 15.392 * dr * (ws * Math.Sin(p) * Math.Sin(d) + Math.Cos(p) * Math.Cos(d) * Math.Sin(ws)); //---- calculate PET (From Hargreaves and Samani 1985) //-- calculate latent heat of vaporization (from Water Resources Engineering, David A. Chin) double L = 2.501 - 0.002361 * T; double PET = (0.0023 * Ra * Math.Sqrt(Tmax - Tmin) * (T + 17.8)) / L; return(PET); }
public IValueSet GetValues(ITime time, string linkID) { // covert time to a DateTime data type TimeStamp timestamp = (TimeStamp)time; DateTime dt = CalendarConverter.ModifiedJulian2Gregorian( (double)timestamp.ModifiedJulianDay); // write datetime to log file StreamWriter sr = new StreamWriter("hydrolink_log.txt", true); sr.WriteLine("get values request for time: " + dt.ToLongDateString() + " " + dt.ToLongTimeString()); sr.Flush(); //get scalar set IValueSet values = _buffervalues[linkID].GetValues(time); // write value set to log file ScalarSet ss = (ScalarSet)values; sr.Write("values set: "); sr.Flush(); for (int i = 0; i < ss.Count; ++i) { sr.Write(" " + ss.GetScalar(i).ToString() + " "); sr.Flush(); } sr.Write("\n"); sr.Close(); return(values); }
public override bool PerformTimeStep() { //---- get input data //-- temp double[] temp = ((ScalarSet)this.GetValues(input_quantity[0], input_elementset[0])).data; //-- max temp double[] maxtemp = ((ScalarSet)this.GetValues(input_quantity[1], input_elementset[1])).data; //-- min temp double[] mintemp = ((ScalarSet)this.GetValues(input_quantity[2], input_elementset[2])).data; //---- calculate pet for each element //-- get the number of elements (assuming that they're all the same) int elemcount = this.GetInputExchangeItem(0).ElementSet.ElementCount; double[] pet = new double[elemcount]; for (int i = 0; i <= elemcount - 1; i++) { pet[i] = CalculatePET(temp[i], mintemp[i], maxtemp[i], i); } //---- save output values DateTime dt = CalendarConverter.ModifiedJulian2Gregorian(((TimeStamp)this.GetCurrentTime()).ModifiedJulianDay); _output.Add(dt, pet); //---- set output values this.SetValues(output_quantity, output_elementset, new ScalarSet(pet)); //---- advance to the next timestep this.AdvanceTime(); return(true); }
int nt = 1;// number of earliest outputs need to be saved public override void Finish() { if (!System.IO.Directory.Exists(outputPath)) { System.IO.Directory.CreateDirectory(outputPath); } //System.IO.Directory.CreateDirectory("wateroutput"); StreamWriter swa = new StreamWriter(outputPath + "/waterAdvection.csv"); swa.WriteLine("This is some info about the model...."); DateTime start = CalendarConverter.ModifiedJulian2Gregorian(((TimeStamp)this.GetTimeHorizon().Start).ModifiedJulianDay); DateTime end = CalendarConverter.ModifiedJulian2Gregorian(((TimeStamp)this.GetTimeHorizon().End).ModifiedJulianDay); swa.WriteLine("StartDate: , " + String.Format("{0:d/M/yyyy HH:mm:ss}", start)); swa.WriteLine("EndDate: , " + String.Format("{0:d/M/yyyy HH:mm:ss}", end)); swa.WriteLine(); swa.WriteLine("Time [H:mm:ss], Concentration"); foreach (KeyValuePair <DateTime, double[, ]> kvp in outputValues) { string time = String.Format("{0:HH:mm:ss}", kvp.Key); swa.Write(time + ","); //StreamWriter sw = new StreamWriter("wateroutput/" + time + ".csv"); for (int i = 0; i < kvp.Value.GetLength(0); i++) { for (int j = 0; j < kvp.Value.GetLength(1); j++) { swa.Write(kvp.Value[i, j].ToString() + ","); } swa.Write("\n"); } } swa.Close(); }
/// <summary> /// Converts event to <c>string</c> representation. /// </summary> /// <param name="Event">Event to be converted to <c>string</c></param> /// <returns>Returns resulting <c>string</c>.</returns> public static string EventToString(IEvent Event) { StringBuilder builder = new StringBuilder(200); builder.Append("[Type="); builder.Append(Event.Type.ToString()); if (Event.Description != null) { builder.Append("][Message="); builder.Append(Event.Description); } if (Event.Sender != null) { builder.Append("][ModelID="); builder.Append(((ILinkableComponent)Event.Sender).ModelID); } if (Event.SimulationTime != null) { builder.Append("][SimTime="); builder.Append(CalendarConverter.ModifiedJulian2Gregorian(Event.SimulationTime.ModifiedJulianDay).ToString()); } builder.Append(']'); return(builder.ToString()); }
public void TimeHorizon() { DateTime startDate = new DateTime(1990, 1, 2, 0, 0, 0); DateTime endDate = new DateTime(1990, 2, 1, 0, 0, 0); Assert.AreEqual(startDate, CalendarConverter.ModifiedJulian2Gregorian(gwModelLC.TimeHorizon.Start.ModifiedJulianDay)); Assert.AreEqual(endDate, CalendarConverter.ModifiedJulian2Gregorian(gwModelLC.TimeHorizon.End.ModifiedJulianDay)); }
[TestMethod] public void TrickyDates() { double julianDate = 46096.999999998196; DateTime gregorian = CalendarConverter.ModifiedJulian2Gregorian(julianDate); Assert.AreEqual(1985, gregorian.Year, "Year expected"); Assert.AreEqual(2, gregorian.Month, "Month expected"); Assert.AreEqual(1, gregorian.Day, "Day expected"); }
private void Evaluate(DateTime inGregDate) { double modJulDate = CalendarConverter.Gregorian2ModifiedJulian(inGregDate); long mjdInt = (long)modJulDate; DateTime outGregDate = CalendarConverter.ModifiedJulian2Gregorian(modJulDate); Assert.AreEqual(inGregDate.ToString(), outGregDate.ToString(), modJulDate.ToString()); }
public void RunSimulationWithInputAndOutput() { ITimeSpan modelSpan = mohidWaterEngineWrapper.GetTimeHorizon(); double now = modelSpan.Start.ModifiedJulianDay; Stopwatch win = new Stopwatch(); Stopwatch wout = new Stopwatch(); Stopwatch wengine = new Stopwatch(); while (now < modelSpan.End.ModifiedJulianDay) { DateTime currentTime = CalendarConverter.ModifiedJulian2Gregorian(now); DateTime intitalTime = CalendarConverter.ModifiedJulian2Gregorian( mohidWaterEngineWrapper.GetTimeHorizon().Start.ModifiedJulianDay); Console.WriteLine(currentTime.ToString()); wengine.Start(); mohidWaterEngineWrapper.PerformTimeStep(); wengine.Stop(); wout.Start(); //Gets outputs Items for (int i = 0; i < mohidWaterEngineWrapper.GetOutputExchangeItemCount(); i++) { OutputExchangeItem ouputItem = mohidWaterEngineWrapper.GetOutputExchangeItem(i); IValueSet values = mohidWaterEngineWrapper.GetValues(ouputItem.Quantity.ID, ouputItem.ElementSet.ID); } wout.Stop(); //Sets Input Items win.Start(); for (int i = 0; i < mohidWaterEngineWrapper.GetInputExchangeItemCount(); i++) { InputExchangeItem inputItem = mohidWaterEngineWrapper.GetInputExchangeItem(i); double[] aux = new double[inputItem.ElementSet.ElementCount]; for (int j = 0; j < inputItem.ElementSet.ElementCount; j++) { aux[j] = 0; } IValueSet values = new ScalarSet(aux); //mohidLandEngineWrapper.SetValues(inputItem.Quantity.ID, inputItem.ElementSet.ID, values); } win.Stop(); now = mohidWaterEngineWrapper.GetEarliestNeededTime().ModifiedJulianDay; } Console.WriteLine("Input Exchange: " + win.ElapsedMilliseconds.ToString()); Console.WriteLine("Output Exchange: " + wout.ElapsedMilliseconds.ToString()); Console.WriteLine("Engine: " + wengine.ElapsedMilliseconds.ToString()); }
public void AccessTimes() { DateTime start = new DateTime(2002, 1, 1, 0, 0, 0); DateTime end = new DateTime(2002, 1, 1, 12, 0, 0); ITimeSpan timeHorizon = mohidWaterEngineWrapper.GetTimeHorizon(); Assert.AreEqual(CalendarConverter.ModifiedJulian2Gregorian(timeHorizon.Start.ModifiedJulianDay), start); Assert.AreEqual(CalendarConverter.ModifiedJulian2Gregorian(timeHorizon.End.ModifiedJulianDay), end); }
/// <summary> /// This method performs specified actions upon the closure of the model /// </summary> public override void Finish() { //intialize streamwriter to write output data. if (_outDir != null) { try { sw = new System.IO.StreamWriter(_outDir + "/MuskingumRouting_output.csv"); } catch (SystemException e) { throw new Exception("The Muskingum Component was unable to create the desired output file. " + "This is possibly due to an invalid \'OutDir\' field supplied in " + "the *.omi file", e); } } else { try { sw = new System.IO.StreamWriter("../MuskingumRouting_output.csv"); } catch (SystemException e) { throw new Exception(" The Muskingum component failed in writing it output file to path " + System.IO.Directory.GetCurrentDirectory() + ". This may be due to " + "lack of user permissions.", e); } } // current time TimeStamp time = (TimeStamp)this.GetCurrentTime(); DateTime current = CalendarConverter.ModifiedJulian2Gregorian(time.ModifiedJulianDay); Double step_sec = this.GetTimeStep(); //get the last time current = current.AddSeconds(-1 * step_sec); sw.Write("Date,"); for (int i = 1; i <= _output[current].Length; i++) { sw.Write("Element " + i.ToString() + ","); } sw.Write("\n"); foreach (KeyValuePair <DateTime, double[]> kvp in _output) { sw.Write(kvp.Key.ToShortDateString() + " " + kvp.Key.ToLongTimeString() + ","); for (int j = 0; j < kvp.Value.Length; j++) { sw.Write(kvp.Value[j].ToString() + ","); } sw.Write("\n"); } sw.Close(); }
/// <summary> /// This method is being used to write the calculated values to file, for use outside of the OpenMI environment. /// </summary> public override void Finish() { //intialize streamwriter to write output data. if (_outDir != null) { try { sw = new System.IO.StreamWriter(_outDir + "/SCSUnitHydrograph_output.csv"); } catch (SystemException e) { throw new Exception("The UH Component was unable to create the desired output file. " + "This is possibly due to an invalid \'OutDir\' field supplied in " + "the *.omi file", e); } } else { try { sw = new System.IO.StreamWriter("../SCSUnitHydrograph_output.csv"); } catch (SystemException e) { throw new Exception(" The UH component failed in writing it output file to path " + System.IO.Directory.GetCurrentDirectory() + ". This may be due to " + "lack of user permissions.", e); } } //Write output data sw.Write("Date, Time, "); OpenMI.Standard.ITimeSpan ts = this.GetTimeHorizon(); TimeStamp t = (TimeStamp)ts.Start; DateTime dt = CalendarConverter.ModifiedJulian2Gregorian((double)t.ModifiedJulianDay); for (int i = 0; i <= output[dt].Count - 1; i++) { sw.Write("element " + (i + 1).ToString() + ","); } sw.Write("\n"); foreach (System.Collections.Generic.KeyValuePair <DateTime, ArrayList> kvp in output) { sw.Write(String.Format("{0:MM/dd/yyyy}", kvp.Key) + ", " + String.Format("{0:hh:mm tt}", kvp.Key) + ","); for (int i = 0; i <= kvp.Value.Count - 1; i++) { sw.Write(kvp.Value[i].ToString() + ","); } sw.Write("\n"); } sw.Close(); }
public override bool PerformTimeStep() { //Defie current time step and the row of water component TimeStamp SedTime = (TimeStamp)this.GetCurrentTime(); ScalarSet aa = (ScalarSet)this.GetValues("Concentration", "water"); //set adv_prev to the imported values for (int i = 0; i <= cw.GetLength(1) - 1; i++) { adv_prev[0, i] = aa.data[i]; } // specifies if the values should be saved. bool SaveValues = true; TimeStamp t = (TimeStamp)this.GetCurrentTime(); DateTime time = CalendarConverter.ModifiedJulian2Gregorian(t.ModifiedJulianDay); // calculate concentration in sediment using diffusion mechanism from water cs = Calculate_concentration(); //setup the value of diff_prev= upper row of cs since cs contain 9 rows for (int i = 0; i <= cs.GetLength(1) - 1; i++) { diff_prev[i] = cs[cs.GetUpperBound(0), i]; } //save results for output during Finish() double[,] z = new double[rows_S, cols_S]; if (SaveValues) { for (int i = 0; i <= cs.GetLength(0) - 1; i++) { for (int j = 0; j <= cs.GetLength(1) - 1; j++) { z[i, j] = cs[i, j]; } } //save results for output during Finish() outputValues.Add(time, z); outv.Add(z); } //setting boundary conditions so that they are available to water component. double[] outvals = new double[cs.GetLength(1)]; for (int i = 0; i <= cs.GetLength(1) - 1; i++) { outvals[i] = cs[8, i]; } this.SetValues("Concentration", "sed", new ScalarSet(outvals)); this.AdvanceTime(); return(true); }
public void ConvertThis() { double julianDate = 51544.0006944444; DateTime gregorian = CalendarConverter.ModifiedJulian2Gregorian(julianDate); DateTime Time = new DateTime(2000, 1, 1, 16, 47, 00); Oatc.OpenMI.Sdk.Backbone.TimeStamp t = new Oatc.OpenMI.Sdk.Backbone.TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(Time)); var v = ((global::OpenMI.Standard.ITimeSpan)t).Start; DateTime gregorian2 = CalendarConverter.ModifiedJulian2Gregorian(t.ModifiedJulianDay); }
public void GetTimeHorizon() { Console.WriteLine("Begin Get Time Horizon Test..."); //create the his component HydroLink his = new HydroLink(); IArgument[] arguments = new IArgument[1]; arguments[0] = new Argument("WaterMLdb", @"..\..\..\Data\db", true, "WaterML Database"); his.Initialize(arguments); //get earliest and latest times Console.WriteLine("start: " + CalendarConverter.ModifiedJulian2Gregorian(his.TimeHorizon.Start.ModifiedJulianDay).ToString()); Console.WriteLine("end: " + CalendarConverter.ModifiedJulian2Gregorian(his.TimeHorizon.End.ModifiedJulianDay).ToString()); }
public void GetTimeHorizon() { Console.WriteLine("Begin Get Time Horizon Test..."); //create the his component DbReader his = new DbReader(); IArgument[] arguments = new IArgument[1]; arguments[0] = new Argument("DbPath", @"..\data\cuahsi-his\demo.db", true, "Database"); his.Initialize(arguments); //get earliest and latest times Console.WriteLine("start: " + CalendarConverter.ModifiedJulian2Gregorian(his.TimeHorizon.Start.ModifiedJulianDay).ToString()); Console.WriteLine("end: " + CalendarConverter.ModifiedJulian2Gregorian(his.TimeHorizon.End.ModifiedJulianDay).ToString()); }
public override bool PerformTimeStep() { //Define time step and get lowest row from the Sediment component grid(lowest row of matrix= actual top row) TimeStamp WaterTime = (TimeStamp)this.GetCurrentTime(); ScalarSet ss = (ScalarSet)this.GetValues("Concentration", "sed"); //set diff_prev = the imported values for (int i = 0; i <= cs.GetLength(1) - 1; i++) { diff_prev[i] = ss.data[i]; } //specifies if values should be saved. bool SaveValues = true; TimeStamp t = (TimeStamp)this.GetCurrentTime(); DateTime time = CalendarConverter.ModifiedJulian2Gregorian(t.ModifiedJulianDay); // calculate concentration in water using advection mechanismin water and diffusion from sediment cw = Calculate_concentration(); //store these c values in adv_prev, for next timestep adv_prev = cw; //save results for output during Finish() double[,] z = new double[rows_W, cols_W]; if (SaveValues) { for (int i = 0; i <= cw.GetLength(0) - 1; i++) { for (int j = 0; j <= cw.GetLength(1) - 1; j++) { z[i, j] = adv_prev[i, j]; } } outputValues.Add(time, z); } double[] outvals = new double[cw.GetLength(1)]; for (int i = 0; i <= cw.GetLength(1) - 1; i++) { outvals[i] = cw[cw.GetLength(0) - 1, i]; } this.SetValues("Concentration", "water", new ScalarSet(outvals)); this.AdvanceTime(); return(true); }
[TestMethod] public void SomeDates() { double zero = 0; DateTime zeroDate = CalendarConverter.ModifiedJulian2Gregorian(zero); Assert.AreEqual(1858, zeroDate.Year, "Year of Modified Julian Date Zero"); Assert.AreEqual(11, zeroDate.Month, "Month of Modified Julian Date Zero"); Assert.AreEqual(17, zeroDate.Day, "Day of Modified Julian Date Zero"); double jan1_1985 = 46066.25; DateTime jan1_1985Date = CalendarConverter.ModifiedJulian2Gregorian(jan1_1985); Assert.AreEqual(1985, jan1_1985Date.Year, "Year of jan 1 1985"); Assert.AreEqual(1, jan1_1985Date.Month, "Month of jan 1 1985"); Assert.AreEqual(1, jan1_1985Date.Day, "Day of jan 1 1985"); Assert.AreEqual(6, jan1_1985Date.Hour, "Hour of jan 1 1985"); }
/// <summary> /// Writes HD time series data object to the data repository /// </summary> public void Finish() { //check to see if the database path is overridden var db = conn != null ? RepositoryFactory.Instance.Get <IRepositoryManager>(DatabaseTypes.SQLite, conn) : RepositoryFactory.Instance.Get <IRepositoryManager>(); //write each series to the database foreach (Series series in serieses.Values) { //-- get the theme Theme theme = series.ThemeList[0]; //-- need to adjust the series values back by one time step Dictionary <DateTime, double> new_data = new Dictionary <DateTime, double>(); // determine the timestep using the first two values (assumes uniform timstep) double timestep = _timestep[theme.Name][1].Subtract(_timestep[theme.Name][0]).TotalSeconds; // change the data value times back 1 time step // this is necessary b/c each model advances it's time before dbwriter gets the data for (int i = 0; i <= series.ValueCount - 1; i++) { // subtract 1 for the timestep advancement // subtract 1 for the 1-timestep delay that OpenMI creates series.DataValueList[i].DateTimeUTC = series.DataValueList[i].DateTimeUTC.AddSeconds(-2 * timestep); series.DataValueList[i].LocalDateTime = series.DataValueList[i].LocalDateTime.AddSeconds(-2 * timestep); // remove data value if less than start if (series.DataValueList[i].LocalDateTime < CalendarConverter.ModifiedJulian2Gregorian(_start).AddSeconds(-timestep)) { //series.DataValueList[i].Value = series.GetNoDataValue(); series.DataValueList.RemoveAt(i); // This change was necessary b/c series.GetNoDataValue() was removed } } //-- save data series //db.SaveSeriesAsCopy(series, theme); db.SaveSeries(series, theme, OverwriteOptions.Copy); //This change was necessary b/c db.SaveSeriesAsCopy() was removed } //clear all values in the buffer _smartBuffer.Clear(this.TimeHorizon); }
public void OnEvent(IEvent Event) { ILink[] links = GetAcceptingLinks(); foreach (ILink link in links) { if (link.SourceComponent == Event.Sender) { IValueSet values = Event.Sender.GetValues(Event.SimulationTime, link.ID); if (values is IScalarSet) { IScalarSet scalarSet = (IScalarSet)values; DataArrived(CalendarConverter.ModifiedJulian2Gregorian(Event.SimulationTime.ModifiedJulianDay), Event.Sender.ModelID, link.SourceQuantity.ID, link.SourceElementSet.ID, scalarSet); } } } }
/// <summary> /// Converts a ITime object to a formatted string /// </summary> /// <param name="time">The time to convert</param> /// <returns>The formatted string</returns> public static string ITimeToString(ITime time) { string timeString; if (time is ITimeStamp) { timeString = (CalendarConverter.ModifiedJulian2Gregorian(((ITimeStamp)time).ModifiedJulianDay)).ToString(); } else if (time is ITimeSpan) { timeString = "[" + (CalendarConverter.ModifiedJulian2Gregorian(((ITimeSpan)time).Start.ModifiedJulianDay)).ToString() + ", " + (CalendarConverter.ModifiedJulian2Gregorian(((ITimeSpan)time).End.ModifiedJulianDay)).ToString() + "]"; } else { throw new System.Exception("Illigal type used for time, must be OpenMI.Standard.ITimeStamp or OpenMI.Standard.TimeSpan"); } return(timeString); }
private void buttonTimeLatestOverlapping_Click(object sender, System.EventArgs e) { double start = double.MinValue, end = double.MaxValue; foreach (UIModel model in _composition.Models) { start = Math.Max(model.LinkableComponent.TimeHorizon.Start.ModifiedJulianDay, start); end = Math.Min(model.LinkableComponent.TimeHorizon.End.ModifiedJulianDay, end); } if (start > end) { MessageBox.Show("Model timehorizons don't overlap.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { textTriggerInvokeTime.Text = CalendarConverter.ModifiedJulian2Gregorian(end).ToString(); } }
public override bool PerformTimeStep() { //request the excess precipitation an infiltration component ScalarSet excess = (ScalarSet)this.GetValues(_inputQuantity, _inputElementSet); double[] Outflow = new double[excess.Count]; //--- CALCULATE BURST EXCESS ---- for (int i = 0; i <= excess.Count - 1; i++) { //Push the burst value into the Pe array Push(_pe[i], excess.data[i]); //Calculate the resulting Outflow at this timestep Outflow[i] = DotProduct(_uh[i], _pe[i]); } //store the Outflow, to write out in Finish() ArrayList outputVals = new ArrayList(); for (int k = 0; k <= Outflow.Length - 1; k++) { outputVals.Add(Outflow[k]); } //add the output values and corresponding times to the output arraylist. This will be used in Finish() DateTime Currenttime = CalendarConverter.ModifiedJulian2Gregorian( ((TimeStamp)this.GetCurrentTime()).ModifiedJulianDay); output.Add(Currenttime, outputVals); //Set the output values for the downstream component this.SetValues(_outputQuantity, _outputElementSet, new ScalarSet(Outflow)); //advance time AdvanceTime(); return(true); }
private ListViewItem GetItem(IEvent Event) { string[] subItems = new string[5]; subItems[0] = (_eventsCount++).ToString(); subItems[1] = Event.Type.ToString(); subItems[2] = Event.Description; ILinkableComponent sender = Event.Sender; if (sender != null) { subItems[3] = sender.ModelID; } ITimeStamp simTime = Event.SimulationTime; if (simTime != null) { subItems[4] = CalendarConverter.ModifiedJulian2Gregorian(simTime.ModifiedJulianDay).ToString(); } return(new ListViewItem(subItems)); }
/// <summary> /// Runs simulation. /// </summary> /// <param name="runListener">Simulation listener.</param> /// <param name="runInSameThread">If <c>true</c>, simulation is run in same thread like caller, /// ie. method blocks until simulation don't finish. If <c>false</c>, simulation is /// run in separate thread and method returns immediately.</param> /// <remarks> /// Simulation is run the way that trigger invokes <see cref="ILinkableComponent.GetValues">ILinkableComponent.GetValues</see> /// method of the model it's connected to /// at the time specified by <see cref="TriggerInvokeTime">TriggerInvokeTime</see> property. /// If you need to use more than one listener you can use <see cref="ProxyListener">ProxyListener</see> /// class or <see cref="ProxyMultiThreadListener">ProxyMultiThreadListener</see> if <c>runInSameThread</c> is <c>false</c>. /// </remarks> public void Run(Logger logger, bool runInSameThread) { LoggerListener loggerListener = new LoggerListener(logger); ProgressListener progressListener = new ProgressListener(); progressListener.ModelProgressChangedHandler += new ModelProgressChangedDelegate(delegate(ILinkableComponent linkableComponent, ITimeStamp simTime) { string guid = cmGuidMapping[linkableComponent]; string progress = CalendarConverter.ModifiedJulian2Gregorian(simTime.ModifiedJulianDay).ToString(); CompositionModelProgressChangedHandler(this, guid, progress); }); ArrayList listeners = new ArrayList(); listeners.Add(loggerListener); listeners.Add(progressListener); ProxyListener proxyListener = new ProxyListener(); proxyListener.Initialize(listeners); startTime = DateTime.Now; if (_running) { throw (new Exception("Simulation is already running.")); } _running = true; _runListener = proxyListener; try { TimeStamp runToTime = new TimeStamp(CalendarConverter.Gregorian2ModifiedJulian(_triggerInvokeTime)); // Create informative message if (_runListener != null) { StringBuilder description = new StringBuilder(); description.Append("Starting simulation at "); description.Append(DateTime.Now.ToString()); description.Append(","); description.Append(" composition consists from following models:\n"); foreach (Model model in _models) { description.Append(model.ModelID); description.Append(", "); } // todo: add more info? Event theEvent = new Event(EventType.Informative); theEvent.Description = description.ToString(); _runListener.OnEvent(theEvent); } _runPrepareForComputationStarted = true; // prepare for computation if (_runListener != null) { Event theEvent = new Event(EventType.Informative); theEvent.Description = "Preparing for computation...."; _runListener.OnEvent(theEvent); } // subscribing event listener to all models if (_runListener != null) { Event theEvent = new Event(EventType.Informative); theEvent.Description = "Subscribing proxy event listener...."; _runListener.OnEvent(theEvent); for (int i = 0; i < _runListener.GetAcceptedEventTypeCount(); i++) { foreach (Model uimodel in _models) { theEvent = new Event(EventType.Informative); theEvent.Description = "Calling Subscribe() method with EventType." + ((EventType)i).ToString() + " of model " + uimodel.ModelID; _runListener.OnEvent(theEvent); for (int j = 0; j < uimodel.LinkableComponent.GetPublishedEventTypeCount(); j++) { if (uimodel.LinkableComponent.GetPublishedEventType(j) == _runListener.GetAcceptedEventType(i)) { uimodel.LinkableComponent.Subscribe(_runListener, _runListener.GetAcceptedEventType(i)); break; } } } } } if (!runInSameThread) { // creating run thread if (_runListener != null) { Event theEvent = new Event(EventType.Informative); theEvent.Description = "Creating run thread...."; _runListener.OnEvent(theEvent); } _runThread = new Thread(RunThreadFunction) { Priority = ThreadPriority.Normal }; // starting thread... if (_runListener != null) { Event theEvent = new Event(EventType.GlobalProgress); theEvent.Description = "Starting run thread...."; _runListener.OnEvent(theEvent); } _runThread.Start(); } else { // run simulation in same thread (for example when running from console) if (_runListener != null) { Event theEvent = new Event(EventType.Informative); theEvent.Description = "Running simulation in same thread...."; _runListener.OnEvent(theEvent); } RunThreadFunction(); } } catch (System.Exception e) { if (_runListener != null) { Event theEvent = new Event(EventType.Informative); theEvent.Description = "Exception occured while initiating simulation run: " + e.ToString(); _runListener.OnEvent(theEvent); _runListener.OnEvent(SimulationFailedEvent); // todo: add info about time to this event endTime = DateTime.Now; var ev = new Event { Description = "Elapsed time: " + (endTime - startTime), Type = EventType.GlobalProgress }; _runListener.OnEvent(ev); } } finally { } }
public void GetEarliestNeededTime() { Assert.AreEqual(_simulationStart, CalendarConverter.ModifiedJulian2Gregorian(_gwModelEngine.GetEarliestNeededTime().ModifiedJulianDay)); _gwModelEngine.PerformTimeStep(); Assert.AreEqual(_simulationStart + new System.TimeSpan(1, 0, 0, 0, 0), CalendarConverter.ModifiedJulian2Gregorian(_gwModelEngine.GetEarliestNeededTime().ModifiedJulianDay)); }
public void GetCurrentTime() { Assert.AreEqual(_simulationStart, CalendarConverter.ModifiedJulian2Gregorian(((ITimeStamp)_gwModelEngine.GetCurrentTime()).ModifiedJulianDay)); _gwModelEngine.PerformTimeStep(); Assert.AreEqual(_simulationStart + new System.TimeSpan(1, 0, 0, 0, 0), CalendarConverter.ModifiedJulian2Gregorian(((ITimeStamp)_gwModelEngine.GetCurrentTime()).ModifiedJulianDay)); }
public void GetTimeHorizon() { Assert.AreEqual(_simulationStart, CalendarConverter.ModifiedJulian2Gregorian(_gwModelEngine.GetTimeHorizon().Start.ModifiedJulianDay)); Assert.AreEqual(_simulationEnd, CalendarConverter.ModifiedJulian2Gregorian(_gwModelEngine.GetTimeHorizon().End.ModifiedJulianDay)); }
public override bool PerformTimeStep() { //Get input streamflow ScalarSet streamflow = (ScalarSet)this.GetValues(input_quantity, input_elementset); //transform streamflow to double[] double[] inflow_vals = streamflow.data; //initialize the flow at the outlet to zero double flow_at_outlet = 0.0; //get the current time TimeStamp time = (TimeStamp)this.GetCurrentTime(); DateTime current = CalendarConverter.ModifiedJulian2Gregorian(time.ModifiedJulianDay); //get the time when calc's will be performed current = current.AddSeconds(_ts); //round to the nearest 5min interval current = new DateTime(((current.Ticks + 25000000) / 50000000) * 50000000); //get enumerator of source nodes for the topologically sorted graph IEnumerator topoEnum = _topoSort.GetEnumerator(); #region Set Inflows //loop through all of the reaches in the order they are sorted while (topoEnum.MoveNext()) { //loop through all of the edges in the graph foreach (TaggedEdge <Int64, Reach> edge in g.Edges) { //check if the source node (unsorted graph) of the edge equals the current source node of the sorted graph if (edge.Source == Convert.ToInt64(topoEnum.Current)) { int sourceID = 0; //loop through all of the edges of the graph again foreach (TaggedEdge <Int64, Reach> downstreamEdge in g.Edges) { //find the edge in which the source node equals the current edge's target node if (downstreamEdge.Source == edge.Target) { //get the index of the target (based on the unsorted graph)to determine the input value // corresponding with the edge.Target edge. int index = 0; foreach (TaggedEdge <Int64, Reach> r in g.Edges) { if (r.Source == edge.Source) { break; } index++; } //apply the inflow to the downstream edge if (downstreamEdge.Tag.inflow.ContainsKey(current)) { //HACK: This assumes that reach ID's are 1-based //downstreamEdge.Tag.inflow[current] += inflow_vals[edge.Tag.id - 1]; downstreamEdge.Tag.inflow[current] += inflow_vals[index]; } else { //HACK: This assumes that reach ID's are 1-based //downstreamEdge.Tag.inflow[current] = inflow_vals[edge.Tag.id - 1]; downstreamEdge.Tag.inflow.Add(current, inflow_vals[index]); } //break the loop break; } sourceID++; //if no downstream edges are found, this edge must connect to the outlet if (sourceID == inflow_vals.Length) { //get the index (based on the unsorted graph)to determine the correct input value int index = 0; foreach (TaggedEdge <Int64, Reach> r in g.Edges) { if (r.Source == edge.Source) { break; } index++; } //flow_at_outlet += inflow_vals[edge.Tag.id-1]; flow_at_outlet += inflow_vals[index]; break; } } //break the loop break; } //index++; } } #endregion #region Route Flows //reset the sorted graph topoEnum.Reset(); while (topoEnum.MoveNext()) { //---- ROUTE THE FLOW DOWN THIS REACH ---- TaggedEdge <Int64, Reach> e = null; //find the edge that correspondes to this source node foreach (TaggedEdge <Int64, Reach> edge in g.Edges) { //get the source node if (edge.Source == Convert.ToInt64(topoEnum.Current)) { e = edge; break; } } //no downstream edge found (outlet condition) if (e == null) { break; } #region Muskingum Computation //get inflow from previous time step double In0 = e.Tag.inflow[current.AddSeconds(-1.0 * _ts)]; //check that this inflow is not negative if (e.Tag.inflow.ContainsKey(current)) { if (e.Tag.inflow[current] < 0) { e.Tag.inflow[current] = 0; } } else { e.Tag.inflow[current] = 0.0; } ////////check that this inflow is not negative //////try //////{ ////// if (e.Tag.inflow[current] < 0) ////// e.Tag.inflow[current] = 0; //////} //////catch (KeyNotFoundException) //////{ ////// e.Tag.inflow[current] = 0.0; //////} //get the inflow from the current timestep double In1 = e.Tag.inflow[current]; //get outflow from previous time step double Out0 = e.Tag.outflow[current.AddSeconds(-1.0 * _ts)]; //TODO: write to log if the calculated flow is unstable //calculate outflow for current time step double Out1 = e.Tag.C1 * In1 + e.Tag.C2 * In0 + e.Tag.C3 * Out0; //store calculated outflow in the Reach class e.Tag.outflow[current] = Out1; #endregion #region Add this flow to downstream reach Int64 targetNode = e.Target; TaggedEdge <Int64, Reach> outEdge = null; //get outflow edge foreach (TaggedEdge <Int64, Reach> edge in g.Edges) { if (edge.Source == targetNode) { //set the out edge outEdge = edge; //break the loop break; } } //if outEdge == null then the current reach has no successors if (outEdge != null) { //HACK: this is taken from the other Muskingum component //outEdge.Tag.inflow[current] = In1; //apply outflow to downstream reach if (outEdge.Tag.inflow.ContainsKey(current)) { outEdge.Tag.inflow[current] += Out1; } else { outEdge.Tag.inflow[current] = Out1; } ////////apply outflow to downstream reach //////try //////{ ////// outEdge.Tag.inflow[current] += Out1; //////} //////catch (SystemException) //////{ ////// outEdge.Tag.inflow[current] = Out1; //////} } //downstream must be the outlet else { flow_at_outlet += Out1; } //Set the current inflow for this reach equal to the inflow from the previos timestep //save the previous inflow value e.Tag.inflow[current.AddSeconds(-1 * _ts)] = In1; } #endregion #endregion #region Save the Outflows //Parse outflow_stream into double[] in the order of the input file topoEnum.Reset(); double[] outflows = new double[g.EdgeCount]; while (topoEnum.MoveNext()) { //find corresponding edge index int index = 0; TaggedEdge <Int64, Reach> edge = null; foreach (TaggedEdge <Int64, Reach> e in g.Edges) { if (e.Source == Convert.ToInt64(topoEnum.Current)) { //set the edge edge = e; break; } index++; } if (index == outflows.Length) { int index2 = 0; TaggedEdge <Int64, Reach> edge2 = null; //find the reach the goes to the outlet foreach (TaggedEdge <Int64, Reach> e in g.Edges) { if (e.Target == Convert.ToInt64(topoEnum.Current)) { //set the edge edge2 = e; break; } index2++; } //HACK //outflows[index2] = flow_at_outlet; } else { try { outflows[index] = edge.Tag.outflow[current]; } catch (SystemException) { throw new Exception("Stop"); } } } #endregion //HACK: Negative values should be reported so that the modeler knows that the simulation is unstable //set any negative flow values equal to zero for (int o = 0; o <= outflows.Length - 1; o++) { if (outflows[o] < 0) { outflows[o] = 0; } } //set the values this.SetValues(output_quantity, output_elementset, new ScalarSet(outflows)); //--- save values to output them in the Finish() method --- //get current time and convert into UTC time TimeStamp currenttime = (TimeStamp)this.GetCurrentTime(); DateTime modTime = CalendarConverter.ModifiedJulian2Gregorian(currenttime.ModifiedJulianDay); _output[modTime] = outflows; //Advance time this.AdvanceTime(); return(true); }