Beispiel #1
0
        private double _timeStepLength; //[seconds]


        public RiverModelEngine(ILinkableComponent myLinkableComponent)
        {
            this.myLinkableComponent = myLinkableComponent;
            _modelID     = "TestRiverModel Model Caption";
            _xCoordinate = new double[] { 3, 5, 8, 8 };
            _yCoordinate = new double[] { 9, 7, 7, 3 };

            _numberOfNodes = _xCoordinate.Length;

            _simulationStart = new DateTime(2005, 1, 1, 0, 0, 0);
            _simulationEnd   = new DateTime(2005, 2, 10, 0, 0, 0);
            _timeStepLength  = 3600 * 24; //one day

            _inputExchangeItems  = new List <IInputItem>();
            _outputExchangeItems = new List <IOutputItem>();

            _storage = new double[_numberOfNodes];
            for (int i = 0; i < _numberOfNodes; i++)
            {
                _storage[i] = 0;
            }
            _flow    = new double[_numberOfNodes - 1];
            _leakage = new double[_numberOfNodes - 1];
            _runoff  = 10;
            _currentTimeStepNumber = 0;

            _initializeMethodWasInvoked = false;
            _finishMethodWasInvoked     = false;
            _disposeMethodWasInvoked    = false;

            _states         = new ArrayList();
            _stateIdCreator = 0;
        }
Beispiel #2
0
        public void Init()
        {
            controller = new IterationController();
            Quantity Q = new Quantity("Q");
            Quantity H = new Quantity("H");

            modelA   = new TestComponent();
            modelB   = new TestComponent();
            deployer = new TestComponent();
            ElementSet point = new ElementSet("point", "point", ElementType.IDBased,
                                              new SpatialReference());
            ElementSet slot1 = new ElementSet("1", "1", ElementType.IDBased, new SpatialReference());
            ElementSet slot2 = new ElementSet("2", "2", ElementType.IDBased, new SpatialReference());

            link1 = new Link(controller, slot1, Q, modelA, point, Q, "link1");
            controller.AddLink(link1);
            modelA.AddLink(link1);
            link2 = new Link(modelA, point, H, controller, slot2, H, "link2");
            controller.AddLink(link2);
            modelA.AddLink(link2);
            link3 = new Link(controller, slot2, H, modelB, point, H, "link3");
            controller.AddLink(link3);
            modelB.AddLink(link3);
            link4 = new Link(modelB, point, Q, controller, slot1, Q, "link4");
            controller.AddLink(link4);
            modelB.AddLink(link4);
            link5 = new Link(controller, slot1, Q, deployer, point, Q, "link5");
            deployer.AddLink(link5);
            controller.AddLink(link5);
            link6 = new Link(controller, slot2, H, deployer, point, H, "link6");
            deployer.AddLink(link6);
            controller.AddLink(link6);
        }
Beispiel #3
0
        public void Create(string modelId, string workingDirectory, string assemblyPath, string linkableComponent)
        {
            _workingDirectory = workingDirectory;
            string oldDirectory = Directory.GetCurrentDirectory();

            try
            {
                Directory.SetCurrentDirectory(_workingDirectory);
                AssemblySupport.LoadAssembly(_workingDirectory, assemblyPath);

                object obj = AssemblySupport.GetNewInstance(linkableComponent);
                if (!(obj is ILinkableComponent))
                {
                    throw new Exception("\n\nThe class type " + linkableComponent + " in\n" +
                                        assemblyPath +
                                        "\nis not an OpenMI.Standard.ILinkableComponent (OpenMI.Standard.dll version 1.4)." +
                                        "\nYou may have specified a wrong class name, " +
                                        "\nor the class implements the ILinkableComponent interface of a previous version of the OpenMI Standard.\n");
                }
                _linkableComponent = (ILinkableComponent)obj;
            }
            finally
            {
                Directory.SetCurrentDirectory(oldDirectory);
            }

            _modelID = modelId;
        }
 public static ComponentProperties read(String filename, ILinkableComponent component,
         Dictionary<String, IElementSet> elementSets)
 {
     var xmlDocument = new XmlDocument();
     xmlDocument.Load(filename);
     var properties = readConfiguration(xmlDocument, component, elementSets);
     return properties;
 }
 public void Init()
 {
     events = new List <LinkableComponentStatusChangeEventArgs>();
     Argument[] arguments = { new Argument("Path", @"..\..\Data\", true, "description") };
     riverModelLC = new RiverModelLinkableComponent();
     riverModelLC.StatusChanged += riverModelLC_StatusChanged;
     riverModelLC.Initialize(arguments);
 }
        public override void AddLink(ILink link)
        {
            ILinkableComponent LC = link.SourceComponent;

            for (int i = 0; i < GetAcceptedEventTypeCount(); i++)
            {
                EventType ev = GetAcceptedEventType(i);
                LC.Subscribe(this, ev);
            }
            base.AddLink(link);
        }
Beispiel #7
0
 public EventCopy(IEvent theEvent)
 {
     _description = theEvent.Description;
     _type        = theEvent.Type;
     _sender      = theEvent.Sender;
     if (theEvent.SimulationTime == null)
     {
         _simulationTime = null;
     }
     else
     {
         _simulationTime = new TimeStamp(theEvent.SimulationTime);
     }
 }
Beispiel #8
0
        protected void RestoreAllStates()
        {
            IEnumerator enumerator = GetAcceptingLinks().GetEnumerator();

            while (enumerator.MoveNext())
            {
                ILink link = (ILink)enumerator.Current;
                ILinkableComponent provider = link.SourceComponent;
                if (provider is IManageState)
                {
                    ((IManageState)provider).RestoreState((string)StateTable[link.ID]);
                }
            }
        }
Beispiel #9
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="SourceComponent">The source component</param>
 /// <param name="SourceElementSet">The source element set</param>
 /// <param name="SourceQuantity">The source quantity</param>
 /// <param name="TargetComponent">The target component</param>
 /// <param name="TargetElementSet">The target element set</param>
 /// <param name="TargetQuantity">The target quantity</param>
 /// <param name="ID">The ID</param>
 public Link(ILinkableComponent SourceComponent,
             IElementSet SourceElementSet,
             IQuantity SourceQuantity,
             ILinkableComponent TargetComponent,
             IElementSet TargetElementSet,
             IQuantity TargetQuantity,
             string ID)
 {
     _sourceComponent  = SourceComponent;
     _sourceElementSet = SourceElementSet;
     _sourceQuantity   = SourceQuantity;
     _targetComponent  = TargetComponent;
     _targetElementSet = TargetElementSet;
     _targetQuantity   = TargetQuantity;
     _description      = Description;
     _id = ID;
 }
Beispiel #10
0
        public void Init()
        {
            gwModelLC = new Oatc.OpenMI.Examples.ModelComponents.SpatialModels.GroundWaterModel.GWModelLC();

            Oatc.OpenMI.Sdk.Backbone.Argument[] arguments = new Argument[10];
            arguments[0] = new Oatc.OpenMI.Sdk.Backbone.Argument("simulationStart", "1990,1,2,0,0,0", true, " year, month, day, hour, minute, second for simulation start");
            arguments[1] = new Oatc.OpenMI.Sdk.Backbone.Argument("simulationEnd", "1990,2,1,0,0,0", true, " year, month, day, hour, minute, second for simulation start");
            arguments[2] = new Oatc.OpenMI.Sdk.Backbone.Argument("nx", "2", true, "Number of grid cells in x-direction");
            arguments[3] = new Oatc.OpenMI.Sdk.Backbone.Argument("ny", "2", true, "Number of grid cells in y-direction");
            arguments[4] = new Oatc.OpenMI.Sdk.Backbone.Argument("ox", "1000", true, "origo X");
            arguments[5] = new Oatc.OpenMI.Sdk.Backbone.Argument("oy", "2000", true, "origo Y");
            arguments[6] = new Oatc.OpenMI.Sdk.Backbone.Argument("cellSize", "900", true, "cell size");
            arguments[7] = new Oatc.OpenMI.Sdk.Backbone.Argument("groundWaterLevel", "1.0", true, "Ground Wagter Level");
            arguments[8] = new Oatc.OpenMI.Sdk.Backbone.Argument("modelID", "GWModelEngineModelID", true, "model ID");
            arguments[9] = new Oatc.OpenMI.Sdk.Backbone.Argument("gridAngle", "0", true, "rotation angle for the grid");

            gwModelLC.Initialize(arguments);
        }
 /// <summary>
 /// Send event
 /// </summary>
 /// <param name="eventType">the event type to send</param>
 /// <param name="sender">reference to the sender (this)</param>
 public void SendEvent(EventType eventType, ILinkableComponent sender)
 {
     if (((Oatc.OpenMI.Sdk.Backbone.LinkableComponent) this.link.TargetComponent).HasListeners())
     {
         Oatc.OpenMI.Sdk.Backbone.Event eventD = new Oatc.OpenMI.Sdk.Backbone.Event(eventType);
         eventD.Description = eventType.ToString();
         eventD.Sender      = sender;
         ITime t = this._engine.GetCurrentTime();
         if (t is ITimeStamp)
         {
             eventD.SimulationTime = t as ITimeStamp;
         }
         else
         {
             eventD.SimulationTime = ((ITimeSpan)this._engine.GetCurrentTime()).End;
         }
         this.link.TargetComponent.SendEvent(eventD);
     }
 }
 /// <summary>
 /// Send event
 /// </summary>
 /// <param name="eventType">the event type to send</param>
 /// <param name="sender">reference to the sender (this)</param>
 public void SendEvent( EventType eventType, ILinkableComponent sender)
 {
     if (((Oatc.OpenMI.Sdk.Backbone.LinkableComponent)this.link.TargetComponent).HasListeners())
       {
       Oatc.OpenMI.Sdk.Backbone.Event eventD = new Oatc.OpenMI.Sdk.Backbone.Event(eventType);
       eventD.Description = eventType.ToString();
       eventD.Sender = sender;
       ITime t = this._engine.GetCurrentTime();
       if (t is ITimeStamp)
       {
           eventD.SimulationTime = t as ITimeStamp;
       }
       else
       {
           eventD.SimulationTime = ((ITimeSpan)this._engine.GetCurrentTime()).End;
       }
       this.link.TargetComponent.SendEvent(eventD);
       }
 }
Beispiel #13
0
        public GWModelEngine(ILinkableComponent myLinkableComponent)
        {
            this.myLinkableComponent = myLinkableComponent;
            _numberOfElements        = 4;
            _simulationStart         = new DateTime(2005, 1, 1, 0, 0, 0);
            _simulationEnd           = new DateTime(2005, 2, 10, 0, 0, 0);
            _timeStepLength          = 3600 * 24; //one day

            _inputExchangeItems  = new List <IInputItem>();
            _outputExchangeItems = new List <IOutputItem>();

            _storage = new double[_numberOfElements];

            for (int i = 0; i < _numberOfElements; i++)
            {
                _storage[i] = 0;
            }

            _currentTimeStepNumber = 0;
        }
        /// <summary>
        /// Removes connection between two models.
        /// </summary>
        /// <param name="connection">Connection to be removed.</param>
        public void RemoveConnection(Connection connection)
        {
            // remove ILinks from both connected components
            if (!_runPrepareForComputationStarted)
            {
                foreach (ILink link in connection.Links)
                {
                    string linkID = link.ID;
                    ILinkableComponent
                        sourceComponent = link.SourceComponent,
                        targetComponent = link.TargetComponent;


                    sourceComponent.RemoveLink(linkID);
                    targetComponent.RemoveLink(linkID);
                }
            }

            _connections.Remove(connection);
        }
Beispiel #15
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="SourceComponent">The source component</param>
 /// <param name="SourceElementSet">The source element set</param>
 /// <param name="SourceQuantity">The source quantity</param>
 /// <param name="TargetComponent">The target component</param>
 /// <param name="TargetElementSet">The target element set</param>
 /// <param name="TargetQuantity">The target quantity</param>
 /// <param name="Description">The description</param>
 /// <param name="ID">The ID</param>
 /// <param name="DataOperations">Data operations to be carried out by the provider</param>
 public Link(ILinkableComponent SourceComponent,
             IElementSet SourceElementSet,
             IQuantity SourceQuantity,
             ILinkableComponent TargetComponent,
             IElementSet TargetElementSet,
             IQuantity TargetQuantity,
             string Description,
             string ID,
             ArrayList DataOperations)
 {
     _sourceComponent  = SourceComponent;
     _sourceElementSet = SourceElementSet;
     _sourceQuantity   = SourceQuantity;
     _targetComponent  = TargetComponent;
     _targetElementSet = TargetElementSet;
     _targetQuantity   = TargetQuantity;
     _description      = Description;
     _id             = ID;
     _dataOperations = DataOperations;
 }
Beispiel #16
0
        //private DbOperations _db;

        #region ILinkableComponent Members

        /// <summary>
        /// This method is called when links are created by the component
        /// </summary>
        /// <param name="link">OpenMI link object</param>
        public void AddLink(ILink link)
        {
            //subscribe to events
            ILinkableComponent LC = link.SourceComponent;

            for (int i = 0; i < GetAcceptedEventTypeCount(); i++)
            {
                EventType ev = GetAcceptedEventType(i);
                LC.Subscribe(this, ev);
            }

            //build HD data model object to store time-series
            CreateSeries(link);

            //store the link for future reference
            _links.Add(link.ID, link);

            // create timestep list
            //_timestep.Add(link.ID, new List<DateTime>());
        }
        public void Init()
        {
            controller = new OptimizationController(1);
            IArgument[] properties = new Argument[1];
            properties[0] = new Argument("Parameter", "P0,-100,100,3.5", true, "Parameter 1");
            controller.Initialize(properties);
            modelA   = new TestFunction();
            deployer = new TestComponent();
            ElementSet slot1 = new ElementSet("P0", "P0", ElementType.IDBased, null);

            link1 = new Link(controller, slot1, null, deployer, slot1, null, "link1");
            deployer.AddLink(link1);
            controller.AddLink(link1);

            link2 = new Link(modelA, slot1, null, controller, slot1, null, "link2");
            controller.AddLink(link2);
            modelA.AddLink(link2);

            link3 = new Link(controller, slot1, null, modelA, slot1, null, "link3");
            controller.AddLink(link3);
            modelA.AddLink(link3);
        }
Beispiel #18
0
        private ListViewItem GetItem(IEvent Event)
        {
            string[] subItems = new string[5];
            subItems[0] = (_eventsCount++).ToString();
            subItems[1] = Event.Type.ToString();
            subItems[2] = Event.Description;

            ILinkableComponent sender = Event.Sender;

            if (sender != null)
            {
                subItems[3] = sender.ModelID;
            }

            ITimeStamp simTime = Event.SimulationTime;

            if (simTime != null)
            {
                subItems[4] = CalendarConverter.ModifiedJulian2Gregorian(simTime.ModifiedJulianDay).ToString();
            }

            return(new ListViewItem(subItems));
        }
 private bool isModelEngineComponent(ILinkableComponent component)
 {
     return(typeof(LinkableRunEngine).IsAssignableFrom(component.GetType()));
 }
        private static List<OutputExchangeItem> readOutputExchangeItems(XmlNode aNode, ILinkableComponent component,
                Dictionary<String, IElementSet> elementSets)
        {
            var items = new List<OutputExchangeItem>();

            foreach (XmlNode node in aNode.ChildNodes)
            {
                if (node.Name == "OutputExchangeItem")
                {
                    var item = new OutputExchangeItem();

                    // 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;
        }
        private static ComponentProperties readConfiguration(XmlDocument doc, ILinkableComponent component,
                Dictionary<String, IElementSet> elementSets)
        {
            var aNode = doc.ChildNodes[0];

            // ensure the configuration element is there
            Utils.forceNodeName(aNode, "Configuration");

            // create a new properties object
            var properties = new ComponentProperties();

            // read the element sets and create temporary objects that can be
            // assigned to the output exchange items as we read them, note that
            // we want to add them to our current set, since we may have read
            // other element sets from the element set file
            readElementSets(Utils.findChildNode(aNode, "ElementSets", false), elementSets);

            // read the name-value pair extras
            properties.setExtras(readExtras(Utils.findChildNode(aNode, "Extras", false)));

            // read the exchange items
            properties.setOutputExchangeItems(readOutputExchangeItems(Utils.findChildNode(aNode, "ExchangeItems"),
                component, elementSets));
            properties.setInputExchangeItems(readInputExchangeItems(Utils.findChildNode(aNode, "ExchangeItems"), component,
                elementSets));

            // read the time horizon
            var timeHorizonNode = Utils.findChildNode(aNode, "TimeHorizon");
            properties.setStartDateTime(Utils.readDateTimeString(Utils.findChildNodeValue(timeHorizonNode, "StartDateTime")));
            properties.setEndDateTime(Utils.readDateTimeString(Utils.findChildNodeValue(timeHorizonNode, "EndDateTime")));
            properties.setTimeStepInSeconds(Double.Parse(Utils
                .findChildNodeValue(timeHorizonNode, "TimeStepInSeconds")));

            // read the model info
            var modelInfoNode = Utils.findChildNode(aNode, "ModelInfo");
            properties.setModelId(Utils.findChildNodeValue(modelInfoNode, "ID"));
            properties.setModelDescription(Utils.findChildNodeValue(modelInfoNode, "Description"));
            if (Utils.findChildNode(modelInfoNode, "PrefetchEnabled", false) != null)
                properties.setExtra("prefetchEnabled", Utils.findChildNodeValue(modelInfoNode, "PrefetchEnabled"));
            if (Utils.findChildNode(modelInfoNode, "CacheEnabled", false) != null)
                properties.setExtra("cacheEnabled", Utils.findChildNodeValue(modelInfoNode, "CacheEnabled"));
            if (Utils.findChildNode(modelInfoNode, "CacheName", false) != null)
                properties.setExtra("cacheName", Utils.findChildNodeValue(modelInfoNode, "CacheName"));
            if (Utils.findChildNode(modelInfoNode, "ProcessingTime", false) != null)
                properties.setExtra("processingTime", Utils.findChildNodeValue(modelInfoNode, "ProcessingTime"));
            if (Utils.findChildNode(modelInfoNode, "UsePersistence", false) != null)
                properties.setExtra("usePersistence", Utils.findChildNodeValue(modelInfoNode, "UsePersistence"));
            if (Utils.findChildNode(modelInfoNode, "StartupDelay", false) != null)
                properties.setExtra("startupDelay", Utils.findChildNodeValue(modelInfoNode, "StartupDelay"));
            if (Utils.findChildNode(modelInfoNode, "ShutdownDelay", false) != null)
                properties.setExtra("shutdownDelay", Utils.findChildNodeValue(modelInfoNode, "ShutdownDelay"));

            return properties;
        }
Beispiel #22
0
        /// <summary>
        /// Sets this model according to OMI file.
        /// </summary>
        /// <param name="filename">Relative or absolute path to OMI file describing the model.</param>
        /// <param name="relativeDirectory">Directory <c>filename</c> is relative to, or <c>null</c> if <c>filename</c> is absolute or relative to current directory.</param>
        /// <remarks>See <see cref="Utils.GetFileInfo">Utils.GetFileInfo</see> for more info about how
        /// specified file is searched.</remarks>
        public void ReadOMIFile(string relativeDirectory, string filename)
        {
            // Open OMI file as xmlDocument
            FileInfo omiFileInfo = Utils.GetFileInfo(relativeDirectory, filename);

            if (!omiFileInfo.Exists)
            {
                throw(new Exception("Omi file not found (CurrentDirectory='" + Directory.GetCurrentDirectory() + "', File='" + filename + "')"));
            }

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.Load(omiFileInfo.FullName);

            // get 1st LinkableComponent element
            XmlElement xmlLinkableComponent = null;

            foreach (XmlNode node in xmlDocument.ChildNodes)
            {
                if (node.Name == "LinkableComponent")
                {
                    xmlLinkableComponent = (XmlElement)node;
                    break;
                }
            }

            // load assembly if present (from relative location of the OMI file)
            if (xmlLinkableComponent == null)
            {
                throw new Exception("No linkable components found in composition file " + omiFileInfo);
            }
            else
            {
                string assemblyFilename = xmlLinkableComponent.GetAttribute("Assembly");
                if (assemblyFilename != null)
                {
                    AssemblySupport.LoadAssembly(omiFileInfo.DirectoryName, assemblyFilename);
                }
            }

            // read arguments
            ArrayList linkableComponentArguments = new ArrayList();

            foreach (XmlElement xmlArguments in xmlLinkableComponent.ChildNodes)
            {
                if (xmlArguments.Name == "Arguments")
                {
                    foreach (XmlElement xmlArgument in xmlArguments.ChildNodes)
                    {
                        linkableComponentArguments.Add(new Argument(xmlArgument.GetAttribute("Key"), xmlArgument.GetAttribute("Value"), true, "No description"));
                    }
                }
            }

            // get new instance of ILinkableComponent type
            // for this moment set current directory to omi file's directory
            string oldDirectory = Directory.GetCurrentDirectory();

            try
            {
                Directory.SetCurrentDirectory(omiFileInfo.DirectoryName);

                string classTypeName = xmlLinkableComponent.GetAttribute("Type");
                object obj           = AssemblySupport.GetNewInstance(classTypeName);
                if (!(obj is ILinkableComponent))
                {
                    throw new Exception("\n\nThe class type " + classTypeName + " in\n" +
                                        filename +
                                        "\nis not an OpenMI.Standard.ILinkableComponent (OpenMI.Standard.dll version 1.4.0.0)." +
                                        "\nYou may have specified a wrong class name, " +
                                        "\nor the class implements the ILinkableComponent interface of a previous version of the OpenMI Standard.\n");
                }
                _linkableComponent = (ILinkableComponent)obj;
                _linkableComponent.Initialize((IArgument[])linkableComponentArguments.ToArray(typeof(IArgument)));
            }
            finally
            {
                Directory.SetCurrentDirectory(oldDirectory);
            }

            _omiFilename = omiFileInfo.FullName;

            _modelID = _linkableComponent.ModelID;

            // remote components have rectangle style
            string componentDescription = _linkableComponent.ComponentDescription;

            if (componentDescription != null)
            {
                if (componentDescription.IndexOf("OpenMI.Distributed") >= 0)
                {
                    _rectanglePen.DashStyle = DashStyle.Dash;
                }
            }
        }
Beispiel #23
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="type">Event type</param>
 /// <param name="sender"> Sender of the event</param>
 /// <param name="description">Description for the event</param>
 public Event(EventType type, ILinkableComponent sender, string description)
 {
     _type        = type;
     _sender      = sender;
     _description = description;
 }
        /// <summary>
        /// Constructs a new <see cref="PropertyManager">PropertyManager</see> from <c>object</c>
        /// of known type.
        /// </summary>
        /// <param name="obj">Object of known type.</param>
        /// <param name="allReadOnly">If true, all properties are readonly.</param>
        /// <returns>Returns new <see cref="PropertyManager">PropertyManager</see>
        /// or <c>null</c> if object's type isn't known.</returns>
        /// <remarks>A this time this method knowns following types:
        /// <list>
        /// <item><see cref="IQuantity">IQuantity</see></item>
        /// <item><see cref="IElementSet">IElementSet</see></item>
        /// <item><see cref="IDataOperation">IDataOperation</see></item>
        /// <item><see cref="ILinkableComponent">ILinkableComponent</see></item>
        /// </list>
        /// Method saves <c>obj</c> parameter to <see cref="Tag">Tag</see> property, but you can
        /// use it for any purpose.
        /// </remarks>
        public static PropertyManager ConstructPropertyManager(object obj, bool allReadOnly)
        {
            PropertyManager prop = null;

            if (obj is IQuantity)
            {
                IQuantity quantity = (IQuantity)obj;
                prop = new PropertyManager();

                // General
                prop.SetProperty("Description", quantity.Description, true, "Description of this Quantity.", "General");
                prop.SetProperty("ID", quantity.ID, true, "ID of this Quantity.", "General");
                prop.SetProperty("ValueType", quantity.ValueType.ToString(), true, "Type of this Quantity's value.", "General");

                // Dimensions
                prop.SetProperty("AmountOfSubstance", quantity.Dimension.GetPower(DimensionBase.AmountOfSubstance).ToString(), true, "The amount of substance in mole.", "Dimensions");
                prop.SetProperty("Currency", quantity.Dimension.GetPower(DimensionBase.Currency).ToString(), true, "Currency in Euro.", "Dimensions");
                prop.SetProperty("ElectricCurrent", quantity.Dimension.GetPower(DimensionBase.ElectricCurrent).ToString(), true, "Electric current in ampere.", "Dimensions");
                prop.SetProperty("Length", quantity.Dimension.GetPower(DimensionBase.Length).ToString(), true, "Length in meter.", "Dimensions");
                prop.SetProperty("LuminousIntensity", quantity.Dimension.GetPower(DimensionBase.LuminousIntensity).ToString(), true, "Luminous intensity in candela.", "Dimensions");
                prop.SetProperty("Mass", quantity.Dimension.GetPower(DimensionBase.Mass).ToString(), true, "Mass in kilogram.", "Dimensions");
                prop.SetProperty("Temperature", quantity.Dimension.GetPower(DimensionBase.Temperature).ToString(), true, "Temperature in kelvin.", "Dimensions");
                prop.SetProperty("Time", quantity.Dimension.GetPower(DimensionBase.Time).ToString(), true, "Time in second.", "Dimensions");

                // Unit
                prop.SetProperty("ConversionFactorToSI", quantity.Unit.ConversionFactorToSI.ToString(), true, "Multiplicative coefficient used to convert this quantity to SI (SiUnit = Unit*ConversionFactorToSI + OffSetToSI).", "Unit");
                prop.SetProperty("OffSetToSI", quantity.Unit.OffSetToSI.ToString(), true, "Additive coefficient used to convert this quantity to SI (SiUnit = Unit*ConversionFactorToSI + OffSetToSI).", "Unit");
                prop.SetProperty("UnitDescription", quantity.Unit.Description, true, "Description of this unit.", "Unit");
                prop.SetProperty("UnitID", quantity.Unit.ID, true, "ID of this unit.", "Unit");
            }
            else if (obj is IElementSet)
            {
                IElementSet elementSet = (IElementSet)obj;
                prop = new PropertyManager();

                // General
                prop.SetProperty("ID", elementSet.ID, true, "ID of this ElementSet", "General");
                prop.SetProperty("Version", elementSet.Version.ToString(), true, "Version of this ElementSet.", "General");
                prop.SetProperty("SpatialReferenceID", elementSet.SpatialReference.ID, true, "ID of this ElementSet's SpatialReference", "General");
                prop.SetProperty("Description", elementSet.Description, true, "Description of this ElementSet.", "General");
                prop.SetProperty("ElementCount", elementSet.ElementCount.ToString(), true, "Count of elements of this ElementSet.", "General");
                prop.SetProperty("ElementType", elementSet.ElementType.ToString(), true, "Type of elements in this ElementSet.", "General");
            }
            else if (obj is IDataOperation)
            {
                IDataOperation dataOperation = (IDataOperation)obj;
                prop = new PropertyManager();

                string DataOperationID = "DataOperationID";

                // small trick to avoid that some argument's name is same as DataOperationID.
                // it's not quite pure, but it works:-)
                bool conflict;
                do
                {
                    conflict = false;
                    for (int i = 0; i < dataOperation.ArgumentCount; i++)
                    {
                        if (dataOperation.GetArgument(i).Key == DataOperationID)
                        {
                            DataOperationID += " ";
                            conflict         = true;
                            break;
                        }
                    }
                }while(conflict);

                // General
                prop.SetProperty(DataOperationID, dataOperation.ID, true, "ID of this DataOperation", "General");

                // Arguments
                for (int i = 0; i < dataOperation.ArgumentCount; i++)
                {
                    IArgument arg = dataOperation.GetArgument(i);
                    prop.SetProperty(arg.Key, arg.Value, arg.ReadOnly || allReadOnly, arg.Description, "Arguments");
                }
            }
            else if (obj is ILinkableComponent)
            {
                ILinkableComponent linkableComponent = (ILinkableComponent)obj;
                prop = new PropertyManager();

                DateTime
                    timeHorizonStart  = CalendarConverter.ModifiedJulian2Gregorian(linkableComponent.TimeHorizon.Start.ModifiedJulianDay),
                    timeHorizonEnd    = CalendarConverter.ModifiedJulian2Gregorian(linkableComponent.TimeHorizon.End.ModifiedJulianDay),
                    earliestInputTime = CalendarConverter.ModifiedJulian2Gregorian(linkableComponent.EarliestInputTime.ModifiedJulianDay);

                // General
                prop.SetProperty("ComponentID", linkableComponent.ComponentID, true, "ID the component.", "General");
                prop.SetProperty("ComponentDescription", linkableComponent.ComponentDescription, true, "Description of this component.", "General");
                prop.SetProperty("InputExchangeItemCount", linkableComponent.InputExchangeItemCount.ToString(), true, "Number of input exchange items.", "General");
                prop.SetProperty("OutputExchangeItemCount", linkableComponent.OutputExchangeItemCount.ToString(), true, "Number of output exchange items.", "General");
                prop.SetProperty("ModelID", linkableComponent.ModelID, true, "ID of the model (model=component+data).", "General");
                prop.SetProperty("ModelDescription", linkableComponent.ModelDescription, true, "Description of the model.", "General");
                prop.SetProperty("TimeHorizonStart", timeHorizonStart.ToString(), true, "Start of component's timehorizon.", "General");
                prop.SetProperty("TimeHorizonEnd", timeHorizonEnd.ToString(), true, "End of component's timehorizon.", "General");
                prop.SetProperty("ValidationMessage", linkableComponent.Validate(), true, "Validation string generated by component. No error ocured if it's empty.", "General");
                prop.SetProperty("EarliestInputTime", earliestInputTime.ToString(), true, "Earliest time for which component needs next input.", "General");

                string implementsIManageState = obj is IManageState ? "yes" : "no";
                prop.SetProperty("ImplementsIManageState", implementsIManageState, true, "Describes whether model implements IManageState interface.", "General");
            }

            if (prop != null)
            {
                prop.Tag = obj;
            }

            return(prop);
        }
        public static ILink CreateLink(ILinkableComponent sourceComponent, string sourceQuantityID, string sourceElementSetID, ILinkableComponent targetComponent, string targetQuantityID, string targetElementSetID, string[] dataOperationIDs)
        {
            string linkID = sourceComponent.ComponentID + "(" + sourceQuantityID + ", " + sourceElementSetID + ") to " + targetComponent.ComponentID + "(" + targetQuantityID + ", " + targetElementSetID + ")";

            int outputExchangeItemIndex = -1;
            for (int i = 0; i < sourceComponent.OutputExchangeItemCount; i++)
            {
                if (sourceComponent.GetOutputExchangeItem(i).Quantity.ID == sourceQuantityID && sourceComponent.GetOutputExchangeItem(i).ElementSet.ID == sourceElementSetID)
                {
                    outputExchangeItemIndex = i;
                }
            }

            if (outputExchangeItemIndex < 0)
            {
                throw new Exception("Exception in LinkFactory.CreateLink, failed to find output exchange item for " + sourceQuantityID + ", " + sourceElementSetID + " during creation of link: " + linkID);
            }

            int inputExchangeItemIndex = -1;
            for (int i = 0; i < targetComponent.InputExchangeItemCount; i++)
            {
                if (targetComponent.GetInputExchangeItem(i).Quantity.ID == targetQuantityID && targetComponent.GetInputExchangeItem(i).ElementSet.ID == targetElementSetID)
                {
                    inputExchangeItemIndex = i;
                }
            }

            if (inputExchangeItemIndex < 0)
            {
                throw new Exception("Exception in LinkFactory.CreateLink, failed to find input exchange item for " + targetQuantityID + ", " + targetElementSetID + " during creation of link: " + linkID);
            }


            Link link = new Link();
            link.ID = linkID;
            link.Description = linkID;
            link.SourceComponent = sourceComponent;
            link.SourceQuantity = sourceComponent.GetOutputExchangeItem(outputExchangeItemIndex).Quantity;
            link.SourceElementSet = sourceComponent.GetOutputExchangeItem(outputExchangeItemIndex).ElementSet;
            link.TargetComponent = targetComponent;
            link.TargetQuantity = targetComponent.GetInputExchangeItem(inputExchangeItemIndex).Quantity;
            link.TargetElementSet = targetComponent.GetInputExchangeItem(inputExchangeItemIndex).ElementSet;

            bool dataOperationWasFound = false;

            for (int n = 0; n < dataOperationIDs.Length; n++)
            {
                dataOperationWasFound = false;
                for (int i = 0; i < sourceComponent.GetOutputExchangeItem(outputExchangeItemIndex).DataOperationCount; i++)
                {
                    if (sourceComponent.GetOutputExchangeItem(outputExchangeItemIndex).GetDataOperation(i).ID == dataOperationIDs[n])
                    {
                        link.AddDataOperation(sourceComponent.GetOutputExchangeItem(outputExchangeItemIndex).GetDataOperation(i));
                        dataOperationWasFound = true;
                    }
                }
                if (!dataOperationWasFound)
                {
                    throw new Exception("failed to find dataOperation: " + dataOperationIDs[n] + " during creation of link: " + linkID);
                }
            }

            return (ILink)link;
        }
Beispiel #26
0
        void RunProgress(object sender, ProgressChangedEventArgs e)
        {
            lock (this)
            {
                if (e.UserState != null &&
                    (e.UserState is CompositionRun.State))
                {
                    CompositionRun.State state
                        = (CompositionRun.State)e.UserState;

                    DataGridViewCell cellComponent = _table.Cell(Table.EColumns.Component, state.OprIndex, dataGridView1);

                    // Status

                    DataGridViewCell cellStatus = _table.Cell(Table.EColumns.Status, state.OprIndex, dataGridView1);

                    ILinkableComponent iLC = state.StatusArgs != null
                                                ? state.StatusArgs.LinkableComponent
                                                : state.ExchangeArgs.ExchangeItem.Component;

                    cellStatus.Value = iLC != null?iLC.Status.ToString() : "";

                    dataGridView1.InvalidateCell(cellStatus);

                    // Changes Count

                    DataGridViewCell cellChanges = _table.Cell(Table.EColumns.Events, state.OprIndex, dataGridView1);

                    cellChanges.Value = (int)cellChanges.Value + 1;
                    dataGridView1.InvalidateCell(cellChanges);

                    // Changed Time

                    DataGridViewCell cellChanged = _table.Cell(Table.EColumns.Changed, state.OprIndex, dataGridView1);
                    cellChanged.Value = state.LastEventUpdate;
                    dataGridView1.InvalidateCell(cellChanged);

                    // Changed Progress

                    int?progress = state.Progress;

                    if (progress != null)
                    {
                        DataGridViewCell cellProgress = _table.Cell(Table.EColumns.Progress, state.OprIndex, dataGridView1);
                        cellProgress.Value = progress.Value;
                        dataGridView1.InvalidateCell(cellProgress);

                        if (state.OprIndex == _nOprIndexTrigger &&
                            progressBar1.Value != progress.Value)
                        {
                            progressBar1.Value = progress.Value;
                            progressBar1.Invalidate();

                            UpdateTitleText(progress);

                            _timeSpan = DateTime.Now - _startTime;

                            string elapsed = string.Format("{0},{1},{2}.{3}",
                                                           _timeSpan.Hours, _timeSpan.Minutes,
                                                           _timeSpan.Seconds, _timeSpan.Milliseconds);

                            labelMessage.Text = string.Format("Running [{0}%]\r\nElapsed {1}",
                                                              progress.Value, elapsed);
                        }
                    }

                    dataGridView1.Refresh();

                    _logCache.Add(state);
                }
            }
        }
Beispiel #27
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="SourceComponent">The source component</param>
		/// <param name="SourceElementSet">The source element set</param>
		/// <param name="SourceQuantity">The source quantity</param>
		/// <param name="TargetComponent">The target component</param>
		/// <param name="TargetElementSet">The target element set</param>
		/// <param name="TargetQuantity">The target quantity</param>
		/// <param name="Description">The description</param>
		/// <param name="ID">The ID</param>
		/// <param name="DataOperations">Data operations to be carried out by the provider</param>
		public Link(ILinkableComponent SourceComponent,
			IElementSet SourceElementSet,
			IQuantity SourceQuantity,
			ILinkableComponent TargetComponent,
			IElementSet TargetElementSet,
			IQuantity TargetQuantity,
			string Description,
			string ID,
			ArrayList DataOperations)
		{
			_sourceComponent = SourceComponent;
			_sourceElementSet = SourceElementSet;
			_sourceQuantity = SourceQuantity;
			_targetComponent = TargetComponent;
			_targetElementSet = TargetElementSet;
			_targetQuantity = TargetQuantity;
			_description = Description;
			_id = ID;
			_dataOperations = DataOperations;
		}
Beispiel #28
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="SourceComponent">The source component</param>
		/// <param name="SourceElementSet">The source element set</param>
		/// <param name="SourceQuantity">The source quantity</param>
		/// <param name="TargetComponent">The target component</param>
		/// <param name="TargetElementSet">The target element set</param>
		/// <param name="TargetQuantity">The target quantity</param>
		/// <param name="ID">The ID</param>
		public Link(ILinkableComponent SourceComponent,
			IElementSet SourceElementSet,
			IQuantity SourceQuantity,
			ILinkableComponent TargetComponent,
			IElementSet TargetElementSet,
			IQuantity TargetQuantity,
			string ID)
		{
			_sourceComponent = SourceComponent;
			_sourceElementSet = SourceElementSet;
			_sourceQuantity = SourceQuantity;
			_targetComponent = TargetComponent;
			_targetElementSet = TargetElementSet;
			_targetQuantity = TargetQuantity;
			_description = Description;
			_id = ID;
		}
Beispiel #29
0
		/// <summary>
		/// Sets this model according to OMI file.
		/// </summary>
		/// <param name="filename">Relative or absolute path to OMI file describing the model.</param>
		/// <param name="relativeDirectory">Directory <c>filename</c> is relative to, or <c>null</c> if <c>filename</c> is absolute or relative to current directory.</param>
		/// <remarks>See <see cref="Utils.GetFileInfo">Utils.GetFileInfo</see> for more info about how
		/// specified file is searched.</remarks>	
		public void ReadOMIFile( string relativeDirectory, string filename )
		{
			// Open OMI file as xmlDocument
			FileInfo omiFileInfo = Utils.GetFileInfo( relativeDirectory, filename );
			if( !omiFileInfo.Exists )
				throw( new Exception("Omi file not found (CurrentDirectory='"+Directory.GetCurrentDirectory()+"', File='"+filename+"')") );

			XmlDocument xmlDocument = new XmlDocument();
			xmlDocument.Load( omiFileInfo.FullName );

			// get 1st LinkableComponent element
			XmlElement xmlLinkableComponent = null;
			foreach( XmlNode node in xmlDocument.ChildNodes )
				if( node.Name=="LinkableComponent" )
				{
					xmlLinkableComponent = (XmlElement)node;
					break;
				}

			// load assembly if present (from relative location of the OMI file)
			if (xmlLinkableComponent == null)
			{
				throw new Exception("No linkable components found in composition file " + omiFileInfo);
			}
			else
			{
				string assemblyFilename = xmlLinkableComponent.GetAttribute("Assembly");
				if (assemblyFilename != null)
					AssemblySupport.LoadAssembly(omiFileInfo.DirectoryName, assemblyFilename);
			}

			// read arguments
			ArrayList linkableComponentArguments = new ArrayList();

			foreach( XmlElement xmlArguments in xmlLinkableComponent.ChildNodes )
				if( xmlArguments.Name == "Arguments" )
					foreach( XmlElement xmlArgument in xmlArguments.ChildNodes )
						linkableComponentArguments.Add( new Argument(xmlArgument.GetAttribute("Key"), xmlArgument.GetAttribute("Value"), true, "No description"));

			// get new instance of ILinkableComponent type
			// for this moment set current directory to omi file's directory
			string oldDirectory = Directory.GetCurrentDirectory(); 
			try 
			{
				Directory.SetCurrentDirectory( omiFileInfo.DirectoryName );

				string classTypeName = xmlLinkableComponent.GetAttribute("Type");
				object obj = AssemblySupport.GetNewInstance( classTypeName );
				if ( ! ( obj is ILinkableComponent ) )
				{
					throw new Exception("\n\nThe class type " + classTypeName + " in\n" +
						filename +
						"\nis not an OpenMI.Standard.ILinkableComponent (OpenMI.Standard.dll version 1.4.0.0)." +
						"\nYou may have specified a wrong class name, " +
						"\nor the class implements the ILinkableComponent interface of a previous version of the OpenMI Standard.\n");
				}
				_linkableComponent = (ILinkableComponent)obj;
				_linkableComponent.Initialize( (IArgument[])linkableComponentArguments.ToArray(typeof(IArgument)) );
			}
			finally
			{
				Directory.SetCurrentDirectory( oldDirectory );
			}

			_omiFilename = omiFileInfo.FullName;
			
			_modelID = _linkableComponent.ModelID;

			// remote components have rectangle style
			string componentDescription = _linkableComponent.ComponentDescription;
			if( componentDescription != null )
				if( componentDescription.IndexOf( "OpenMI.Distributed" ) >= 0 )				
					_rectanglePen.DashStyle = DashStyle.Dash;
		}
Beispiel #30
0
        public override IValueSet GetValues(IExchangeItem querySpecifier)
        {
            if (querySpecifier.TimeSet == null || querySpecifier.TimeSet.Times == null ||
                querySpecifier.TimeSet.Times.Count == 0)
            {
                throw new Exception("Invalid query specifier \"" + querySpecifier.Id +
                                    "\" for in GetValues() call to time decorater " + Id);
            }
            if (ParentOutput.TimeSet == null || ParentOutput.TimeSet.Times == null)
            {
                throw new Exception("Invalid time specifier in decorated output item \"" + ParentOutput.Id +
                                    "\" for in GetValues() call to time decorater " + Id);
            }

            // Determinee query time and currently available time
            double queryTimeAsMJD =
                querySpecifier.TimeSet.Times[querySpecifier.TimeSet.Times.Count - 1].StampAsModifiedJulianDay +
                querySpecifier.TimeSet.Times[querySpecifier.TimeSet.Times.Count - 1].DurationInDays;
            double        availableTimeAsMJD       = Double.NegativeInfinity;
            IList <ITime> decoratedOutputItemTimes = ParentOutput.TimeSet.Times;

            if (decoratedOutputItemTimes.Count > 0)
            {
                availableTimeAsMJD =
                    decoratedOutputItemTimes[decoratedOutputItemTimes.Count - 1].StampAsModifiedJulianDay +
                    decoratedOutputItemTimes[decoratedOutputItemTimes.Count - 1].DurationInDays;
            }

            // Update as far as needed.
            ILinkableComponent linkableComponent = ParentOutput.Component;

            while ((linkableComponent.Status == LinkableComponentStatus.Valid ||
                    linkableComponent.Status == LinkableComponentStatus.Updated) &&
                   availableTimeAsMJD < queryTimeAsMJD)
            {
                linkableComponent.Update();
                // Determine newly available time
                decoratedOutputItemTimes = ParentOutput.TimeSet.Times;
                availableTimeAsMJD       =
                    decoratedOutputItemTimes[decoratedOutputItemTimes.Count - 1].StampAsModifiedJulianDay +
                    decoratedOutputItemTimes[decoratedOutputItemTimes.Count - 1].DurationInDays;
            }

            // Return the values for the required time(s)
            IList <IList <double> > resultValues = new List <IList <double> >();

            if (querySpecifier.TimeSet != null && querySpecifier.TimeSet.Times != null)
            {
                for (int t = 0; t < querySpecifier.TimeSet.Times.Count; t++)
                {
                    resultValues.Add(new List <double>());
                    ITime         queryTime         = querySpecifier.TimeSet.Times[t];
                    List <double> valuesForTimeStep = _buffer.GetValues(queryTime);
                    foreach (double d in valuesForTimeStep)
                    {
                        resultValues[t].Add(d);
                    }
                }
            }
            return(new ValueSet <double>(resultValues));
        }
Beispiel #31
0
 private bool isModelEngineComponent(ILinkableComponent component)
 {
     return typeof(LinkableRunEngine).IsAssignableFrom(component.GetType());
 }
Beispiel #32
0
 public TestEngine(ILinkableComponent myLinkableComponent)
 {
     this.myLinkableComponent = myLinkableComponent;
     modelId = "TestEngineComponentID";
 }
 public BufferedOutputItem(string id, IValueDefinition quantity, IElementSet elementSet, ILinkableComponent component) : base(id, quantity, elementSet)
 {
     Component = component;
 }
Beispiel #34
0
        public static ILink CreateLink(ILinkableComponent sourceComponent, string sourceQuantityID, string sourceElementSetID, ILinkableComponent targetComponent, string targetQuantityID, string targetElementSetID, string[] dataOperationIDs)
        {
            string linkID = sourceComponent.ComponentID + "(" + sourceQuantityID + ", " + sourceElementSetID + ") to " + targetComponent.ComponentID + "(" + targetQuantityID + ", " + targetElementSetID + ")";

            int outputExchangeItemIndex = -1;

            for (int i = 0; i < sourceComponent.OutputExchangeItemCount; i++)
            {
                if (sourceComponent.GetOutputExchangeItem(i).Quantity.ID == sourceQuantityID && sourceComponent.GetOutputExchangeItem(i).ElementSet.ID == sourceElementSetID)
                {
                    outputExchangeItemIndex = i;
                }
            }

            if (outputExchangeItemIndex < 0)
            {
                throw new Exception("Exception in LinkFactory.CreateLink, failed to find output exchange item for " + sourceQuantityID + ", " + sourceElementSetID + " during creation of link: " + linkID);
            }

            int inputExchangeItemIndex = -1;

            for (int i = 0; i < targetComponent.InputExchangeItemCount; i++)
            {
                if (targetComponent.GetInputExchangeItem(i).Quantity.ID == targetQuantityID && targetComponent.GetInputExchangeItem(i).ElementSet.ID == targetElementSetID)
                {
                    inputExchangeItemIndex = i;
                }
            }

            if (inputExchangeItemIndex < 0)
            {
                throw new Exception("Exception in LinkFactory.CreateLink, failed to find input exchange item for " + targetQuantityID + ", " + targetElementSetID + " during creation of link: " + linkID);
            }


            Link link = new Link();

            link.ID               = linkID;
            link.Description      = linkID;
            link.SourceComponent  = sourceComponent;
            link.SourceQuantity   = sourceComponent.GetOutputExchangeItem(outputExchangeItemIndex).Quantity;
            link.SourceElementSet = sourceComponent.GetOutputExchangeItem(outputExchangeItemIndex).ElementSet;
            link.TargetComponent  = targetComponent;
            link.TargetQuantity   = targetComponent.GetInputExchangeItem(inputExchangeItemIndex).Quantity;
            link.TargetElementSet = targetComponent.GetInputExchangeItem(inputExchangeItemIndex).ElementSet;

            bool dataOperationWasFound = false;

            for (int n = 0; n < dataOperationIDs.Length; n++)
            {
                dataOperationWasFound = false;
                for (int i = 0; i < sourceComponent.GetOutputExchangeItem(outputExchangeItemIndex).DataOperationCount; i++)
                {
                    if (sourceComponent.GetOutputExchangeItem(outputExchangeItemIndex).GetDataOperation(i).ID == dataOperationIDs[n])
                    {
                        link.AddDataOperation(sourceComponent.GetOutputExchangeItem(outputExchangeItemIndex).GetDataOperation(i));
                        dataOperationWasFound = true;
                    }
                }
                if (!dataOperationWasFound)
                {
                    throw new Exception("failed to find dataOperation: " + dataOperationIDs[n] + " during creation of link: " + linkID);
                }
            }

            return((ILink)link);
        }
Beispiel #35
0
			public EventCopy( IEvent theEvent )
			{
				_description = theEvent.Description;
				_type = theEvent.Type;
				_sender = theEvent.Sender;
				if( theEvent.SimulationTime == null )
					_simulationTime = null;
				else
					_simulationTime = new TimeStamp( theEvent.SimulationTime );
			}
Beispiel #36
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="type">Event type</param>
 /// <param name="sender"> Sender of the event</param>
 /// <param name="description">Description for the event</param>
 public Event(EventType type, ILinkableComponent sender, string description)
 {
     _type = type;
     _sender = sender;
     _description = description;
 }
 public SimpleComponent()
 {
     component = this;
 }
 public Engine(ILinkableComponent component)
 {
     this.component = component;
 }