/// <summary> /// Reads the Configuration file, and creates OpenMI exchange items /// </summary> /// <param name="configFile">path pointing to the components comfiguration (XML) file</param> public void SetVariablesFromConfigFile(string configFile) { //Read config file XmlDocument doc = new XmlDocument(); doc.Load(configFile); XmlElement root = doc.DocumentElement; XmlNodeList outputExchangeItems = root.SelectNodes("//OutputExchangeItem"); foreach (XmlNode outputExchangeItem in outputExchangeItems) { OutputExchangeItem o = (OutputExchangeItem)CreateExchangeItemsFromXMLNode(outputExchangeItem, "OutputExchangeItem"); _outputExchangeItems.Add(o); string Key = o.ElementSet.ID + ":" + o.Quantity.ID; System.Collections.Hashtable hashtable = new Hashtable(); hashtable.Add("OutputExchangeItem", Key); //pass this info to the IRunEngine, via Intitialize _engineApiAccess.Initialize(hashtable); } XmlNodeList inputExchangeItems = root.SelectNodes("//InputExchangeItem"); foreach (XmlNode inputExchangeItem in inputExchangeItems) { InputExchangeItem i = (InputExchangeItem)CreateExchangeItemsFromXMLNode(inputExchangeItem, "InputExchangeItem"); _inputExchangeItems.Add(i); } XmlNode timeHorizon = root.SelectSingleNode("//TimeHorizon"); this.start = CalendarConverter.Gregorian2ModifiedJulian(Convert.ToDateTime(timeHorizon["StartDateTime"].InnerText)); }
public void ExchangeItems() { Assert.AreEqual(1, testComponent1.InputExchangeItemCount); Assert.AreEqual(1, testComponent1.OutputExchangeItemCount); Quantity q = new Quantity("Q"); ElementSet elementSet = new ElementSet(); elementSet.ID = "ES"; InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.Quantity = q; inputExchangeItem.ElementSet = elementSet; Assert.AreEqual(testComponent1.GetInputExchangeItem(0), inputExchangeItem); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.Quantity = new Quantity("Q2"); ElementSet elementSet2 = new ElementSet(); elementSet2.ID = "ES2"; outputExchangeItem.ElementSet = elementSet; Assert.AreEqual(testComponent1.GetOutputExchangeItem(0), outputExchangeItem); }
public void ExchangeItemsDefinedByConfig() { _engine = new LoadCalculator.LoadCalculatorLinkableEngine(); ArrayList componentArguments = new ArrayList(); componentArguments.Add(new Argument("ConfigFile", "./config.xml", true, "none")); _engine.Initialize((IArgument[])componentArguments.ToArray(typeof(IArgument))); int in_count = _engine.InputExchangeItemCount; int out_count = _engine.OutputExchangeItemCount; for (int i = 0; i <= in_count - 1; i++) { InputExchangeItem ie = (InputExchangeItem)_engine.GetInputExchangeItem(i); Debug.Write("Testing Input Element Count..."); Assert.IsFalse(ie.ElementSet.ElementCount > 0); Debug.WriteLine("done."); Debug.Write("Testing Input Conv2SI..."); Assert.IsTrue(ie.Quantity.Unit.ConversionFactorToSI >= 0); Debug.WriteLine("done."); Debug.Write("Testing Input Offset2SI..."); Assert.IsTrue(ie.Quantity.Unit.OffSetToSI >= 0); Debug.WriteLine("done."); } for (int i = 0; i <= out_count - 1; i++) { OutputExchangeItem oe = (OutputExchangeItem)_engine.GetOutputExchangeItem(i); Debug.Write("Testing Output Element Count..."); Assert.IsTrue(oe.ElementSet.ElementCount > 0); Debug.WriteLine("done."); Debug.Write("Testing Output Conv2SI..."); Assert.IsTrue(oe.Quantity.Unit.ConversionFactorToSI >= 0); Debug.WriteLine("done."); Debug.Write("Testing Output Offset2SI..."); Assert.IsTrue(oe.Quantity.Unit.OffSetToSI >= 0); Debug.WriteLine("done."); } Assert.IsTrue(_engine.TimeHorizon.Start.ModifiedJulianDay == CalendarConverter. Gregorian2ModifiedJulian(new DateTime(2009, 10, 27, 08, 30, 00))); _engine.Finish(); }
public override void Initialize(IArgument[] properties) { SendEvent(new Event(EventType.Informative, this, "Started initialization..")); Dictionary<string, string> arguments = new Dictionary<string, string>(); for (int i = 0; i < properties.Length; i++) { arguments.Add(properties[i].Key, properties[i].Value); } filename = arguments["Filename"]; outputFilename = arguments["OutputFilename"]; tsGroup = TimeSeriesGroupFactory.Create(filename); foreach (BaseTimeSeries baseTimeSeries in tsGroup.Items) { HydroNumerics.OpenMI.Sdk.Backbone.Dimension dimention = new HydroNumerics.OpenMI.Sdk.Backbone.Dimension(); dimention.AmountOfSubstance = baseTimeSeries.Unit.Dimension.AmountOfSubstance; dimention.Currency = baseTimeSeries.Unit.Dimension.Currency; dimention.ElectricCurrent = baseTimeSeries.Unit.Dimension.ElectricCurrent; dimention.Length = baseTimeSeries.Unit.Dimension.Length; dimention.LuminousIntensity = baseTimeSeries.Unit.Dimension.LuminousIntensity; dimention.Mass = baseTimeSeries.Unit.Dimension.Mass; dimention.Time = baseTimeSeries.Unit.Dimension.Time; HydroNumerics.OpenMI.Sdk.Backbone.Unit unit = new HydroNumerics.OpenMI.Sdk.Backbone.Unit(); unit.ID = baseTimeSeries.Unit.ID; unit.Description = baseTimeSeries.Unit.Description; unit.ConversionFactorToSI = baseTimeSeries.Unit.ConversionFactorToSI; unit.OffSetToSI = baseTimeSeries.Unit.OffSetToSI; TsQuantity quantity = new TsQuantity(); quantity.ID = baseTimeSeries.Name; quantity.Description = baseTimeSeries.Description; quantity.Dimension = dimention; quantity.Unit = unit; quantity.BaseTimeSeries = baseTimeSeries; ElementSet elementSet = new ElementSet(); elementSet.ID = "IDBased"; elementSet.Description = "IDBased"; elementSet.ElementType = global::OpenMI.Standard.ElementType.IDBased; elementSet.SpatialReference = new SpatialReference("Undefined"); Element element = new Element(); element.ID = "IDBased"; elementSet.AddElement(element); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.Quantity = quantity; outputExchangeItem.ElementSet = elementSet; this.AddOutputExchangeItem(outputExchangeItem); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.Quantity = quantity; inputExchangeItem.ElementSet = elementSet; this.AddInputExchangeItem(inputExchangeItem); } initializeWasInvoked = true; SendEvent(new Event(EventType.Informative, this, "Completed initialization")); }
public void GetInputExchangeItems() { EngineWrapper engineWrapper = new EngineWrapper(); engineWrapper.Initialize(arguments); Assert.AreEqual(2, engineWrapper.GetInputExchangeItemCount()); List <HydroNumerics.OpenMI.Sdk.Backbone.InputExchangeItem> inputExchangeItemsList = new List <InputExchangeItem>(); for (int i = 0; i < engineWrapper.GetInputExchangeItemCount(); i++) { inputExchangeItemsList.Add(engineWrapper.GetInputExchangeItem(i)); } InputExchangeItem inputExchangeItem = inputExchangeItemsList.First(myVar => myVar.Quantity.ID == "Flow"); Assert.AreEqual("Flow", inputExchangeItem.Quantity.ID); Assert.AreEqual("Inflow to Upper lake", inputExchangeItem.ElementSet.ID); Assert.AreEqual(ElementType.IDBased, inputExchangeItem.ElementSet.ElementType); inputExchangeItem = inputExchangeItemsList.First(myVar => myVar.Quantity.ID == "Head"); Assert.AreEqual("Head", inputExchangeItem.Quantity.ID); Assert.AreEqual("Groundwater boundary under Upper Lake", inputExchangeItem.ElementSet.ID); Assert.AreEqual(ElementType.XYPolygon, inputExchangeItem.ElementSet.ElementType); Assert.AreEqual(6, inputExchangeItem.ElementSet.GetVertexCount(0)); }
public void GetValues_AsProvider() { LinkableTimeSeriesGroup linkableTimeSeriesGroup = new LinkableTimeSeriesGroup(); linkableTimeSeriesGroup.Initialize(arguments); InputExchangeItem targetExchangeItem = new InputExchangeItem(); Quantity targetQuantity = new Quantity(); targetQuantity.ID = "Water Level"; targetQuantity.Unit = new HydroNumerics.OpenMI.Sdk.Backbone.Unit("meter", 1, 0, "meter"); ElementSet targetElementSet = new ElementSet("inputLocation", "Location", ElementType.IDBased, new SpatialReference("")); targetElementSet.AddElement(new Element("E1")); Link link = new Link(); link.SourceComponent = linkableTimeSeriesGroup; link.SourceQuantity = linkableTimeSeriesGroup.GetOutputExchangeItem(1).Quantity; link.SourceElementSet = linkableTimeSeriesGroup.GetOutputExchangeItem(1).ElementSet; link.TargetComponent = null; link.TargetQuantity = targetQuantity; link.TargetElementSet = targetElementSet; link.ID = "Link001"; linkableTimeSeriesGroup.AddLink(link); linkableTimeSeriesGroup.Prepare(); IValueSet valueSet = linkableTimeSeriesGroup.GetValues(new TimeStamp(new System.DateTime(2010, 1, 5)), "Link001"); Assert.AreEqual(0.063, ((IScalarSet)valueSet).GetScalar(0)); linkableTimeSeriesGroup.Finish(); linkableTimeSeriesGroup.Dispose(); }
public override void Initialize(IArgument[] properties) { for (int i = 0; i < 20; i++) { string ID = (i + 1).ToString(); Quantity quantity = new Quantity(new Unit("Unit", 1.0, 0.0, "Unit"), "Quantity", "Quantity"); ElementSet elementSet = new ElementSet(ID, ID, ElementType.IDBased, new SpatialReference()); Element element = new Element(ID); elementSet.AddElement(element); InputExchangeItem exchangeItem = new InputExchangeItem(); exchangeItem.ElementSet = elementSet; exchangeItem.Quantity = quantity; AddInputExchangeItem(exchangeItem); } for (int i = 0; i < 20; i++) { string ID = (i + 1).ToString(); Quantity quantity = new Quantity(new Unit("Unit", 1.0, 0.0, "Unit"), "Quantity", "Quantity"); ElementSet elementSet = new ElementSet(ID, ID, ElementType.IDBased, new SpatialReference()); Element element = new Element(ID); elementSet.AddElement(element); OutputExchangeItem exchangeItem = new OutputExchangeItem(); exchangeItem.ElementSet = elementSet; exchangeItem.Quantity = quantity; AddOutputExchangeItem(exchangeItem); } }
public void Initialize(Hashtable properties) { double ox = 2.0; double oy = 2.0; double dx = 4.0; double dy = 4.0; // -- Populate Input Exchange Items --- Element element0 = new Element("element:0"); element0.AddVertex(new Vertex(ox, oy, 0)); element0.AddVertex(new Vertex(ox + dx, oy, 0)); element0.AddVertex(new Vertex(ox + dx, oy + dy, 0)); element0.AddVertex(new Vertex(ox, oy + dy, 0)); Element element1 = new Element("element:1"); element1.AddVertex(new Vertex(ox + dx, oy, 0)); element1.AddVertex(new Vertex(ox + 2 * dx, oy, 0)); element1.AddVertex(new Vertex(ox + 2 * dx, oy + dy, 0)); element1.AddVertex(new Vertex(ox + dx, oy + dy, 0)); Element element2 = new Element("element:2"); element2.AddVertex(new Vertex(ox, oy + dy, 0)); element2.AddVertex(new Vertex(ox + dx, oy + dy, 0)); element2.AddVertex(new Vertex(ox + dx, oy + 2 * dy, 0)); element2.AddVertex(new Vertex(ox, oy + 2 * dy, 0)); Element element3 = new Element("element:3"); element3.AddVertex(new Vertex(ox + dx, oy + dy, 0)); element3.AddVertex(new Vertex(ox + 2 * dx, oy + dy, 0)); element3.AddVertex(new Vertex(ox + 2 * dx, oy + 2 * dy, 0)); element3.AddVertex(new Vertex(ox + dx, oy + 2 * dy, 0)); ElementSet elementSet = new ElementSet("RegularGrid", "RegularGrid", ElementType.Polygon, " "); elementSet.AddElement(element0); elementSet.AddElement(element1); elementSet.AddElement(element2); elementSet.AddElement(element3); Unit storageUnit = new Unit("Storage", 1.0, 0.0, "Storage"); storageUnit.Dimension = new Dimension(); Quantity storageQuantity = new Quantity(storageUnit, "Storage", "Storage"); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.ElementSet = elementSet; inputExchangeItem.Quantity = storageQuantity; _inputExchangeItems.Add(inputExchangeItem); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.ElementSet = elementSet; outputExchangeItem.Quantity = storageQuantity; _outputExchangeItems.Add(outputExchangeItem); }
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 Initialize(System.Collections.Hashtable properties) { double ox = 2.0; double oy = 2.0; double dx = 4.0; double dy = 4.0; // -- Populate Input Exchange Items --- Element element0 = new Element("element:0"); element0.AddVertex(new Vertex(ox, oy, 0)); element0.AddVertex(new Vertex(ox + dx, oy, 0)); element0.AddVertex(new Vertex(ox + dx, oy + dy, 0)); element0.AddVertex(new Vertex(ox, oy + dy, 0)); Element element1 = new Element("element:1"); element1.AddVertex(new Vertex(ox + dx, oy, 0)); element1.AddVertex(new Vertex(ox + 2 * dx, oy, 0)); element1.AddVertex(new Vertex(ox + 2 * dx, oy + dy, 0)); element1.AddVertex(new Vertex(ox + dx, oy + dy, 0)); Element element2 = new Element("element:2"); element2.AddVertex(new Vertex(ox, oy + dy, 0)); element2.AddVertex(new Vertex(ox + dx, oy + dy, 0)); element2.AddVertex(new Vertex(ox + dx, oy + 2 * dy, 0)); element2.AddVertex(new Vertex(ox, oy + 2 * dy, 0)); Element element3 = new Element("element:3"); element3.AddVertex(new Vertex(ox + dx, oy + dy, 0)); element3.AddVertex(new Vertex(ox + 2 * dx, oy + dy, 0)); element3.AddVertex(new Vertex(ox + 2 * dx, oy + 2 * dy, 0)); element3.AddVertex(new Vertex(ox + dx, oy + 2 * dy, 0)); ElementSet elementSet = new ElementSet("RegularGrid", "RegularGrid", ElementType.XYPolygon, new SpatialReference(" ")); elementSet.AddElement(element0); elementSet.AddElement(element1); elementSet.AddElement(element2); elementSet.AddElement(element3); Quantity storageQuantity = new Quantity(new Unit("Storage", 1.0, 0.0, "Storage"), "Storage", "Storage", global::OpenMI.Standard.ValueType.Scalar, new Dimension()); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.ElementSet = elementSet; inputExchangeItem.Quantity = storageQuantity; _inputExchangeItems.Add(inputExchangeItem); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.ElementSet = elementSet; outputExchangeItem.Quantity = storageQuantity; _outputExchangeItems.Add(outputExchangeItem); }
public override IInputExchangeItem GetInputExchangeItem(int inputExchangeItemIndex) { Quantity quantity = new Quantity(new Unit("Unit", 1.0, 0.0, "Unit"), "Quantity", "Quantity"); ElementSet elementSet = new ElementSet("1", "1", ElementType.IDBased, new SpatialReference()); InputExchangeItem exchangeItem = new InputExchangeItem(); exchangeItem.ElementSet = elementSet; exchangeItem.Quantity = quantity; return(exchangeItem); }
public void Init() { eventSent = false; testComponent1 = new TestComponent(); testComponent2 = new TestComponent2(); Link link1 = new Link(); link1.ID = "Link1"; link1.SourceComponent = testComponent1; link1.TargetComponent = testComponent2; Link link2 = new Link(); link2.ID = "Link2"; link2.SourceComponent = testComponent2; link2.TargetComponent = testComponent1; Link link3 = new Link(); link3.ID = "Link3"; link3.SourceComponent = link3.TargetComponent = testComponent1; testComponent1.AddLink(link1); testComponent1.AddLink(link2); testComponent1.AddLink(link3); testComponent2.AddLink(link1); testComponent2.AddLink(link2); testComponent1.RemoveLink("Link3"); testComponent1.Subscribe(this, EventType.Informative); Quantity q = new Quantity("Q"); ElementSet elementSet = new ElementSet(); elementSet.ID = "ES"; InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.Quantity = q; inputExchangeItem.ElementSet = elementSet; testComponent1.AddInputExchangeItem(inputExchangeItem); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.Quantity = new Quantity("Q2"); ElementSet elementSet2 = new ElementSet(); elementSet2.ID = "ES2"; outputExchangeItem.ElementSet = elementSet; testComponent1.AddOutputExchangeItem(outputExchangeItem); }
public override IInputExchangeItem GetInputExchangeItem(int inputExchangeItemIndex) { inputExchangeItemIndex++; string ID = inputExchangeItemIndex.ToString(); Quantity quantity = new Quantity(new Unit("Unit", 1.0, 0.0, "Unit"), "Quantity", "Quantity"); ElementSet elementSet = new ElementSet(ID, ID, ElementType.IDBased, new SpatialReference()); Element element = new Element(ID); elementSet.AddElement(element); InputExchangeItem exchangeItem = new InputExchangeItem(); exchangeItem.ElementSet = elementSet; exchangeItem.Quantity = quantity; return(exchangeItem); }
public void Initialize(System.Collections.Hashtable properties) { _dt = 1.0; _dx = 0.0; _initialValue = 100; if (properties.ContainsKey("modelID")) { _modelID = (string)properties["ModelID"]; } if (properties.ContainsKey("dt")) { _dt = (double)properties["dt"]; } if (properties.ContainsKey("dx")) { _dx = (double)properties["dx"]; } _values = new double[3]; for (int i = 0; i < _values.Length; i++) { _values[i] = _initialValue; } _startTime = 4000; _currentTime = _startTime; Element element = new Element("ElementID"); ElementSet elementSet = new ElementSet("Description", "ID", ElementType.IDBased, new SpatialReference(" no ")); elementSet.AddElement(element); Quantity quantity = new Quantity(new Unit("Flow", 1, 0, "flow"), "Flow", "ID", global::OpenMI.Standard.ValueType.Scalar, new Dimension()); _outputExchangeItem = new OutputExchangeItem(); _inputExchangeItem = new InputExchangeItem(); _outputExchangeItem.Quantity = quantity; _outputExchangeItem.ElementSet = elementSet; _inputExchangeItem.Quantity = quantity; _inputExchangeItem.ElementSet = elementSet; }
public void Initialize(System.Collections.Hashtable properties) { currentTimestep = 0; simulationStart = new DateTime(2001, 1, 1); dt = 172800; //timestep length (2 days) nt = 80; // number of timesteps nx = 2; //number of grid cells in x-direction ny = 2; //number of grid cells in y-direction grid = new RegularGrid(10, 10, 1000, nx, ny, 0); groundwaterHeads = new TimeSeriesGroup(); infiltrations = new TimeSeriesGroup(); for (int i = 0; i < nx * ny; i++) { groundwaterHeads.Items.Add(new TimestampSeries("GwHead" + i.ToString(), simulationStart, nt, dt, TimestepUnit.Seconds, 4.9, new HydroNumerics.Core.Unit("meters", 1.0, 0.0))); infiltrations.Items.Add(new TimestampSeries("Infiltration" + i.ToString(), simulationStart, nt, dt, TimestepUnit.Seconds, -9999.9999, new HydroNumerics.Core.Unit("flow", 1.0, 0.0))); } Quantity infiltQuantity = new Quantity(); infiltQuantity.Unit = new HydroNumerics.OpenMI.Sdk.Backbone.Unit("level", 1.0, 0.0); infiltQuantity.ID = "Infiltration"; infiltQuantity.Description = "infiltration"; infiltQuantity.ValueType = global::OpenMI.Standard.ValueType.Scalar; InputExchangeItem infiltExItem = new InputExchangeItem(); infiltExItem.Quantity = infiltQuantity; infiltExItem.ElementSet = grid; inputExchangeItems = new List <InputExchangeItem>(); inputExchangeItems.Add(infiltExItem); Quantity headQuantity = new Quantity(); headQuantity.Description = "Groundwater head"; headQuantity.ID = "Head"; headQuantity.Unit = new HydroNumerics.OpenMI.Sdk.Backbone.Unit("meters", 1, 0); headQuantity.ValueType = global::OpenMI.Standard.ValueType.Scalar; OutputExchangeItem headOutItem = new OutputExchangeItem(); headOutItem.Quantity = headQuantity; headOutItem.ElementSet = grid; outputExchangeItems = new List <OutputExchangeItem>(); outputExchangeItems.Add(headOutItem); }
public void Init() { eventSent = false; testComponent1 = new TestComponent(); testComponent2 = new TestComponent2(); Link link1 = new Link(); link1.ID ="Link1"; link1.SourceComponent = testComponent1; link1.TargetComponent = testComponent2; Link link2 = new Link(); link2.ID ="Link2"; link2.SourceComponent = testComponent2; link2.TargetComponent = testComponent1; Link link3 = new Link(); link3.ID = "Link3"; link3.SourceComponent = link3.TargetComponent = testComponent1; testComponent1.AddLink(link1); testComponent1.AddLink(link2); testComponent1.AddLink(link3); testComponent2.AddLink(link1); testComponent2.AddLink(link2); testComponent1.RemoveLink("Link3"); testComponent1.Subscribe(this,EventType.Informative); Quantity q = new Quantity("Q"); ElementSet elementSet = new ElementSet(); elementSet.ID = "ES"; InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.Quantity = q; inputExchangeItem.ElementSet = elementSet; testComponent1.AddInputExchangeItem(inputExchangeItem); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.Quantity = new Quantity("Q2"); ElementSet elementSet2 = new ElementSet(); elementSet2.ID = "ES2"; outputExchangeItem.ElementSet = elementSet; testComponent1.AddOutputExchangeItem(outputExchangeItem); }
public override void Initialize(System.Collections.Hashtable properties) { //---- get configuration data string config = null; if (properties.ContainsKey("ConfigFile")) { config = properties["ConfigFile"].ToString(); } else { throw new Exception("A configuration file must be supplied for the Hargreaves component!!!"); } if (properties.ContainsKey("Output")) { output_path = properties["Output"].ToString(); } //---- set smw parameters this.SetVariablesFromConfigFile(config); this.SetValuesTableFields(); //---- get exhange item attributes //-- input exchange items int num_inputs = this.GetInputExchangeItemCount(); input_elementset = new string[num_inputs]; input_quantity = new string[num_inputs]; for (int i = 0; i <= num_inputs - 1; i++) { InputExchangeItem input = this.GetInputExchangeItem(i); input_elementset[i] = input.ElementSet.ID; input_quantity[i] = input.Quantity.ID; } //-- output exchange items int num_outputs = this.GetOutputExchangeItemCount(); OutputExchangeItem output = this.GetOutputExchangeItem(num_outputs - 1); output_elementset = output.ElementSet.ID; output_quantity = output.Quantity.ID; }
public override void Initialize(IArgument[] properties) { foreach (IArgument argument in properties) { if (argument.Key.Equals("Parameter")) { string paramstring = argument.Value; char[] delimiter = new char[1]; delimiter[0] = ','; string[] substring = paramstring.Split(delimiter); string ID = substring[0]; double minimum = Double.Parse(substring[1]); double maximum = Double.Parse(substring[2]); double currentValue = Double.Parse(substring[3]); ParameterDescriptor descriptor = new ParameterDescriptor(ID, minimum, maximum, currentValue); AddParameter(descriptor); Quantity quantity = new Quantity(new Unit("Unit", 1.0, 0.0, "Unit"), "Quantity", "Quantity"); ElementSet elementSet = new ElementSet(ID, ID, ElementType.IDBased, new SpatialReference()); OutputExchangeItem exchangeItem = new OutputExchangeItem(); exchangeItem.ElementSet = elementSet; exchangeItem.Quantity = quantity; AddOutputExchangeItem(exchangeItem); } } for (int i = 0; i < 1; i++) { string ID = (i + 1).ToString(); Quantity quantity = new Quantity(new Unit("Unit", 1.0, 0.0, "Unit"), "Cost", "Cost"); ElementSet elementSet = new ElementSet(ID, ID, ElementType.IDBased, new SpatialReference()); Element element = new Element(ID); elementSet.AddElement(element); InputExchangeItem exchangeItem = new InputExchangeItem(); exchangeItem.ElementSet = elementSet; exchangeItem.Quantity = quantity; AddInputExchangeItem(exchangeItem); } }
public void ExchangeItems() { Assert.AreEqual(1,testComponent1.InputExchangeItemCount); Assert.AreEqual(1,testComponent1.OutputExchangeItemCount); Quantity q = new Quantity("Q"); ElementSet elementSet = new ElementSet(); elementSet.ID = "ES"; InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.Quantity = q; inputExchangeItem.ElementSet = elementSet; Assert.AreEqual(testComponent1.GetInputExchangeItem(0),inputExchangeItem); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.Quantity = new Quantity("Q2"); ElementSet elementSet2 = new ElementSet(); elementSet2.ID = "ES2"; outputExchangeItem.ElementSet = elementSet; Assert.AreEqual(testComponent1.GetOutputExchangeItem(0),outputExchangeItem); }
public override void RemoveLink(string LinkID) { base.RemoveLink(LinkID); Link link = (Link)_links[LinkID]; Quantity q = new Quantity(); q = (Quantity)link.SourceQuantity; ElementSet eset = new ElementSet(); eset = (ElementSet)link.SourceElementSet; InputExchangeItem input = new InputExchangeItem(); input.Quantity = q; input.ElementSet = eset; //generate an output exchange item based on the input its getting OutputExchangeItem output = new OutputExchangeItem(); output.Quantity = q; output.ElementSet = eset; //remove link if (_outputExchangeItems.Contains(output)) { _outputExchangeItems.Remove(output); } if (_inputExchangeItems.Contains(input)) { _inputExchangeItems.Remove(input); } _links.Remove(LinkID); }
public void ExchangeItemsDefinedByOmi() { _engine = new LoadCalculator.LoadCalculatorLinkableEngine(); ArrayList componentArguments = new ArrayList(); componentArguments.Add(new Argument("StartDateTime", "10/27/2009 8:30:00AM", true, "none")); componentArguments.Add(new Argument("TimeStepInSeconds", "86400", true, "none")); componentArguments.Add(new Argument("InputTimeSeries", "Discharge:[cms]", true, "none")); componentArguments.Add(new Argument("InputTimeSeries", "Concentration:[mg/l]", true, "none")); componentArguments.Add(new Argument("OutputTimeSeries", "GillsCreek:Nitrogen Loading:[kg/day]:NumElements=1", true, "none")); _engine.Initialize((IArgument[])componentArguments.ToArray(typeof(IArgument))); int in_count = _engine.InputExchangeItemCount; int out_count = _engine.OutputExchangeItemCount; for (int i = 0; i <= in_count - 1; i++) { InputExchangeItem ie = (InputExchangeItem)_engine.GetInputExchangeItem(i); Debug.Write("Testing Input Element Count..."); Assert.IsFalse(ie.ElementSet.ElementCount > 0); Debug.WriteLine("done."); Debug.Write("Testing Input Conv2SI..."); Assert.IsTrue(ie.Quantity.Unit.ConversionFactorToSI >= 0); Debug.WriteLine("done."); Debug.Write("Testing Input Offset2SI..."); Assert.IsTrue(ie.Quantity.Unit.OffSetToSI >= 0); Debug.WriteLine("done."); } for (int i = 0; i <= out_count - 1; i++) { OutputExchangeItem oe = (OutputExchangeItem)_engine.GetOutputExchangeItem(i); Debug.Write("Testing Output Element Count..."); Assert.IsTrue(oe.ElementSet.ElementCount > 0); Debug.WriteLine("done."); Debug.Write("Testing Output Conv2SI..."); Assert.IsTrue(oe.Quantity.Unit.ConversionFactorToSI >= 0); Debug.WriteLine("done."); Debug.Write("Testing Output Offset2SI..."); Assert.IsTrue(oe.Quantity.Unit.OffSetToSI >= 0); Debug.WriteLine("done."); } Assert.IsTrue(_engine.TimeHorizon.Start.ModifiedJulianDay == CalendarConverter. Gregorian2ModifiedJulian(new DateTime(2009, 10, 27, 08, 30, 00))); _engine.Finish(); }
public IInputExchangeItem GetInputExchangeItem(int index) { // -- create a flow quanitity -- Dimension flowDimension = new Dimension(); flowDimension.SetPower(DimensionBase.Length, 3); flowDimension.SetPower(DimensionBase.Time, -1); Unit literPrSecUnit = new Unit("LiterPrSecond", 0.001, 0, "Liters pr Second"); Quantity flowQuantity = new Quantity(literPrSecUnit, "Flow", "Flow", global::OpenMI.Standard.ValueType.Scalar, flowDimension); Element element = new Element(); element.ID = "DummyElement"; ElementSet elementSet = new ElementSet("Dummy ElementSet", "DummyElementSet", ElementType.IDBased, new SpatialReference("no reference")); elementSet.AddElement(element); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.ElementSet = elementSet; inputExchangeItem.Quantity = flowQuantity; return(inputExchangeItem); }
public override void Initialize(IArgument[] properties) { SendEvent(new Event(EventType.Informative, this, "Started initialization..")); Dictionary <string, string> arguments = new Dictionary <string, string>(); for (int i = 0; i < properties.Length; i++) { arguments.Add(properties[i].Key, properties[i].Value); } filename = arguments["Filename"]; outputFilename = arguments["OutputFilename"]; tsGroup = TimeSeriesGroupFactory.Create(filename); foreach (BaseTimeSeries baseTimeSeries in tsGroup.Items) { HydroNumerics.OpenMI.Sdk.Backbone.Dimension dimention = new HydroNumerics.OpenMI.Sdk.Backbone.Dimension(); dimention.AmountOfSubstance = baseTimeSeries.Unit.Dimension.AmountOfSubstance; dimention.Currency = baseTimeSeries.Unit.Dimension.Currency; dimention.ElectricCurrent = baseTimeSeries.Unit.Dimension.ElectricCurrent; dimention.Length = baseTimeSeries.Unit.Dimension.Length; dimention.LuminousIntensity = baseTimeSeries.Unit.Dimension.LuminousIntensity; dimention.Mass = baseTimeSeries.Unit.Dimension.Mass; dimention.Time = baseTimeSeries.Unit.Dimension.Time; HydroNumerics.OpenMI.Sdk.Backbone.Unit unit = new HydroNumerics.OpenMI.Sdk.Backbone.Unit(); unit.ID = baseTimeSeries.Unit.ID; unit.Description = baseTimeSeries.Unit.Description; unit.ConversionFactorToSI = baseTimeSeries.Unit.ConversionFactorToSI; unit.OffSetToSI = baseTimeSeries.Unit.OffSetToSI; TsQuantity quantity = new TsQuantity(); quantity.ID = baseTimeSeries.Name; quantity.Description = baseTimeSeries.Description; quantity.Dimension = dimention; quantity.Unit = unit; quantity.BaseTimeSeries = baseTimeSeries; ElementSet elementSet = new ElementSet(); elementSet.ID = "IDBased"; elementSet.Description = "IDBased"; elementSet.ElementType = global::OpenMI.Standard.ElementType.IDBased; elementSet.SpatialReference = new SpatialReference("Undefined"); Element element = new Element(); element.ID = "IDBased"; elementSet.AddElement(element); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.Quantity = quantity; outputExchangeItem.ElementSet = elementSet; this.AddOutputExchangeItem(outputExchangeItem); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.Quantity = quantity; inputExchangeItem.ElementSet = elementSet; this.AddInputExchangeItem(inputExchangeItem); } initializeWasInvoked = true; SendEvent(new Event(EventType.Informative, this, "Completed initialization")); }
/// <summary> /// This method is used to construct the component /// </summary> /// <param name="properties">arguments stored in the *.omi file</param> public void Initialize(IArgument[] properties) { //extract argument(s) from OMI file foreach (IArgument property in properties) { //overwrite the connection string, if one is given in the *.omi if (property.Key == "DbPath") { _dbPath = property.Value; } //default value for relationFactor is 1; if (property.Key == "Relaxation") { _smartBuffer.RelaxationFactor = Convert.ToDouble(property.Value); } if (property.Key == "IgnoreValue") { _ignore = Convert.ToDouble(property.Value); } } //---- set database to default if dbpath is invalid string fullpath = ""; //-- first check if dbpath is null bool pass = true; if (String.IsNullOrWhiteSpace(_dbPath)) { pass = false; } //-- next, check that dbpath points to an actual file else { //-- if relative path is given if (!Path.IsPathRooted(_dbPath)) { fullpath = System.IO.Path.GetFullPath(System.IO.Directory.GetCurrentDirectory() + _dbPath); } //-- if absolute path else { fullpath = System.IO.Path.GetFullPath(_dbPath); } if (!File.Exists(fullpath)) { pass = false; //-- warn the user that the database could not be found System.Windows.Forms.MessageBox.Show("The database supplied in DbWriter.omi could not be found. As a result the DbWriter will connect to the current HydroDesktop database." + "\n\n--- The following database could not be found --- \n" + fullpath, "An Error Occurred While Loading Database...", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); } } //-- set the connection string if (!pass) { conn = Settings.Instance.DataRepositoryConnectionString; } else { //FileInfo fi = new FileInfo(fullpath); //conn = @"Data Source = " + fi.FullName + ";New=False;Compress=True;Version=3"; conn = @"Data Source = " + fullpath + ";New=False;Compress=True;Version=3"; } //---- read db info provided by omi dbargs = ReadDbArgs(properties); //---- create generic input and output exchange items InputExchangeItem inExchangeItem = new InputExchangeItem(); inExchangeItem.ElementSet = new ElementSet("any element set", "any element set", ElementType.IDBased, new Oatc.OpenMI.Sdk.Backbone.SpatialReference("1")); inExchangeItem.Quantity = new Quantity("any quantity"); _inputExchangeItems.Add(inExchangeItem); OutputExchangeItem outExchangeItem = new OutputExchangeItem(); outExchangeItem.ElementSet = new ElementSet("dummy element set", "dummy element set", ElementType.IDBased, new Oatc.OpenMI.Sdk.Backbone.SpatialReference("1")); outExchangeItem.Quantity = new Quantity("dummy quantity"); _outputExchangeItems.Add(outExchangeItem); //---- define arbitrary start and end times _earliestInputTime = CalendarConverter.Gregorian2ModifiedJulian(new DateTime(1900, 1, 1)); _latestInputTime = CalendarConverter.Gregorian2ModifiedJulian(new DateTime(2100, 12, 31)); }
/// <summary> /// This method is used to perform actions prior to model simulation /// </summary> /// <param name="properties"></param> public override void Initialize(System.Collections.Hashtable properties) { //Get config file path defined in sample.omi string configFile = (string)properties["ConfigFile"]; //set OpenMI internal variables this.SetVariablesFromConfigFile(configFile); // initialize a data structure to hold results this.SetValuesTableFields(); //save the time step (defined within the config.xml) _timestep = this.GetTimeStep(); //save input exchange item info InputExchangeItem input = this.GetInputExchangeItem(0); _input_elementset = input.ElementSet.ID; _input_quantity = input.Quantity.ID; //save output exchange item info OutputExchangeItem output = this.GetOutputExchangeItem(0); _output_elementset = output.ElementSet.ID; _output_quantity = output.Quantity.ID; //Note: this can region can be omitted if a shapefile is specified in config.xml #region Manually Define Element Set //Get the input and output element sets from the SMW ElementSet out_elem = (ElementSet)this.Outputs[0].ElementSet; ElementSet in_elem = (ElementSet)this.Inputs[0].ElementSet; //Set some ElementSet properties out_elem.ElementType = OpenMI.Standard.ElementType.XYPoint; in_elem.ElementType = OpenMI.Standard.ElementType.XYPoint; //Create elements e1, e2 and e3 Element e1 = new Element(); Vertex v1 = new Vertex(1, 1, 0); e1.AddVertex(v1); Element e2 = new Element(); Vertex v2 = new Vertex(1, 5, 0); e2.AddVertex(v2); Element e3 = new Element(); Vertex v3 = new Vertex(5, 5, 0); e2.AddVertex(v3); //add these elements to the input and output element sets out_elem.AddElement(e1); out_elem.AddElement(e2); out_elem.AddElement(e3); in_elem.AddElement(e1); in_elem.AddElement(e2); in_elem.AddElement(e3); #endregion //Do some Calculations prior to simulation for (int i = 0; i < in_elem.Elements.Length; i++) { _seeds.Add(_rndNum.Next()); } }
public void Initialize(System.Collections.Hashtable properties) { if (properties.ContainsKey("ModelID")) { _modelID = (string) properties["ModelID"]; } if (properties.ContainsKey("TimeStepLength")) { _timeStepLength = Convert.ToDouble((string) properties["TimeStepLength"]); } // -- create a flow quanitity -- Dimension flowDimension = new Dimension(); flowDimension.SetPower(DimensionBase.Length,3); flowDimension.SetPower(DimensionBase.Time,-1); Unit literPrSecUnit = new Unit("LiterPrSecond",0.001,0,"Liters pr Second"); Quantity flowQuantity = new Quantity(literPrSecUnit,"Flow","Flow",global::OpenMI.Standard.ValueType.Scalar,flowDimension); // -- create leakage quantity -- Quantity leakageQuantity = new Quantity(literPrSecUnit,"Leakage","Leakage",global::OpenMI.Standard.ValueType.Scalar,flowDimension); // -- create and populate elementset to represente the whole river network -- ElementSet fullRiverElementSet = new ElementSet("WholeRiver","WholeRiver",ElementType.XYPolyLine,new SpatialReference("no reference")); for (int i = 0; i < _numberOfNodes -1; i++) { Element element = new Element(); element.ID = "Branch:" + i.ToString(); element.AddVertex(new Vertex(_xCoordinate[i],_yCoordinate[i],-999)); element.AddVertex(new Vertex(_xCoordinate[i+1],_yCoordinate[i+1],-999)); fullRiverElementSet.AddElement(element); } // --- populate input exchange items for flow to individual nodes --- for ( int i = 0; i < _numberOfNodes; i++) { Element element = new Element(); element.ID = "Node:" + i.ToString(); ElementSet elementSet = new ElementSet("Individual nodes","Node:" + i.ToString(), ElementType.IDBased,new SpatialReference("no reference")); elementSet.AddElement(element); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.ElementSet = elementSet; inputExchangeItem.Quantity = flowQuantity; _inputExchangeItems.Add(inputExchangeItem); } // --- Populate input exchange item for flow to the whole georeferenced river --- InputExchangeItem wholeRiverInputExchangeItem = new InputExchangeItem(); wholeRiverInputExchangeItem.ElementSet = fullRiverElementSet; wholeRiverInputExchangeItem.Quantity = flowQuantity; _inputExchangeItems.Add(wholeRiverInputExchangeItem); // --- Populate output exchange items for flow in river branches --- for (int i = 0; i < _numberOfNodes - 1; i++) { Element element = new Element(); element.ID = "Branch:" + i.ToString(); ElementSet elementSet = new ElementSet("Individual nodes","Branch:" + i.ToString(),ElementType.IDBased,new SpatialReference("no reference")); elementSet.AddElement(element); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.ElementSet = elementSet; outputExchangeItem.Quantity = flowQuantity; _outputExchangeItems.Add(outputExchangeItem); } // --- polulate output exchange items for leakage for individual branches -- for (int i = 0; i < _numberOfNodes - 1; i++) { Element element = new Element(); element.ID = "Branch:" + i.ToString(); ElementSet elementSet = new ElementSet("Individual nodes","Branch:" + i.ToString(),ElementType.IDBased,new SpatialReference("no reference")); elementSet.AddElement(element); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.ElementSet = elementSet; outputExchangeItem.Quantity = leakageQuantity; _outputExchangeItems.Add(outputExchangeItem); } // --- Populate output exchange item for leakage from the whole georeferenced river --- OutputExchangeItem wholeRiverOutputExchangeItem = new OutputExchangeItem(); wholeRiverOutputExchangeItem.ElementSet = fullRiverElementSet; wholeRiverOutputExchangeItem.Quantity = leakageQuantity; _outputExchangeItems.Add(wholeRiverOutputExchangeItem); // --- populate with initial state variables --- for (int i = 0; i < _numberOfNodes -1; i++) { _flow[i] = 7; } _currentTimeStepNumber = 1; _initializeMethodWasInvoked = true; }
public void Initialize(System.Collections.Hashtable properties) { if (!properties.Contains("InputFilename")) { throw new Exception("Missing key \"InputFilename\" in parameter to method HydroNumerics.HydroNet.OpenMI.EngineWrapper.Initialize(...)"); } if (!properties.Contains("TimestepLength")) { throw new Exception("Missing key \"TimestepLength\" in parameter to method HydroNumerics.HydroNet.OpenMI.EngineWrapper.Initialize(...)"); } inputFilename = (string)properties["InputFilename"]; double dt = Convert.ToDouble((string)properties["TimestepLength"]); timestepLength = System.TimeSpan.FromSeconds(dt); // because the OpenMI configuration editor works makes paths relative to locations of OMI files or the configuration editor itselves, thigs may go wrong. // In order to overcome this problem, the full path for the input file is saves, so when the Finish method is invoked, the output is save to the input file again and not // a file at some random location :-). See below System.IO.FileInfo fileInfo = new System.IO.FileInfo(inputFilename); inputFilename = fileInfo.FullName; model = HydroNumerics.HydroNet.Core.ModelFactory.GetModel(inputFilename); model.Initialize(); //model = ModelFactory.GetModel(inputFilename); foreach (var wb in model._waterBodies) { //Build exchangeitems from groundwater boundaries foreach (var gwb in wb.GroundwaterBoundaries) { GroundWaterBoundary GWB = gwb as GroundWaterBoundary; if (GWB != null) { ElementSet elementSet = new ElementSet(); elementSet.ID = GWB.Name; elementSet.Description = "Location: " + GWB.Name; elementSet.SpatialReference = new SpatialReference("Undefined"); Element element = new Element(); element.ID = GWB.Name; elementSet.ElementType = ElementType.XYPolygon; foreach (XYPoint xyPoint in ((XYPolygon)GWB.ContactGeometry).Points) { element.AddVertex(new Vertex(xyPoint.X, xyPoint.Y, 0)); } elementSet.AddElement(element); //Head HydroNumerics.OpenMI.Sdk.Backbone.Dimension dimension = new HydroNumerics.OpenMI.Sdk.Backbone.Dimension(); dimension.Length = 1; HydroNumerics.OpenMI.Sdk.Backbone.Unit unit = new HydroNumerics.OpenMI.Sdk.Backbone.Unit(); unit.ID = "m"; unit.Description = "meter"; unit.ConversionFactorToSI = 1; unit.OffSetToSI = 0; Quantity quantity = new Quantity(); quantity.ID = "Head"; quantity.Description = "Head at:" + GWB.Name; quantity.Dimension = dimension; quantity.Unit = unit; InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.Quantity = quantity; inputExchangeItem.ElementSet = elementSet; inputExchangeItems.Add(inputExchangeItem); HeadBoundaries.Add(GWB.Name, GWB); //Leakage Quantity leakage = new Quantity("Leakage"); leakage.Description = "Leakage at:" + GWB.Name; var leakageDimension = new HydroNumerics.OpenMI.Sdk.Backbone.Dimension(); leakageDimension.Length = 3; leakageDimension.Time = -1; leakage.Dimension = leakageDimension; leakage.Unit = new HydroNumerics.OpenMI.Sdk.Backbone.Unit("m3/s", 1, 0); OutputExchangeItem outputitem = new OutputExchangeItem(); outputitem.Quantity = leakage; outputitem.ElementSet = elementSet; outputExchangeItems.Add(outputitem); LeakageBoundaries.Add(GWB.Name, GWB); } } foreach (var S in wb.Sources) { ElementSet elementSet = new ElementSet(); elementSet.ID = S.Name; elementSet.Description = "Location: " + S.Name; elementSet.SpatialReference = new SpatialReference("Undefined"); Element element = new Element(); element.ID = S.Name; elementSet.ElementType = ElementType.IDBased; //Flow Quantity leakage = new Quantity("Flow"); leakage.Description = "Flow at:" + S.Name; var leakageDimension = new HydroNumerics.OpenMI.Sdk.Backbone.Dimension(); leakageDimension.Length = 3; leakageDimension.Time = -1; leakage.Dimension = leakageDimension; leakage.Unit = new HydroNumerics.OpenMI.Sdk.Backbone.Unit("m3/s", 1, 0); InputExchangeItem outputitem = new InputExchangeItem(); outputitem.Quantity = leakage; outputitem.ElementSet = elementSet; inputExchangeItems.Add(outputitem); FlowBoundaries.Add(S.Name, (SinkSourceBoundary)S); } } //foreach (var exchangeItem in model.ExchangeItems) //{ // HydroNumerics.OpenMI.Sdk.Backbone.Dimension dimention = new HydroNumerics.OpenMI.Sdk.Backbone.Dimension(); // dimention.AmountOfSubstance = exchangeItem.Unit.Dimension.AmountOfSubstance; // dimention.Currency = exchangeItem.Unit.Dimension.Currency; // dimention.ElectricCurrent = exchangeItem.Unit.Dimension.ElectricCurrent; // dimention.Length = exchangeItem.Unit.Dimension.AmountOfSubstance; // dimention.LuminousIntensity = exchangeItem.Unit.Dimension.Length; // dimention.Mass = exchangeItem.Unit.Dimension.LuminousIntensity; // dimention.AmountOfSubstance = exchangeItem.Unit.Dimension.Mass; // dimention.Time = exchangeItem.Unit.Dimension.Time; // HydroNumerics.OpenMI.Sdk.Backbone.Unit unit = new HydroNumerics.OpenMI.Sdk.Backbone.Unit(); // unit.ID = exchangeItem.Unit.ID; // unit.Description = exchangeItem.Unit.Description; // unit.ConversionFactorToSI = exchangeItem.Unit.ConversionFactorToSI; // unit.OffSetToSI = unit.OffSetToSI; // Quantity quantity = new Quantity(); // quantity.ID = exchangeItem.Quantity; // quantity.Description = exchangeItem.Description; // quantity.Dimension = dimention; // quantity.Unit = unit; // ElementSet elementSet = new ElementSet(); // elementSet.ID = exchangeItem.Location; // elementSet.Description = "Location: " + exchangeItem.Location; // elementSet.SpatialReference = new SpatialReference("Undefined"); // Element element = new Element(); // element.ID = exchangeItem.Location; // if (exchangeItem.Geometry is XYPolygon) // { // elementSet.ElementType = ElementType.XYPolygon; // foreach (XYPoint xyPoint in ((XYPolygon)exchangeItem.Geometry).Points) // { // element.AddVertex(new Vertex(xyPoint.X, xyPoint.Y, 0)); // } // } // else if (exchangeItem.Geometry is XYPoint) // { // throw new NotImplementedException(); // } // else if (exchangeItem.Geometry is XYPolyline) // { // throw new NotImplementedException(); // } // else // { // elementSet.ElementType = global::OpenMI.Standard.ElementType.IDBased; // } // elementSet.AddElement(element); // if (exchangeItem.IsOutput) // { // OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); // outputExchangeItem.Quantity = quantity; // outputExchangeItem.ElementSet = elementSet; // outputExchangeItems.Add(outputExchangeItem); // } // if (exchangeItem.IsInput) // { // InputExchangeItem inputExchangeItem = new InputExchangeItem(); // inputExchangeItem.Quantity = quantity; // inputExchangeItem.ElementSet = elementSet; // inputExchangeItems.Add(inputExchangeItem); // } //} }
private static List<InputExchangeItem> readInputExchangeItems(XmlNode aNode, ILinkableComponent component, Dictionary<String, IElementSet> elementSets) { var items = new List<InputExchangeItem>(); foreach (XmlNode node in aNode.ChildNodes) { if (node.Name == "InputExchangeItem") { var item = new InputExchangeItem(); // see what the element set id is and lookup the actual // object and assign it to the exchange item var elementSetId = Utils.findChildNodeValue(node, "ElementSetID"); item.ElementSet = elementSets[elementSetId]; // make sure we found the element set if (item.ElementSet == null) throw new Exception("Failed to find element set"); // read the quantity details var quantity = readQuantity(Utils.findChildNode(node, "Quantity")); item.Quantity = quantity; items.Add(item); } } return items; }
public void Initialize(System.Collections.Hashtable properties) { double ox = 2.0; double oy = 2.0; double dx = 4.0; double dy = 4.0; // -- Populate Input Exchange Items --- Element element0 = new Element("element:0"); element0.AddVertex(new Vertex(ox ,oy ,0)); element0.AddVertex(new Vertex(ox+dx ,oy ,0)); element0.AddVertex(new Vertex(ox+dx ,oy+dy ,0)); element0.AddVertex(new Vertex(ox ,oy+dy ,0)); Element element1 = new Element("element:1"); element1.AddVertex(new Vertex(ox + dx ,oy ,0)); element1.AddVertex(new Vertex(ox+2*dx ,oy ,0)); element1.AddVertex(new Vertex(ox+2*dx ,oy+dy ,0)); element1.AddVertex(new Vertex(ox+dx ,oy+dy ,0)); Element element2 = new Element("element:2"); element2.AddVertex(new Vertex(ox ,oy+dy ,0)); element2.AddVertex(new Vertex(ox+dx ,oy+dy ,0)); element2.AddVertex(new Vertex(ox+dx ,oy+2*dy ,0)); element2.AddVertex(new Vertex(ox ,oy+2*dy ,0)); Element element3 = new Element("element:3"); element3.AddVertex(new Vertex(ox + dx ,oy+dy ,0)); element3.AddVertex(new Vertex(ox+2*dx ,oy+dy ,0)); element3.AddVertex(new Vertex(ox+2*dx ,oy+2*dy ,0)); element3.AddVertex(new Vertex(ox+dx ,oy+2*dy ,0)); ElementSet elementSet = new ElementSet("RegularGrid","RegularGrid",ElementType.XYPolygon,new SpatialReference(" ")); elementSet.AddElement(element0); elementSet.AddElement(element1); elementSet.AddElement(element2); elementSet.AddElement(element3); Quantity storageQuantity = new Quantity(new Unit("Storage",1.0,0.0,"Storage"),"Storage","Storage",global::OpenMI.Standard.ValueType.Scalar,new Dimension()); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.ElementSet = elementSet; inputExchangeItem.Quantity = storageQuantity; _inputExchangeItems.Add(inputExchangeItem); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.ElementSet = elementSet; outputExchangeItem.Quantity = storageQuantity; _outputExchangeItems.Add(outputExchangeItem); }
public void GetValues_AsAcceptor() { filename = "HydroNumerics.Time.OpenMI.UnitTest.LinkableTimeSeriesGroupTest.GetValues_AsAcceptor.xts"; string acceptorOutputFilename = "HydroNumerics.Time.OpenMI.UnitTest.LinkableTimeSeriesGroupTest.GetValues_AsAcceptor.out.xts"; TimespanSeries timespanSeries = new TimespanSeries("Flow", new System.DateTime(2010, 1, 1), 10, 2, TimestepUnit.Days, 10.2); timespanSeries.Unit = new HydroNumerics.Core.Unit("Liters pr. sec", 0.001, 0.0, "Liters pr second"); timespanSeries.Unit.Dimension.Length = 3; timespanSeries.Unit.Dimension.Time = -1; timespanSeries.Description = "Measured Flow"; TimestampSeries timestampSeries = new TimestampSeries("Water Level", new System.DateTime(2010, 1, 1), 6, 2, TimestepUnit.Days, 12.2); timestampSeries.Unit = new HydroNumerics.Core.Unit("cm", 0.01, 0.0, "centimeters"); timestampSeries.Unit.Dimension.Length = 1; timestampSeries.Description = "Measured Head"; TimeSeriesGroup tsg = new TimeSeriesGroup(); tsg.Name = "Acceptor"; tsg.Items.Add(timespanSeries); tsg.Items.Add(timestampSeries); tsg.Save(filename); Argument filenameArgument = new Argument("Filename", filename, true, "someDescription"); Argument outputFilenameArgument = new Argument("OutputFilename", acceptorOutputFilename, true, "someDescription"); Argument[] acceptorArguments = new Argument[2] { filenameArgument, outputFilenameArgument }; LinkableTimeSeriesGroup acceptorTs = new LinkableTimeSeriesGroup(); acceptorTs.Initialize(acceptorArguments); acceptorTs.WriteOmiFile(filename); LinkableTimeSeriesGroup linkableTimeSeriesGroup = new LinkableTimeSeriesGroup(); linkableTimeSeriesGroup.Initialize(arguments); Link ts2tsLink1 = new Link(); ts2tsLink1.SourceComponent = linkableTimeSeriesGroup; ts2tsLink1.TargetComponent = acceptorTs; ts2tsLink1.SourceQuantity = linkableTimeSeriesGroup.GetOutputExchangeItem(0).Quantity; ts2tsLink1.SourceElementSet = linkableTimeSeriesGroup.GetOutputExchangeItem(0).ElementSet; ts2tsLink1.TargetQuantity = acceptorTs.GetInputExchangeItem(0).Quantity; ts2tsLink1.TargetElementSet = acceptorTs.GetInputExchangeItem(0).ElementSet; ts2tsLink1.ID = "ts2ts1"; linkableTimeSeriesGroup.AddLink(ts2tsLink1); acceptorTs.AddLink(ts2tsLink1); Link ts2tsLink2 = new Link(); ts2tsLink2.SourceComponent = linkableTimeSeriesGroup; ts2tsLink2.TargetComponent = acceptorTs; ts2tsLink2.SourceQuantity = linkableTimeSeriesGroup.GetOutputExchangeItem(1).Quantity; ts2tsLink2.SourceElementSet = linkableTimeSeriesGroup.GetOutputExchangeItem(1).ElementSet; ts2tsLink2.TargetQuantity = acceptorTs.GetInputExchangeItem(1).Quantity; ts2tsLink2.TargetElementSet = acceptorTs.GetInputExchangeItem(1).ElementSet; ts2tsLink2.ID = "ts2ts2"; linkableTimeSeriesGroup.AddLink(ts2tsLink2); acceptorTs.AddLink(ts2tsLink2); //setting up the work arround type of trigger InputExchangeItem targetExchangeItem = new InputExchangeItem(); Quantity targetQuantity = new Quantity(); targetQuantity.ID = "Water Level"; targetQuantity.Unit = new HydroNumerics.OpenMI.Sdk.Backbone.Unit("meter", 1, 0, "meter"); ElementSet targetElementSet = new ElementSet("inputLocation", "Location", ElementType.IDBased, new SpatialReference("")); Link triggerLink = new Link(); triggerLink.SourceComponent = acceptorTs; triggerLink.TargetComponent = null; triggerLink.SourceQuantity = acceptorTs.GetOutputExchangeItem(0).Quantity; triggerLink.SourceElementSet = acceptorTs.GetOutputExchangeItem(0).ElementSet; triggerLink.TargetQuantity = targetQuantity; triggerLink.TargetElementSet = targetElementSet; triggerLink.ID = "TriggerLink"; acceptorTs.AddLink(triggerLink); TimespanSeries tss1 = (TimespanSeries)acceptorTs.TimeSeriesGroup.Items[0]; TimestampSeries tss2 = (TimestampSeries)acceptorTs.TimeSeriesGroup.Items[1]; Assert.AreEqual(10.2, tss1.Items[0].Value); Assert.AreEqual(12.2, tss2.Items[0].Value); acceptorTs.GetValues(new TimeStamp(new System.DateTime(2010, 1, 3)), triggerLink.ID); Assert.AreEqual(4.3, tss1.Items[0].Value); Assert.AreEqual(6.3, tss2.Items[0].Value); linkableTimeSeriesGroup.Finish(); //save file acceptorTs.Finish(); //save file }
public void Initialize(System.Collections.Hashtable properties) { //List of exchange Items inputExchangeItems = new List<InputExchangeItem>(); outputExchangeItems = new List<OutputExchangeItem>(); //Initializes Engine MohidWaterEngine = new MohidWaterEngineDotNetAccess(); MohidWaterEngine.Initialize(properties["FilePath"].ToString()); // //Dimensions // Dimension dimFlow = new Dimension(); dimFlow.SetPower(DimensionBase.Length, 3); dimFlow.SetPower(DimensionBase.Time, -1); Dimension dimWaterlevel = new Dimension(); dimWaterlevel.SetPower(DimensionBase.Length, 1); Dimension dimConcentration = new Dimension(); dimConcentration.SetPower(DimensionBase.Mass, 1); dimConcentration.SetPower(DimensionBase.Length, -3); // //Units // Unit unitFlow = new Unit("m3/sec", 1, 0, "cubic meter per second"); Unit unitWaterLevel = new Unit("m", 1, 0, "sea water level"); Unit unitConcentration = new Unit("mg/l", 1, 0, "miligram per liter"); // //Quantities // qtdDischargeFlow = new Quantity(unitFlow, "Input Discharge Flow", "Discharge Flow", global::OpenMI.Standard.ValueType.Scalar, dimFlow); qtdWaterLevel = new Quantity(unitWaterLevel, "Waterlevel of the water surface", "Waterlevel", global::OpenMI.Standard.ValueType.Scalar, dimWaterlevel); // //Spatial Reference // SpatialReference spatialReference = new SpatialReference("spatial reference"); // //Element Sets // //Model Grid ElementSet modelGrid = new ElementSet("Model Grid Points of all Compute Points", "Model Grid", ElementType.XYPolygon, spatialReference); //Output exchange items - properties in each grid cell (surface only) numberOfWaterPoints = 0; for (int i = 1; i <= MohidWaterEngine.GetIUB(horizontalGridInstanceID); i++) { for (int j = 1; j <= MohidWaterEngine.GetJUB(horizontalGridInstanceID); j++) { if (MohidWaterEngine.IsWaterPoint(horizontalMapInstanceID, i, j)) { String name = "i=" + i.ToString() + "/j=" + j.ToString(); double[] xCoords = new double[5]; double[] yCoords = new double[5]; MohidWaterEngine.GetGridCellCoordinates(horizontalGridInstanceID, i, j, ref xCoords, ref yCoords); Element element = new Element(name); element.AddVertex(new Vertex(xCoords[0], yCoords[0], 0)); element.AddVertex(new Vertex(xCoords[1], yCoords[1], 0)); element.AddVertex(new Vertex(xCoords[2], yCoords[2], 0)); element.AddVertex(new Vertex(xCoords[3], yCoords[3], 0)); modelGrid.AddElement(element); numberOfWaterPoints++; } } } //allocates waterlevels1D modelGridValues1D = new double[numberOfWaterPoints]; //Discharge Points ElementSet dischargePoints = new ElementSet("Discharge Points", "Discharge Points", ElementType.XYPoint, spatialReference); //Flow input exchange to discharges configured as OpenMI Discharges for (int i = 1; i <= MohidWaterEngine.GetNumberOfDischarges(dischargeInstanceID); i++) { if (MohidWaterEngine.GetDischargeType(dischargeInstanceID, i) == 4) { Element dischargeElement = new Element(MohidWaterEngine.GetDischargeName(dischargeInstanceID, i)); dischargeElement.AddVertex( new Vertex(MohidWaterEngine.GetDischargeXCoordinate(dischargeInstanceID, i), MohidWaterEngine.GetDischargeYCoordinate(dischargeInstanceID, i), 0)); dischargePoints.AddElement(dischargeElement); } } // //Output Exchange Items // //Water Level of the Hydrodynamic model OutputExchangeItem waterlevel = new OutputExchangeItem(); waterlevel.Quantity = qtdWaterLevel; waterlevel.ElementSet = modelGrid; outputExchangeItems.Add(waterlevel); //Properties of the Water properties model for (int idx = 1; idx <= MohidWaterEngine.GetNumberOfProperties(waterPropertiesInstanceID); idx++) { int propertyID = MohidWaterEngine.GetPropertyIDNumber(waterPropertiesInstanceID, idx); string propertyName = MohidWaterEngine.GetPropertyNameByIDNumber(propertyID); Quantity concentrationQuantity = new Quantity(unitConcentration, "Concentration of " + propertyName, propertyID.ToString(), ValueType.Scalar, dimConcentration); qtdProperties.Add(concentrationQuantity); OutputExchangeItem concExchangeItem = new OutputExchangeItem(); concExchangeItem.Quantity = concentrationQuantity; concExchangeItem.ElementSet = modelGrid; outputExchangeItems.Add(concExchangeItem); } //Flow input exchange to discharges configured as OpenMI Discharges for (int i = 1; i <= MohidWaterEngine.GetNumberOfDischarges(dischargeInstanceID); i++) { if (MohidWaterEngine.GetDischargeType(dischargeInstanceID, i) == 4) { String pointName = MohidWaterEngine.GetDischargeName(dischargeInstanceID, i); ElementSet dischargePoint = new ElementSet("Discharge Point of MOHID Water", i.ToString(), ElementType.XYPoint, spatialReference); InputExchangeItem inputDischarge = new InputExchangeItem(); inputDischarge.Quantity = qtdDischargeFlow; Element element = new Element("Point: " + pointName); element.AddVertex(new Vertex(MohidWaterEngine.GetDischargeXCoordinate(dischargeInstanceID, i), MohidWaterEngine.GetDischargeYCoordinate(dischargeInstanceID, i), 0)); dischargePoint.AddElement(element); inputDischarge.ElementSet = dischargePoint; inputExchangeItems.Add(inputDischarge); for (int idx = 1; idx <= MohidWaterEngine.GetNumberOfDischargeProperties(dischargeInstanceID, i); idx++) { int propertyID = MohidWaterEngine.GetDischargePropertyID(dischargeInstanceID, i, idx); string propertyName = MohidWaterEngine.GetPropertyNameByIDNumber(propertyID); Quantity concentrationQuantity = new Quantity(unitConcentration, propertyName, propertyID.ToString(), global::OpenMI.Standard.ValueType.Scalar, dimConcentration); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.ElementSet = dischargePoint; inputExchangeItem.Quantity = concentrationQuantity; inputExchangeItems.Add(inputExchangeItem); } } } }
//part of System.Collections public void Initialize(Hashtable properties) { _inputExchangeItems = new ArrayList(); _outputExchangeItems = new ArrayList(); _elementSets = new Hashtable(); _elementScopes = new Hashtable(); FilePath = ((string)properties["FilePath"]); InitializeDaisy((string)properties["FilePath"]); ModelDescription = ((string)GetDescription()); for (int i = 0; i < _daisyEngine.ScopeSize(); i++) { Scope scope = _daisyEngine.GetScope(i); // Attribut column? if (!scope.HasString("column")) continue; // Create element. string columnID = scope.String("column"); Element element = new Element (columnID); _elementScopes[element] = scope; if (_daisyEngine.HasColumn(columnID)) { Column column = _daisyEngine.GetColumn(columnID); for (uint ii = 0; ii < column.LocationSize(); ii++) { double x = column.LocationX(ii); double y = column.LocationY(ii); double z = 0.0; element.AddVertex(new Vertex(x, y, z)); } } // Add exchange items. for (uint j = 0; j < scope.NumberSize(); j++) { string name = scope.NumberName(j); ElementSet elementSet; // Find or create element set. if (_elementSets.Contains(name)) { elementSet = (ElementSet)_elementSets[name]; elementSet.Description += " " + columnID; // TODO: We should test the type matches here. } else { switch (element.VertexCount) { case 0: // ID based elementSet = new ElementSet(columnID, name, ElementType.XYPoint, new SpatialReference("")); break; case 1: // Point based elementSet = new ElementSet(columnID, name, ElementType.XYPoint, new SpatialReference("")); break; case 2: // Error throw new ApplicationException("Error: Column must not contain exactly two (X Y)-points!"); default: // Polygon elementSet = new ElementSet(columnID, name, ElementType.XYPolygon, new SpatialReference("")); break; } _elementSets[name] = elementSet; string dim = scope.Dimension(name); string description = scope.Description(name); Quantity quantity = Quantity(dim, description, name); if (scope.Writeable()) { InputExchangeItem input = new InputExchangeItem(); input.Quantity = quantity; input.ElementSet = elementSet; _inputExchangeItems.Add(input); } else { OutputExchangeItem output = new OutputExchangeItem(); output.Quantity = quantity; output.ElementSet = elementSet; _outputExchangeItems.Add(output); } } // Add it. elementSet.AddElement(element); } } }
private void CreateExchangeItemsFromXMLNode(XmlNode ExchangeItem, string Identifier) { //Create Dimensions var omiDimensions = new Dimension(); var dimensions = ExchangeItem.SelectNodes("//Dimensions/Dimension"); // You can filter elements here using XPath if (dimensions != null) { foreach (XmlNode dimension in dimensions) { if (dimension["Base"].InnerText == "Length") { omiDimensions.SetPower(DimensionBase.Length, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "Time") { omiDimensions.SetPower(DimensionBase.Time, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "AmountOfSubstance") { omiDimensions.SetPower(DimensionBase.AmountOfSubstance, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "Currency") { omiDimensions.SetPower(DimensionBase.Currency, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "ElectricCurrent") { omiDimensions.SetPower(DimensionBase.ElectricCurrent, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "LuminousIntensity") { omiDimensions.SetPower(DimensionBase.LuminousIntensity, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "Mass") { omiDimensions.SetPower(DimensionBase.Mass, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "Temperature") { omiDimensions.SetPower(DimensionBase.Temperature, Convert.ToDouble(dimension["Power"].InnerText)); } } } //Create Units _omiUnits = new Unit(); var units = ExchangeItem.SelectSingleNode("Quantity/Unit"); if (units != null) { _omiUnits.ID = units["ID"].InnerText; if (units["Description"] != null) _omiUnits.Description = units["Description"].InnerText; if (units["ConversionFactorToSI"] != null) _omiUnits.ConversionFactorToSI = Convert.ToDouble(units["ConversionFactorToSI"].InnerText); if (units["OffSetToSI"] != null) _omiUnits.OffSetToSI = Convert.ToDouble(units["OffSetToSI"].InnerText); } //Create Quantity var omiQuantity = new Quantity(); var quantity = ExchangeItem.SelectSingleNode("Quantity"); omiQuantity.ID = quantity["ID"].InnerText; if (quantity["Description"] != null) omiQuantity.Description = quantity["Description"].InnerText; omiQuantity.Dimension = omiDimensions; omiQuantity.Unit = _omiUnits; omiQuantity.ValueType = ValueType.Scalar; if (quantity["ValueType"] != null) { if (quantity["ValueType"].InnerText == "Scalar") { omiQuantity.ValueType = ValueType.Scalar; } else if (quantity["ValueType"].InnerText == "Vector") { omiQuantity.ValueType = ValueType.Vector; } } //Create Element Set var omiElementSet = new ElementSet(); var elementSet = ExchangeItem.SelectSingleNode("ElementSet"); omiElementSet.ID = elementSet["ID"].InnerText; if (elementSet["Description"] != null) omiElementSet.Description = elementSet["Description"].InnerText; try { //add elements from shapefile to element set var utils = new Utilities(); _shapefilepath = elementSet["ShapefilePath"].InnerText; omiElementSet = utils.AddElementsFromShapefile(omiElementSet, _shapefilepath); } catch (Exception) { Debug.WriteLine("An Element Set has not been declared using AddElementsFromShapefile"); } try { // add elements from xml file to element set var utils = new Utilities(); _xmlFilePath = elementSet["XmlFilePath"].InnerText; omiElementSet = utils.AddElementsFromXmlFile(omiElementSet, _xmlFilePath); } catch (Exception) { Debug.WriteLine("An Element Set has not been declared using AddElementsFromXmlFile"); } if (Identifier == "OutputExchangeItem") { //create exchange item var omiOutputExchangeItem = new OutputExchangeItem(); omiOutputExchangeItem.Quantity = omiQuantity; omiOutputExchangeItem.ElementSet = omiElementSet; //add the output exchange item to the list of output exchange items for the component _outputs.Add(omiOutputExchangeItem); if (!_quantities.ContainsKey(omiQuantity.ID)) _quantities.Add(omiQuantity.ID, omiQuantity); if (!_elementSets.ContainsKey(omiElementSet.ID)) _elementSets.Add(omiElementSet.ID, omiElementSet); } else if (Identifier == "InputExchangeItem") { //create exchange item var omiInputExchangeItem = new InputExchangeItem(); omiInputExchangeItem.Quantity = omiQuantity; omiInputExchangeItem.ElementSet = omiElementSet; //add the output exchange item to the list of output exchange items for the component _inputs.Add(omiInputExchangeItem); if (!_quantities.ContainsKey(omiQuantity.ID)) _quantities.Add(omiQuantity.ID, omiQuantity); if (!_elementSets.ContainsKey(omiElementSet.ID)) _elementSets.Add(omiElementSet.ID, omiElementSet); } }
public void Initialize(System.Collections.Hashtable properties) { getValuesWatch = new Stopwatch(); setValuesWatch = new Stopwatch(); performStepWatch = new Stopwatch(); //List of exchange Items inputExchangeItems = new List<InputExchangeItem>(); outputExchangeItems = new List<OutputExchangeItem>(); //Initializes Engine mohidLandEngine = new MohidLandEngineDotNetAccess(); mohidLandEngine.Initialize(properties["FilePath"].ToString()); // //Dimensions // Dimension dimFlow = new Dimension(); dimFlow.SetPower(DimensionBase.Length, 3); dimFlow.SetPower(DimensionBase.Time, -1); Dimension dimWaterlevel = new Dimension(); dimWaterlevel.SetPower(DimensionBase.Length, 1); Dimension dimWaterColumn = new Dimension(); dimWaterColumn.SetPower(DimensionBase.Length, 1); Dimension dimConcentration = new Dimension(); dimConcentration.SetPower(DimensionBase.Mass, 1); dimConcentration.SetPower(DimensionBase.Length, -3); // //Units // Unit unitFlow = new Unit("m3/sec", 1, 0, "cubic meter per second"); Unit unitWaterLevel = new Unit("m", 1, 0, "meters above mean sea level"); Unit unitWaterColumn = new Unit("m", 1, 0, "meters above ground"); Unit unitConcentration = new Unit("mg/l", 1, 0, "miligram per liter"); // //Quantities // qtdOutflow = new Quantity(unitFlow, "Flow discharge at the outlet", "Outlet Flow", ValueType.Scalar, dimFlow); qtdOutletLevel = new Quantity(unitWaterLevel, "Waterlevel at the outlet", "OutletLevel", ValueType.Scalar, dimWaterlevel); qtdWaterColumn = new Quantity(unitWaterColumn, "Ponded Water Column", "WaterColumn", ValueType.Scalar, dimWaterColumn); qtdDischarges = new Quantity(unitFlow, "Distributed discharges (sewer sinks)", "Discharges", ValueType.Scalar, dimFlow); qtdFlowToStorm = new Quantity(unitFlow, "Flow from the network to the storm water system (inlets)", "Storm Water Out Flow", ValueType.Scalar, dimFlow); qtdFlowFromStrom = new Quantity(unitFlow, "Flow from the storm water system to the network (discharges)", "Storm Water In Flow", ValueType.Scalar, dimFlow); // //Spatial Reference // SpatialReference spatialReference = new SpatialReference("spatial reference"); // //Element Sets // //Model Grid ElementSet modelGrid = new ElementSet("Model Grid Points of all Compute Points", "Model Grid", ElementType.XYPolygon, spatialReference); //Output exchange items - properties in each grid cell (surface only) numberOfWaterPoints = 0; for (int j = 1; j <= mohidLandEngine.GetJUB(horizontalGridInstanceID); j++) { for (int i = 1; i <= mohidLandEngine.GetIUB(horizontalGridInstanceID); i++) { if (mohidLandEngine.IsWaterPoint(horizontalMapInstanceID, i, j)) { String name = "i=" + i.ToString() + "/j=" + j.ToString(); double[] xCoords = new double[5]; double[] yCoords = new double[5]; mohidLandEngine.GetGridCellCoordinates(horizontalGridInstanceID, i, j, ref xCoords, ref yCoords); Element element = new Element(name); element.AddVertex(new Vertex(xCoords[0], yCoords[0], 0)); element.AddVertex(new Vertex(xCoords[1], yCoords[1], 0)); element.AddVertex(new Vertex(xCoords[2], yCoords[2], 0)); element.AddVertex(new Vertex(xCoords[3], yCoords[3], 0)); modelGrid.AddElement(element); numberOfWaterPoints++; } } } //Outlet Node ElementSet outletNode = new ElementSet("Outlet node", "Outlet", ElementType.XYPoint, spatialReference); Element outletElement = new Element("Outlet"); int outletNodeID = mohidLandEngine.GetOutletNodeID(drainageNetworkInstanceID); outletElement.AddVertex(new Vertex(mohidLandEngine.GetXCoordinate(drainageNetworkInstanceID, outletNodeID), mohidLandEngine.GetYCoordinate(drainageNetworkInstanceID, outletNodeID), 0)); outletNode.AddElement(outletElement); //Outflow to Storm Water Model ElementSet stormWaterOutflowNodes = new ElementSet("Nodes which provide flow to the Storm Water System", "Storm Water Inlets", ElementType.XYPoint, spatialReference); int numberOfOutflowNodes = mohidLandEngine.GetNumberOfStormWaterOutFlowNodes(drainageNetworkInstanceID); int[] outflowNodeIDs = new int[numberOfOutflowNodes]; mohidLandEngine.GetStormWaterOutflowIDs(drainageNetworkInstanceID, numberOfOutflowNodes, ref outflowNodeIDs); for (int i = 1; i <= numberOfOutflowNodes; i++) { int nodeID = outflowNodeIDs[i - 1]; Element element = new Element(nodeID.ToString()); element.AddVertex(new Vertex(mohidLandEngine.GetXCoordinate(drainageNetworkInstanceID, nodeID), mohidLandEngine.GetYCoordinate(drainageNetworkInstanceID, nodeID), 0)); stormWaterOutflowNodes.AddElement(element); } //Inflow from Storm Water Model ElementSet stormWaterInflowNodes = new ElementSet("Nodes which receive flow to the Storm Water System", "Storm Water Outlets", ElementType.XYPoint, spatialReference); int numberOfInflowNodes = mohidLandEngine.GetNumberOfStormWaterInFlowNodes(drainageNetworkInstanceID); if (numberOfInflowNodes > 0) { int[] inflowNodeIDs = new int[numberOfInflowNodes]; mohidLandEngine.GetStormWaterInflowIDs(drainageNetworkInstanceID, numberOfOutflowNodes, ref inflowNodeIDs); for (int i = 1; i <= numberOfInflowNodes; i++) { int nodeID = inflowNodeIDs[i - 1]; Element element = new Element(nodeID.ToString()); element.AddVertex(new Vertex(mohidLandEngine.GetXCoordinate(drainageNetworkInstanceID, nodeID), mohidLandEngine.GetYCoordinate(drainageNetworkInstanceID, nodeID), 0)); stormWaterInflowNodes.AddElement(element); } } // //Output Exchange Items // //Flow at the outlet OutputExchangeItem outletFlow = new OutputExchangeItem(); outletFlow.Quantity = qtdOutflow; outletFlow.ElementSet = outletNode; outputExchangeItems.Add(outletFlow); //Overland water column OutputExchangeItem overlandWaterColumn = new OutputExchangeItem(); overlandWaterColumn.Quantity = qtdWaterColumn; overlandWaterColumn.ElementSet = modelGrid; outputExchangeItems.Add(overlandWaterColumn); //Flow to the Storm Water Model if (stormWaterOutflowNodes.ElementCount > 0) { OutputExchangeItem stormWaterOutFlow = new OutputExchangeItem(); stormWaterOutFlow.Quantity = qtdFlowToStorm; stormWaterOutFlow.ElementSet = stormWaterOutflowNodes; outputExchangeItems.Add(stormWaterOutFlow); } // //Input Exchange Items // //Water level at the outlet InputExchangeItem outletLevel = new InputExchangeItem(); outletLevel.Quantity = qtdOutletLevel; outletLevel.ElementSet = outletNode; inputExchangeItems.Add(outletLevel); //Distributed discharges InputExchangeItem dischargeInflow = new InputExchangeItem(); dischargeInflow.Quantity = qtdDischarges; dischargeInflow.ElementSet = modelGrid; inputExchangeItems.Add(dischargeInflow); //Flow from the Storm Water Model if (stormWaterInflowNodes.ElementCount > 0) { InputExchangeItem stormWaterInFlow = new InputExchangeItem(); stormWaterInFlow.Quantity = qtdFlowFromStrom; stormWaterInFlow.ElementSet = stormWaterInflowNodes; inputExchangeItems.Add(stormWaterInFlow); } // //Properties // //Properties input / output exchange items for (int i = 1; i <= mohidLandEngine.GetNumberOfProperties(drainageNetworkInstanceID); i++) { int propertyIDNumber = mohidLandEngine.GetPropertyIDNumber(drainageNetworkInstanceID, i); string propertyName = mohidLandEngine.GetPropertyNameByIDNumber(propertyIDNumber); Quantity concentrationQuantity = new Quantity(unitConcentration, "Concentration of " + propertyName, propertyIDNumber.ToString(), ValueType.Scalar, dimConcentration); OutputExchangeItem outletConc = new OutputExchangeItem(); outletConc.Quantity = concentrationQuantity; outletConc.ElementSet = outletNode; outputExchangeItems.Add(outletConc); InputExchangeItem boundaryConc = new InputExchangeItem(); boundaryConc.Quantity = concentrationQuantity; boundaryConc.ElementSet = outletNode; inputExchangeItems.Add(boundaryConc); } }
public void SetValues(InputExchangeItem input, double[] values) { //IronPython.Runtime.PythonDictionary dict = new IronPython.Runtime.PythonDictionary(); //for (int i = 0; i < values.Length; i++) // dict.Add(input.ElementSet.GetElementID(i), values[i]); SetValuesFunc(input.Quantity.ID, values); }
public void Initialize(System.Collections.Hashtable properties) { _dt = 1.0; _dx = 0.0; _initialValue = 100; if (properties.ContainsKey("modelID")) { _modelID = (string) properties["ModelID"]; } if (properties.ContainsKey("dt")) { _dt = (double) properties["dt"]; } if (properties.ContainsKey("dx")) { _dx = (double) properties["dx"]; } _values = new double[3]; for (int i = 0; i < _values.Length; i++) { _values[i] = _initialValue; } _startTime = 4000; _currentTime = _startTime; Element element = new Element("ElementID"); ElementSet elementSet = new ElementSet("Description","ID",ElementType.IDBased,new SpatialReference(" no ")); elementSet.AddElement(element); Quantity quantity = new Quantity(new Unit("Flow",1,0,"flow"),"Flow","ID",global::OpenMI.Standard.ValueType.Scalar,new Dimension()); _outputExchangeItem = new OutputExchangeItem(); _inputExchangeItem = new InputExchangeItem(); _outputExchangeItem.Quantity = quantity; _outputExchangeItem.ElementSet = elementSet; _inputExchangeItem.Quantity = quantity; _inputExchangeItem.ElementSet = elementSet; }
/// <summary> /// Runs a test of basic functionality on a language adapter. /// </summary> /// <param name="adapter"></param> private void RunTest(ILanguageAdapter adapter) { // create holders for our exchange items List<InputExchangeItem> _inputs = new List<InputExchangeItem>(); List<OutputExchangeItem> _outputs = new List<OutputExchangeItem>(); // read the element sets from the xml file List<XmlElementSet> elementSets = XmlElementSet.Read(@"..\..\Data\ElementSets.xml"); // create an input exchange item InputExchangeItem inItem = new InputExchangeItem(); inItem.Quantity = new Quantity("initem"); inItem.ElementSet = elementSets[0]; _inputs.Add(inItem); // create some fake input data double[] values = new double[inItem.ElementSet.ElementCount]; for (int i = 0; i < values.Length; i++) values[i] = 1.0; // create an output exchange item OutputExchangeItem outItem = new OutputExchangeItem(); outItem.Quantity = new Quantity("outitem"); outItem.ElementSet = elementSets[0]; _outputs.Add(outItem); // fake some times DateTime startTime = new DateTime(1982, 01, 01, 00, 00, 00); double timeStep = 3600; DateTime currentTime = startTime; // call initialize adapter.Start(_inputs, _outputs, startTime, timeStep); // set some values and perform a time step adapter.SetValues(inItem, values); adapter.PerformTimeStep(currentTime); currentTime = currentTime.AddSeconds(timeStep); // get some values and change them values = adapter.GetValues(outItem); for (int i = 0; i < values.Length; i++) values[i] += 0.1; // set some values and perform a time step adapter.SetValues(inItem, values); adapter.PerformTimeStep(currentTime); currentTime = currentTime.AddSeconds(timeStep); // get some values and change them values = adapter.GetValues(outItem); for (int i = 0; i < values.Length; i++) values[i] += 0.1; // set some values and perform a time step adapter.SetValues(inItem, values); adapter.PerformTimeStep(currentTime); currentTime = currentTime.AddSeconds(timeStep); // call finish adapter.Stop(); }
public void Initialize(System.Collections.Hashtable properties) { currentTimestep = 0; simulationStart = new DateTime(2001,1,1); dt = 172800; //timestep length (2 days) nt = 80; // number of timesteps nx = 2; //number of grid cells in x-direction ny = 2; //number of grid cells in y-direction grid = new RegularGrid(10, 10, 1000, nx, ny, 0); groundwaterHeads = new TimeSeriesGroup(); infiltrations = new TimeSeriesGroup(); for (int i = 0; i < nx * ny; i++) { groundwaterHeads.Items.Add(new TimestampSeries("GwHead" + i.ToString(), simulationStart, nt, dt, TimestepUnit.Seconds, 4.9, new HydroNumerics.Core.Unit("meters",1.0,0.0))); infiltrations.Items.Add(new TimestampSeries("Infiltration" + i.ToString(), simulationStart, nt, dt, TimestepUnit.Seconds, -9999.9999, new HydroNumerics.Core.Unit("flow",1.0,0.0))); } Quantity infiltQuantity = new Quantity(); infiltQuantity.Unit = new HydroNumerics.OpenMI.Sdk.Backbone.Unit("level", 1.0,0.0); infiltQuantity.ID = "Infiltration"; infiltQuantity.Description = "infiltration"; infiltQuantity.ValueType = global::OpenMI.Standard.ValueType.Scalar; InputExchangeItem infiltExItem = new InputExchangeItem(); infiltExItem.Quantity = infiltQuantity; infiltExItem.ElementSet = grid; inputExchangeItems = new List<InputExchangeItem>(); inputExchangeItems.Add(infiltExItem); Quantity headQuantity = new Quantity(); headQuantity.Description = "Groundwater head"; headQuantity.ID = "Head"; headQuantity.Unit = new HydroNumerics.OpenMI.Sdk.Backbone.Unit("meters",1,0); headQuantity.ValueType = global::OpenMI.Standard.ValueType.Scalar; OutputExchangeItem headOutItem = new OutputExchangeItem(); headOutItem.Quantity = headQuantity; headOutItem.ElementSet = grid; outputExchangeItems = new List<OutputExchangeItem>(); outputExchangeItems.Add(headOutItem); }
/// <summary> /// Used to Initialize the component. Performs routines that must be completed prior to simulation start. /// </summary> /// <param name="properties">properties extracted from the components *.omi file</param> public override void Initialize(System.Collections.Hashtable properties) { //--- GET MODEL ATTRIBUTES FROM SMW --- string config = null; //set the config path and output directory from the *.omi file. foreach (DictionaryEntry p in properties) { if (p.Key.ToString() == "ConfigFile") { config = (string)properties["ConfigFile"]; } else if (p.Key.ToString() == "OutDir") { _outDir = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), (string)properties["OutDir"]); } } //lookup model's configuration file to determine interface properties SetVariablesFromConfigFile(config); SetValuesTableFields(); //input exchange item attributes int num_inputs = this.GetInputExchangeItemCount(); InputExchangeItem input = this.GetInputExchangeItem(num_inputs - 1); input_elementset = input.ElementSet.ID; input_quantity = input.Quantity.ID; //output exchange item attributes int num_outputs = this.GetOutputExchangeItemCount(); OutputExchangeItem output = this.GetOutputExchangeItem(num_outputs - 1); output_elementset = output.ElementSet.ID; output_quantity = output.Quantity.ID; //timehorizon attributes ITimeSpan time_horizon = this.GetTimeHorizon(); string start = CalendarConverter.ModifiedJulian2Gregorian(time_horizon.Start.ModifiedJulianDay).ToString(); string end = CalendarConverter.ModifiedJulian2Gregorian(time_horizon.End.ModifiedJulianDay).ToString(); //get shapefile path string shapefilePath = this.GetShapefilePath(); //get timestep string timestep = this.GetTimeStep().ToString(); _ts = Convert.ToDouble(timestep); //this uses the free SharpMap API for reading a shapefile VectorLayer myLayer = new VectorLayer("elements_layer"); myLayer.DataSource = new ShapeFile(shapefilePath); myLayer.DataSource.Open(); //initialize array to hold the transformed inflow values int size = myLayer.DataSource.GetFeatureCount(); transformedInflow = new double[size]; //--- BUILD NETWORK --- // loop through all features in feature class for (uint i = 0; i < myLayer.DataSource.GetFeatureCount(); ++i) { FeatureDataRow feat = myLayer.DataSource.GetFeature(i); //This routine, ensures that the reaches are added to the XML stream such that the the elements // align with the subwatersheds.shp. In order to do this I had to assign ArcID's that match the // corresponding Subwatershed.shp elements. //bool IsCorrect = false; //uint j = 0; //while (!IsCorrect) //{ // feat = myLayer.DataSource.GetFeature(j); // if (feat.ItemArray[feat.Table.Columns.IndexOf("GridID")].ToString() == (i + 1).ToString()) // IsCorrect = true; // else // j++; //} string to_comid = feat.ItemArray[feat.Table.Columns.IndexOf("TO_NODE")].ToString(); string from_comid = feat.ItemArray[feat.Table.Columns.IndexOf("FROM_NODE")].ToString(); string k = feat.ItemArray[feat.Table.Columns.IndexOf("K")].ToString(); string x = feat.ItemArray[feat.Table.Columns.IndexOf("X")].ToString(); string id = feat.ItemArray[feat.Table.Columns.IndexOf("GridID")].ToString(); Int64 v1 = Convert.ToInt64(from_comid); Int64 v2 = Convert.ToInt64(to_comid); g.AddVertex(v1); g.AddVertex(v2); var e1 = new TaggedEdge <Int64, Reach>(v1, v2, new Reach(Convert.ToInt64(id), Convert.ToDouble(x), Convert.ToDouble(k), Convert.ToDateTime(start), Convert.ToDouble(timestep))); g.AddEdge(e1); } //sort the graph topologically _topoSort = QuickGraph.Algorithms.AlgorithmExtensions.TopologicalSort <Int64, TaggedEdge <Int64, Reach> >(g); }
private IExchangeItem CreateExchangeItemsFromXMLNode(XmlNode ExchangeItem, string Identifier) { XmlNodeList dimensions = null; //get the Dimensions node by iterating through some nodes. foreach (XmlNode child in ExchangeItem.ChildNodes) { if (child.Name == "Quantity") { foreach (XmlNode node in child.ChildNodes) { if (node.Name == "Dimensions") { dimensions = node.ChildNodes; } } } } //Create Dimensions Dimension omiDimensions = new Dimension(); //XmlNodeList dimensions = ExchangeItem.SelectNodes("//Dimensions/Dimension"); // You can filter elements here using XPath foreach (XmlNode dimension in dimensions) { if (dimension["Base"].InnerText == "Length") { omiDimensions.SetPower(DimensionBase.Length, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "Time") { omiDimensions.SetPower(DimensionBase.Time, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "AmountOfSubstance") { omiDimensions.SetPower(DimensionBase.AmountOfSubstance, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "Currency") { omiDimensions.SetPower(DimensionBase.Currency, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "ElectricCurrent") { omiDimensions.SetPower(DimensionBase.ElectricCurrent, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "LuminousIntensity") { omiDimensions.SetPower(DimensionBase.LuminousIntensity, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "Mass") { omiDimensions.SetPower(DimensionBase.Mass, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "Temperature") { omiDimensions.SetPower(DimensionBase.Temperature, Convert.ToDouble(dimension["Power"].InnerText)); } } //Create Units Unit _omiUnits = new Unit(); XmlNode units = ExchangeItem.SelectSingleNode("Quantity/Unit"); _omiUnits.ID = units["ID"].InnerText; if (units["Description"] != null) { _omiUnits.Description = units["Description"].InnerText; } if (units["ConversionFactorToSI"] != null) { _omiUnits.ConversionFactorToSI = Convert.ToDouble(units["ConversionFactorToSI"].InnerText); } if (units["OffSetToSI"] != null) { _omiUnits.OffSetToSI = Convert.ToDouble(units["OffSetToSI"].InnerText); } //Create Quantity Quantity omiQuantity = new Quantity(); XmlNode quantity = ExchangeItem.SelectSingleNode("Quantity"); omiQuantity.ID = quantity["ID"].InnerText; if (quantity["Description"] != null) { omiQuantity.Description = quantity["Description"].InnerText; } omiQuantity.Dimension = omiDimensions; omiQuantity.Unit = _omiUnits; if (quantity["ValueType"] != null) { if (quantity["ValueType"].InnerText == "Scalar") { omiQuantity.ValueType = OpenMI.Standard.ValueType.Scalar; } else if (quantity["ValueType"].InnerText == "Vector") { omiQuantity.ValueType = OpenMI.Standard.ValueType.Vector; } } //Create Element Set ElementSet omiElementSet = new ElementSet(); XmlNode elementSet = ExchangeItem.SelectSingleNode("ElementSet"); omiElementSet.ID = elementSet["ID"].InnerText; if (elementSet["Description"] != null) { omiElementSet.Description = elementSet["Description"].InnerText; } try { //add elements from shapefile to element set string _shapefilepath = elementSet["ShapefilePath"].InnerText; omiElementSet = AddElementsFromShapefile(omiElementSet, _shapefilepath); } catch (Exception) { try { //add elements from shapefile to element set int numElements = Convert.ToInt32(elementSet["NumberOfElements"].InnerText); omiElementSet.ElementType = ElementType.IDBased; for (int i = 0; i <= numElements - 1; i++) { Element e = new Element(); Vertex v = new Vertex(); e.AddVertex(v); omiElementSet.AddElement(e); } } catch (Exception) { Debug.WriteLine("An Element Set has not been declared using AddElementsFromShapefile"); //make sure that all output exchange items have at least 1 element if (Identifier == "OutputExchangeItem") { //create at least one element omiElementSet.ElementType = ElementType.IDBased; Element e = new Element("Empty"); Vertex v = new Vertex(); e.AddVertex(v); omiElementSet.AddElement(e); } } } if (Identifier == "OutputExchangeItem") { //create exchange item OutputExchangeItem omiOutputExchangeItem = new OutputExchangeItem(); omiOutputExchangeItem.Quantity = omiQuantity; omiOutputExchangeItem.ElementSet = omiElementSet; return(omiOutputExchangeItem); //add the output exchange item to the list of output exchange items for the component //this._outputs.Add(omiOutputExchangeItem); //if (!this._quantities.ContainsKey(omiQuantity.ID)) this._quantities.Add(omiQuantity.ID, omiQuantity); //if (!this._elementSets.ContainsKey(omiElementSet.ID)) this._elementSets.Add(omiElementSet.ID, omiElementSet); } else if (Identifier == "InputExchangeItem") { //create exchange item InputExchangeItem omiInputExchangeItem = new InputExchangeItem(); omiInputExchangeItem.Quantity = omiQuantity; omiInputExchangeItem.ElementSet = omiElementSet; return(omiInputExchangeItem); //add the output exchange item to the list of output exchange items for the component //this._inputs.Add(omiInputExchangeItem); //if (!this._quantities.ContainsKey(omiQuantity.ID)) this._quantities.Add(omiQuantity.ID, omiQuantity); //if (!this._elementSets.ContainsKey(omiElementSet.ID)) this._elementSets.Add(omiElementSet.ID, omiElementSet); } else { throw new Exception(" \"" + Identifier + "\" is not a valid exchange item identifier"); } }
public IInputExchangeItem GetInputExchangeItem(int index) { // -- create a flow quanitity -- Dimension flowDimension = new Dimension(); flowDimension.SetPower(DimensionBase.Length, 3); flowDimension.SetPower(DimensionBase.Time, -1); Unit literPrSecUnit = new Unit("LiterPrSecond", 0.001, 0, "Liters pr Second"); Quantity flowQuantity = new Quantity(literPrSecUnit, "Flow", "Flow", global::OpenMI.Standard.ValueType.Scalar, flowDimension); Element element = new Element(); element.ID = "DummyElement"; ElementSet elementSet = new ElementSet("Dummy ElementSet", "DummyElementSet", ElementType.IDBased, new SpatialReference("no reference")); elementSet.AddElement(element); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.ElementSet = elementSet; inputExchangeItem.Quantity = flowQuantity; return inputExchangeItem; }
public override void Initialize(System.Collections.Hashtable properties) { string configFile = null; //set the config path and output directory from the *.omi file. foreach (DictionaryEntry p in properties) { if (p.Key.ToString() == "ConfigFile") { configFile = (string)properties["ConfigFile"]; } else if (p.Key.ToString() == "OutDir") { _outDir = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), (string)properties["OutDir"]); } } //lookup model's configuration file to determine interface properties SetVariablesFromConfigFile(configFile); SetValuesTableFields(); //setup elementValues DataTable to store element attributes elementValues.Columns.Add("Watershed"); elementValues.Columns.Add("CurveNumber"); elementValues.Columns.Add("cumInfil"); elementValues.Columns.Add("CumPrecip", typeof(double)); elementValues.Columns.Add("HyetoVal", typeof(double)); //get input exchange item attributes int num_inputs = this.GetInputExchangeItemCount(); InputExchangeItem input = this.GetInputExchangeItem(num_inputs - 1); input_elementset = input.ElementSet.ID; input_quantity = input.Quantity.ID; //get output exchange item attributes int num_outputs = this.GetOutputExchangeItemCount(); OutputExchangeItem output = this.GetOutputExchangeItem(num_outputs - 1); output_elementset = output.ElementSet.ID; output_quantity = output.Quantity.ID; // Get shapefile path from Config file XmlDocument doc = new XmlDocument(); doc.Load(configFile); XmlElement root = doc.DocumentElement; XmlNode elementSet = root.SelectSingleNode("//InputExchangeItem//ElementSet"); string shapefilePath = elementSet["ShapefilePath"].InnerText; //open the input shapefile VectorLayer myLayer = new VectorLayer("elements_layer"); //this uses the free SharpMap API for reading a shapefile myLayer.DataSource = new ShapeFile(shapefilePath); myLayer.DataSource.Open(); //get the number of features in the shapefile _featureCount = myLayer.DataSource.GetFeatureCount(); //add feature attributes from shapefile to datatable for (uint i = 0; i < myLayer.DataSource.GetFeatureCount(); ++i) { FeatureDataRow feat = myLayer.DataSource.GetFeature(i); DataTable att = feat.Table; object Watershed = feat.ItemArray[feat.Table.Columns.IndexOf("Watershed")]; object CN = feat.ItemArray[feat.Table.Columns.IndexOf("CN")]; elementValues.LoadDataRow(new object[] { Watershed, CN }, true); } //initialize PeArray_last to store the Pe from the previous timestep PeArray_last = new double[elementValues.Rows.Count]; for (int k = 0; k <= PeArray_last.Length - 1; k++) { PeArray_last[k] = 0.0; } ////intialize streamwriter to write output data. This is used in the Finish() method //writer = new System.IO.StreamWriter("../SCSAbstraction_output.csv"); }
public void SetValues(InputExchangeItem input, double[] values) { SetIDArray(input); Array a = values; Array i = new double[a.Length]; matlab.PutFullMatrix(GetValueArrayName(input), "base", a, i); matlab.Execute(GetValueArrayName(input) + " = " + GetValueArrayName(input) + "'"); }
private void CreateExchangeItemsFromXMLNode(XmlNode ExchangeItem, string Identifier) { //Create Dimensions Dimension omiDimensions = new Dimension(); XmlNodeList dimensions = ExchangeItem.SelectNodes("//Dimensions/Dimension"); // You can filter elements here using XPath foreach (XmlNode dimension in dimensions) { if (dimension["Base"].InnerText == "Length") { omiDimensions.SetPower(DimensionBase.Length, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "Time") { omiDimensions.SetPower(DimensionBase.Time, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "AmountOfSubstance") { omiDimensions.SetPower(DimensionBase.AmountOfSubstance, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "Currency") { omiDimensions.SetPower(DimensionBase.Currency, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "ElectricCurrent") { omiDimensions.SetPower(DimensionBase.ElectricCurrent, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "LuminousIntensity") { omiDimensions.SetPower(DimensionBase.LuminousIntensity, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "Mass") { omiDimensions.SetPower(DimensionBase.Mass, Convert.ToDouble(dimension["Power"].InnerText)); } else if (dimension["Base"].InnerText == "Temperature") { omiDimensions.SetPower(DimensionBase.Temperature, Convert.ToDouble(dimension["Power"].InnerText)); } } //Create Units _omiUnits = new Unit(); XmlNode units = ExchangeItem.SelectSingleNode("Quantity/Unit"); _omiUnits.ID = units["ID"].InnerText; if (units["Description"] != null) { _omiUnits.Description = units["Description"].InnerText; } if (units["ConversionFactorToSI"] != null) { _omiUnits.ConversionFactorToSI = Convert.ToDouble(units["ConversionFactorToSI"].InnerText); } if (units["OffSetToSI"] != null) { _omiUnits.OffSetToSI = Convert.ToDouble(units["OffSetToSI"].InnerText); } //Create Quantity Quantity omiQuantity = new Quantity(); XmlNode quantity = ExchangeItem.SelectSingleNode("Quantity"); omiQuantity.ID = quantity["ID"].InnerText; if (quantity["Description"] != null) { omiQuantity.Description = quantity["Description"].InnerText; } omiQuantity.Dimension = omiDimensions; omiQuantity.Unit = _omiUnits; if (quantity["ValueType"] != null) { if (quantity["ValueType"].InnerText == "Scalar") { omiQuantity.ValueType = OpenMI.Standard.ValueType.Scalar; } else if (quantity["ValueType"].InnerText == "Vector") { omiQuantity.ValueType = OpenMI.Standard.ValueType.Vector; } } //Create Element Set ElementSet omiElementSet = new ElementSet(); XmlNode elementSet = ExchangeItem.SelectSingleNode("ElementSet"); omiElementSet.ID = elementSet["ID"].InnerText; if (elementSet["Description"] != null) { omiElementSet.Description = elementSet["Description"].InnerText; } try { //add elements from shapefile to element set SMW.Utilities utils = new SMW.Utilities(); _shapefilepath = elementSet["ShapefilePath"].InnerText; omiElementSet = utils.AddElementsFromShapefile(omiElementSet, _shapefilepath); } catch (Exception) { Debug.WriteLine("An Element Set has not been declared using AddElementsFromShapefile"); } if (Identifier == "OutputExchangeItem") { //create exchange item OutputExchangeItem omiOutputExchangeItem = new OutputExchangeItem(); omiOutputExchangeItem.Quantity = omiQuantity; omiOutputExchangeItem.ElementSet = omiElementSet; //add the output exchange item to the list of output exchange items for the component this._outputs.Add(omiOutputExchangeItem); if (!this._quantities.ContainsKey(omiQuantity.ID)) { this._quantities.Add(omiQuantity.ID, omiQuantity); } if (!this._elementSets.ContainsKey(omiElementSet.ID)) { this._elementSets.Add(omiElementSet.ID, omiElementSet); } } else if (Identifier == "InputExchangeItem") { //create exchange item InputExchangeItem omiInputExchangeItem = new InputExchangeItem(); omiInputExchangeItem.Quantity = omiQuantity; omiInputExchangeItem.ElementSet = omiElementSet; //add the output exchange item to the list of output exchange items for the component this._inputs.Add(omiInputExchangeItem); if (!this._quantities.ContainsKey(omiQuantity.ID)) { this._quantities.Add(omiQuantity.ID, omiQuantity); } if (!this._elementSets.ContainsKey(omiElementSet.ID)) { this._elementSets.Add(omiElementSet.ID, omiElementSet); } } }
public void Initialize(System.Collections.Hashtable properties) { if (properties.ContainsKey("ModelID")) { _modelID = (string)properties["ModelID"]; } if (properties.ContainsKey("TimeStepLength")) { _timeStepLength = Convert.ToDouble((string)properties["TimeStepLength"]); } // -- create a flow quanitity -- Dimension flowDimension = new Dimension(); flowDimension.SetPower(DimensionBase.Length, 3); flowDimension.SetPower(DimensionBase.Time, -1); Unit literPrSecUnit = new Unit("LiterPrSecond", 0.001, 0, "Liters pr Second"); Quantity flowQuantity = new Quantity(literPrSecUnit, "Flow", "Flow", global::OpenMI.Standard.ValueType.Scalar, flowDimension); // -- create leakage quantity -- Quantity leakageQuantity = new Quantity(literPrSecUnit, "Leakage", "Leakage", global::OpenMI.Standard.ValueType.Scalar, flowDimension); // -- create and populate elementset to represente the whole river network -- ElementSet fullRiverElementSet = new ElementSet("WholeRiver", "WholeRiver", ElementType.XYPolyLine, new SpatialReference("no reference")); for (int i = 0; i < _numberOfNodes - 1; i++) { Element element = new Element(); element.ID = "Branch:" + i.ToString(); element.AddVertex(new Vertex(_xCoordinate[i], _yCoordinate[i], -999)); element.AddVertex(new Vertex(_xCoordinate[i + 1], _yCoordinate[i + 1], -999)); fullRiverElementSet.AddElement(element); } // --- populate input exchange items for flow to individual nodes --- for (int i = 0; i < _numberOfNodes; i++) { Element element = new Element(); element.ID = "Node:" + i.ToString(); ElementSet elementSet = new ElementSet("Individual nodes", "Node:" + i.ToString(), ElementType.IDBased, new SpatialReference("no reference")); elementSet.AddElement(element); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.ElementSet = elementSet; inputExchangeItem.Quantity = flowQuantity; _inputExchangeItems.Add(inputExchangeItem); } // --- Populate input exchange item for flow to the whole georeferenced river --- InputExchangeItem wholeRiverInputExchangeItem = new InputExchangeItem(); wholeRiverInputExchangeItem.ElementSet = fullRiverElementSet; wholeRiverInputExchangeItem.Quantity = flowQuantity; _inputExchangeItems.Add(wholeRiverInputExchangeItem); // --- Populate output exchange items for flow in river branches --- for (int i = 0; i < _numberOfNodes - 1; i++) { Element element = new Element(); element.ID = "Branch:" + i.ToString(); ElementSet elementSet = new ElementSet("Individual nodes", "Branch:" + i.ToString(), ElementType.IDBased, new SpatialReference("no reference")); elementSet.AddElement(element); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.ElementSet = elementSet; outputExchangeItem.Quantity = flowQuantity; _outputExchangeItems.Add(outputExchangeItem); } // --- polulate output exchange items for leakage for individual branches -- for (int i = 0; i < _numberOfNodes - 1; i++) { Element element = new Element(); element.ID = "Branch:" + i.ToString(); ElementSet elementSet = new ElementSet("Individual nodes", "Branch:" + i.ToString(), ElementType.IDBased, new SpatialReference("no reference")); elementSet.AddElement(element); OutputExchangeItem outputExchangeItem = new OutputExchangeItem(); outputExchangeItem.ElementSet = elementSet; outputExchangeItem.Quantity = leakageQuantity; _outputExchangeItems.Add(outputExchangeItem); } // --- Populate output exchange item for leakage from the whole georeferenced river --- OutputExchangeItem wholeRiverOutputExchangeItem = new OutputExchangeItem(); wholeRiverOutputExchangeItem.ElementSet = fullRiverElementSet; wholeRiverOutputExchangeItem.Quantity = leakageQuantity; _outputExchangeItems.Add(wholeRiverOutputExchangeItem); // --- populate with initial state variables --- for (int i = 0; i < _numberOfNodes - 1; i++) { _flow[i] = 7; } _currentTimeStepNumber = 1; _initializeMethodWasInvoked = true; }
/// <summary> /// Used to Initialize the component. Performs routines that must be completed prior to simulation start. /// </summary> /// <param name="properties">properties extracted from the components *.omi file</param> public override void Initialize(System.Collections.Hashtable properties) { //--- GET MODEL ATTRIBUTES FROM SMW --- string config = null; //set the config path and output directory from the *.omi file. foreach (DictionaryEntry p in properties) { if (p.Key.ToString() == "ConfigFile") { config = (string)properties["ConfigFile"]; } else if (p.Key.ToString() == "OutDir") { _outDir = (string)properties["OutDir"]; } } //lookup model's configuration file to determine interface properties SetVariablesFromConfigFile(config); SetValuesTableFields(); //input exchange item attributes int num_inputs = this.GetInputExchangeItemCount(); InputExchangeItem input = this.GetInputExchangeItem(num_inputs - 1); input_elementset = input.ElementSet.ID; input_quantity = input.Quantity.ID; //output exchange item attributes int num_outputs = this.GetOutputExchangeItemCount(); OutputExchangeItem output = this.GetOutputExchangeItem(num_outputs - 1); output_elementset = output.ElementSet.ID; output_quantity = output.Quantity.ID; //timehorizon attributes ITimeSpan time_horizon = this.GetTimeHorizon(); string start = CalendarConverter.ModifiedJulian2Gregorian(time_horizon.Start.ModifiedJulianDay).ToString(); string end = CalendarConverter.ModifiedJulian2Gregorian(time_horizon.End.ModifiedJulianDay).ToString(); //get shapefile path string shapefilePath = this.GetShapefilePath(); //get timestep string timestep = this.GetTimeStep().ToString(); //this uses the free SharpMap API for reading a shapefile VectorLayer myLayer = new VectorLayer("elements_layer"); myLayer.DataSource = new ShapeFile(shapefilePath); myLayer.DataSource.Open(); //initialize array to hold the transformed inflow values int size = myLayer.DataSource.GetFeatureCount(); transformedInflow = new double[size]; //--- BUILD XML STRING TO INITIALIZE THE WEB SERVICE --- string reaches = "<elementset>"; for (uint i = 0; i < myLayer.DataSource.GetFeatureCount(); ++i) { FeatureDataRow feat = myLayer.DataSource.GetFeature(i); //TODO: eliminate this, by spatially referencing the elements //Get the correct ArcID to ensure that the elementset will align correctly //This routine, ensures that the reaches are added to the XML stream such that the the elements // align with the subwatersheds.shp. In order to do this I had to assign ArcID's that match the // corresponding Subwatershed.shp elements. bool IsCorrect = false; uint j = 0; while (!IsCorrect) { feat = myLayer.DataSource.GetFeature(j); if (feat.ItemArray[0].ToString() == (i + 1).ToString()) { IsCorrect = true; } else { j++; } } //Add the FROM attribute of each reach, in the order that // ---> they are established within the xml string ArrayList attributes = new ArrayList(); attributes.Add(feat.ItemArray[feat.Table.Columns.IndexOf("TO_COMID")].ToString()); attributes.Add(feat.ItemArray[feat.Table.Columns.IndexOf("FROM_COMID")].ToString()); //Add i to the reachOrder array. This will index the order in which values are retrieved // --> from the upstream component. reachOrder.Add(Convert.ToInt32(i), attributes); //Add shapefile attributes into the xml string reaches += "<element>"; reaches += "<From>" + feat.ItemArray[feat.Table.Columns.IndexOf("FROM_COMID")].ToString() + "</From>"; reaches += "<To>" + feat.ItemArray[feat.Table.Columns.IndexOf("TO_COMID")].ToString() + "</To>"; reaches += "<K>" + feat.ItemArray[feat.Table.Columns.IndexOf("K")].ToString() + "</K>"; //TravelTime in hours reaches += "<X>" + feat.ItemArray[feat.Table.Columns.IndexOf("X")].ToString() + "</X>"; reaches += "</element>"; } reaches += "<TimeHorizon>"; reaches += "<TimeStepInSeconds>" + timestep + "</TimeStepInSeconds>"; reaches += "<StartDateTime>" + start + "</StartDateTime>"; reaches += "<EndDateTime>" + end + "</EndDateTime>"; reaches += "</TimeHorizon></elementset>"; //--- INITIALIZE THE WEB SERVICE --- bool init = model.initialize(reaches); if (init == false) { throw new Exception("The Muskingum Web Service Failed to Initialize"); } //Create a streamwriter to save results from Perform Time Step if (_outDir != null) { try { sw = new System.IO.StreamWriter(_outDir + "/MuskingumRouting_output.csv"); } catch (SystemException e) { throw new Exception("The Muskingum (Python) 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 (Python) component failed in writing it output file to path " + System.IO.Directory.GetCurrentDirectory() + ". This may be due to " + "lack of user permissions.", e); } } }
public void Initialize(System.Collections.Hashtable properties) { //List of exchange Items inputExchangeItems = new List <InputExchangeItem>(); outputExchangeItems = new List <OutputExchangeItem>(); //Initializes Engine MohidWaterEngine = new MohidWaterEngineDotNetAccess(); MohidWaterEngine.Initialize(properties["FilePath"].ToString()); // //Dimensions // Dimension dimFlow = new Dimension(); dimFlow.SetPower(DimensionBase.Length, 3); dimFlow.SetPower(DimensionBase.Time, -1); Dimension dimWaterlevel = new Dimension(); dimWaterlevel.SetPower(DimensionBase.Length, 1); Dimension dimConcentration = new Dimension(); dimConcentration.SetPower(DimensionBase.Mass, 1); dimConcentration.SetPower(DimensionBase.Length, -3); // //Units // Unit unitFlow = new Unit("m3/sec", 1, 0, "cubic meter per second"); Unit unitWaterLevel = new Unit("m", 1, 0, "sea water level"); Unit unitConcentration = new Unit("mg/l", 1, 0, "miligram per liter"); // //Quantities // qtdDischargeFlow = new Quantity(unitFlow, "Input Discharge Flow", "Discharge Flow", global::OpenMI.Standard.ValueType.Scalar, dimFlow); qtdWaterLevel = new Quantity(unitWaterLevel, "Waterlevel of the water surface", "Waterlevel", global::OpenMI.Standard.ValueType.Scalar, dimWaterlevel); // //Spatial Reference // SpatialReference spatialReference = new SpatialReference("spatial reference"); // //Element Sets // //Model Grid ElementSet modelGrid = new ElementSet("Model Grid Points of all Compute Points", "Model Grid", ElementType.XYPolygon, spatialReference); //Output exchange items - properties in each grid cell (surface only) numberOfWaterPoints = 0; for (int i = 1; i <= MohidWaterEngine.GetIUB(horizontalGridInstanceID); i++) { for (int j = 1; j <= MohidWaterEngine.GetJUB(horizontalGridInstanceID); j++) { if (MohidWaterEngine.IsWaterPoint(horizontalMapInstanceID, i, j)) { String name = "i=" + i.ToString() + "/j=" + j.ToString(); double[] xCoords = new double[5]; double[] yCoords = new double[5]; MohidWaterEngine.GetGridCellCoordinates(horizontalGridInstanceID, i, j, ref xCoords, ref yCoords); Element element = new Element(name); element.AddVertex(new Vertex(xCoords[0], yCoords[0], 0)); element.AddVertex(new Vertex(xCoords[1], yCoords[1], 0)); element.AddVertex(new Vertex(xCoords[2], yCoords[2], 0)); element.AddVertex(new Vertex(xCoords[3], yCoords[3], 0)); modelGrid.AddElement(element); numberOfWaterPoints++; } } } //allocates waterlevels1D modelGridValues1D = new double[numberOfWaterPoints]; //Discharge Points ElementSet dischargePoints = new ElementSet("Discharge Points", "Discharge Points", ElementType.XYPoint, spatialReference); //Flow input exchange to discharges configured as OpenMI Discharges for (int i = 1; i <= MohidWaterEngine.GetNumberOfDischarges(dischargeInstanceID); i++) { if (MohidWaterEngine.GetDischargeType(dischargeInstanceID, i) == 4) { Element dischargeElement = new Element(MohidWaterEngine.GetDischargeName(dischargeInstanceID, i)); dischargeElement.AddVertex( new Vertex(MohidWaterEngine.GetDischargeXCoordinate(dischargeInstanceID, i), MohidWaterEngine.GetDischargeYCoordinate(dischargeInstanceID, i), 0)); dischargePoints.AddElement(dischargeElement); } } // //Output Exchange Items // //Water Level of the Hydrodynamic model OutputExchangeItem waterlevel = new OutputExchangeItem(); waterlevel.Quantity = qtdWaterLevel; waterlevel.ElementSet = modelGrid; outputExchangeItems.Add(waterlevel); //Properties of the Water properties model for (int idx = 1; idx <= MohidWaterEngine.GetNumberOfProperties(waterPropertiesInstanceID); idx++) { int propertyID = MohidWaterEngine.GetPropertyIDNumber(waterPropertiesInstanceID, idx); string propertyName = MohidWaterEngine.GetPropertyNameByIDNumber(propertyID); Quantity concentrationQuantity = new Quantity(unitConcentration, "Concentration of " + propertyName, propertyID.ToString(), ValueType.Scalar, dimConcentration); qtdProperties.Add(concentrationQuantity); OutputExchangeItem concExchangeItem = new OutputExchangeItem(); concExchangeItem.Quantity = concentrationQuantity; concExchangeItem.ElementSet = modelGrid; outputExchangeItems.Add(concExchangeItem); } //Flow input exchange to discharges configured as OpenMI Discharges for (int i = 1; i <= MohidWaterEngine.GetNumberOfDischarges(dischargeInstanceID); i++) { if (MohidWaterEngine.GetDischargeType(dischargeInstanceID, i) == 4) { String pointName = MohidWaterEngine.GetDischargeName(dischargeInstanceID, i); ElementSet dischargePoint = new ElementSet("Discharge Point of MOHID Water", i.ToString(), ElementType.XYPoint, spatialReference); InputExchangeItem inputDischarge = new InputExchangeItem(); inputDischarge.Quantity = qtdDischargeFlow; Element element = new Element("Point: " + pointName); element.AddVertex(new Vertex(MohidWaterEngine.GetDischargeXCoordinate(dischargeInstanceID, i), MohidWaterEngine.GetDischargeYCoordinate(dischargeInstanceID, i), 0)); dischargePoint.AddElement(element); inputDischarge.ElementSet = dischargePoint; inputExchangeItems.Add(inputDischarge); for (int idx = 1; idx <= MohidWaterEngine.GetNumberOfDischargeProperties(dischargeInstanceID, i); idx++) { int propertyID = MohidWaterEngine.GetDischargePropertyID(dischargeInstanceID, i, idx); string propertyName = MohidWaterEngine.GetPropertyNameByIDNumber(propertyID); Quantity concentrationQuantity = new Quantity(unitConcentration, propertyName, propertyID.ToString(), global::OpenMI.Standard.ValueType.Scalar, dimConcentration); InputExchangeItem inputExchangeItem = new InputExchangeItem(); inputExchangeItem.ElementSet = dischargePoint; inputExchangeItem.Quantity = concentrationQuantity; inputExchangeItems.Add(inputExchangeItem); } } } }
public void Initialize(System.Collections.Hashtable properties) { Dictionary <string, List <string> > groupItems = new Dictionary <string, List <string> >(); Dictionary <string, List <string> > OutputGroupItems = new Dictionary <string, List <string> >(); //extract argument(s) from OMI file foreach (string Key in properties.Keys) { if (Key.Split(':')[1] == "InputTimeSeries") { if (groupItems.ContainsKey(properties[Key].ToString())) { groupItems[properties[Key].ToString()].Add(Key.Split(':')[1] + (groupItems[properties[Key].ToString()].Count + 1).ToString()); } else { List <string> l = new List <string>(); l.Add(Key.Split(':')[1] + "1"); groupItems.Add(properties[Key].ToString(), l); } } else if (Key.Split(':')[1] == "OutputTimeSeries") { if (OutputGroupItems.ContainsKey(properties[Key].ToString())) { OutputGroupItems[properties[Key].ToString()].Add(Key.Split(':')[1] + (groupItems[properties[Key].ToString()].Count + 1).ToString()); } else { List <string> l = new List <string>(); l.Add(Key.Split(':')[1] + "1"); OutputGroupItems.Add(properties[Key].ToString(), l); } System.Collections.Hashtable hashtable = new Hashtable(); hashtable.Add("OutputExchangeItem", properties[Key]); //pass this info to the IRunEngine, via Intitialize _engineApiAccess.Initialize(hashtable); } } //create input and output exchange items from the groups defined above. int group = 0; foreach (KeyValuePair <string, List <string> > item in groupItems) { group++; for (int i = 0; i <= item.Value.Count - 1; i++) { string seriesID = item.Value[i]; string[] details = item.Key.ToString().Split(':'); Unit u = new Unit(); u.Description = details[1]; u.ID = details[1]; Quantity q = new Quantity(); q.Description = details[0]; q.ID = details[0]; q.ValueType = OpenMI.Standard.ValueType.Scalar; q.Unit = u; ElementSet eset = new ElementSet(); eset.Description = seriesID; eset.ID = seriesID; eset.ElementType = ElementType.IDBased; InputExchangeItem input = new InputExchangeItem(); input.Quantity = q; input.ElementSet = eset; _inputExchangeItems.Add(input); } } foreach (KeyValuePair <string, List <string> > item in OutputGroupItems) { for (int i = 0; i <= item.Value.Count - 1; i++) { string seriesID = item.Value[i]; string[] details = item.Key.ToString().Split(':'); Unit u = new Unit(); u.Description = details[2]; u.ID = details[2]; Quantity q = new Quantity(); q.Description = details[1]; q.ID = details[1]; q.ValueType = OpenMI.Standard.ValueType.Scalar; q.Unit = u; ElementSet eset = new ElementSet(); eset.Description = details[0]; eset.ID = details[0]; eset.ElementType = ElementType.IDBased; try { int elementCount = Convert.ToInt32(details[3].Split('=')[1]); for (int k = 0; k <= elementCount - 1; k++) { Element e = new Element(); eset.AddElement(e); } } catch (Exception) { } OutputExchangeItem input = new OutputExchangeItem(); input.Quantity = q; input.ElementSet = eset; _outputExchangeItems.Add(input); } } }