public InputSpatialSurrogate(ITimeSpaceInput input)
        {
            _inputOriginal = input;

            if (input == null)
            {
                SetDescribes(new Describes("Unspecified Input"));
                ValueDefinition = new ValueDefinition();
                SpatialDefinition = new SpatialDefinition();
                Component = null;
            }
            else
            {
                SetDescribes(input);

                ValueDefinition = input.ValueDefinition;
                Component = input.Component;

                var inputTime = input as BaseInputSpaceTime;

                SpatialDefinition = inputTime != null
                    ? inputTime.SpatialDefinition
                    : new SpatialDefinition();
            }
        }
Exemplo n.º 2
0
 public ExchangeItem(IBaseExchangeItem openMIItem, bool useBufferedValues)
 {
     if (openMIItem is ITimeSpaceOutput)
     {
         _openMIItem = _openMIOutputItem = (ITimeSpaceOutput)openMIItem;
     }
     else if (openMIItem is ITimeSpaceInput)
     {
         _openMIItem = _openMIInputItem = (ITimeSpaceInput)openMIItem;
     }
     else
     {
         throw new Exception("Unknown exchange item type: " + openMIItem.GetType());
     }
     if (_openMIItem.TimeSet != null && _openMIItem.TimeSet.HasDurations)
     {
         throw new Exception("\"" + Id + ": OpenDA Time Spans not covered by OpenDA Exchange items");
     }
     _useBufferedValues = useBufferedValues;
     if (_useBufferedValues)
     {
         _bufferedValues = new List <List <double> > {
             new List <double>()
         };
         _bufferedTimes = new List <double>();
     }
 }
Exemplo n.º 3
0
        public static IIdentifiable[] GetAvailableMethods(IBaseOutput adaptee, IBaseInput target)
        {
            ITimeSpaceOutput tsadaptee = adaptee as ITimeSpaceOutput;

            // Only works with timespace output as adaptee, and element set as spatial definition
            if (tsadaptee == null || !(tsadaptee.SpatialDefinition is IElementSet))
            {
                return(new IIdentifiable[0]);
            }

            IList <IIdentifiable> methods = new List <IIdentifiable>();

            GetAvailableOperationMethods(ref methods, tsadaptee.ElementSet().ElementType);

            // Check if the target is there and is a timespace input
            ITimeSpaceInput tstarget = target as ITimeSpaceInput;

            if (target == null || tstarget == null || !(tstarget.SpatialDefinition is IElementSet))
            {
                return(((List <IIdentifiable>)methods).ToArray());
            }

            GetAvailableMappingMethods(ref methods, tsadaptee.ElementSet().ElementType, tstarget.ElementSet().ElementType);

            return(((List <IIdentifiable>)methods).ToArray());
        }
 public static bool ConsumerCanBeAdded(IList<ITimeSpaceInput> existingConsumers, ITimeSpaceInput consumer)
 {
     bool canBeAdded = true;
     if (existingConsumers.Count > 0)
     {
         // TODO (JG): make instead check on exchangeItem.ElementSet instead of an arbitray elementSet
         // check if #elements are consistent
         if (consumer.ElementSet() != null &&
             existingConsumers[0].ElementSet() != null &&
             consumer.ElementSet().ElementCount != existingConsumers[0].ElementSet().ElementCount
             )
         {
             canBeAdded = false;
         }
         // TODO (JG): Is this a requirement?
         if (consumer.TimeSet != null &&
             existingConsumers[0].TimeSet != null &&
             consumer.TimeSet.HasDurations != existingConsumers[0].TimeSet.HasDurations
             )
         {
             canBeAdded = false;
         }
         // check if #time stamps are consistent
     }
     return canBeAdded;
 }
Exemplo n.º 5
0
 public void AddIn(IBaseExchangeItem openMIo)
 {
     if (openMIo is ITimeSpaceInput)
     {
         _openMIItem = _openMIInputItem = (ITimeSpaceInput)openMIo;
     }
 }
Exemplo n.º 6
0
        public void CreatePolygon2PointAdaptedOutput2Consumers()
        {
            ITimeSpaceOutput adaptee = new Output(xyPolygon.Caption + ".Flow")
            {
                SpatialDefinition = xyPolygon, ValueDefinition = waterLevelQuantity
            };
            ITimeSpaceInput consumerA = new Input(xyPointA.Caption + ".Flow")
            {
                SpatialDefinition = xyPointA, ValueDefinition = waterLevelQuantity
            };
            ITimeSpaceInput consumerB = new Input(xyPointB.Caption + ".Flow")
            {
                SpatialDefinition = xyPointB, ValueDefinition = waterLevelQuantity
            };

            ITimeSpaceInput consumer = consumerB;

            IIdentifiable           selectedAvailableAdaptedOutputId = adaptedOutputFactory.GetAvailableAdaptedOutputIds(adaptee, consumer)[1];
            ITimeSpaceAdaptedOutput adaptedOutput = (ITimeSpaceAdaptedOutput)adaptedOutputFactory.CreateAdaptedOutput(selectedAvailableAdaptedOutputId, adaptee, consumer);

            adaptedOutput.AddConsumer(consumer);

            Assert.IsTrue(adaptedOutput.ElementSet().ElementType == ElementType.Point, "Consumer's ElementSet TYPE");
            Assert.AreEqual(2, adaptedOutput.ElementSet().ElementCount, "ElementSet of consumer");
            Assert.IsTrue(adaptedOutput.ValueDefinition == adaptee.ValueDefinition, "Adaptee's ValueDefinition");
        }
        public virtual void AddConsumer(IBaseInput consumer)
        {
            ITimeSpaceInput timeSpaceConsumer = consumer as ITimeSpaceInput;

            if (timeSpaceConsumer == null)
            {
                throw new ArgumentException("Must be a ITimeSpaceInput - may need to add adaptor");
            }

            // Create list of consumers
            if (_consumers == null)
            {
                _consumers = new List <ITimeSpaceInput>();
            }

            // consumer should not be already added
            if (_consumers.Contains(timeSpaceConsumer))
            {
                //throw new Exception("consumer \"" + consumer.Caption +
                //    "\" has already been added to \"" + Caption);
            }
            else
            {
                _consumers.Add(timeSpaceConsumer);
                if (consumer.Provider != this)
                {
                    consumer.Provider = this;
                }
            }
        }
Exemplo n.º 8
0
 protected DecoratorBase(IIdentifiable identifiable, string caption, string description, ITimeSpaceOutput decorated, ITimeSpaceInput target)
 {
     _identifiable = identifiable;
     _description  = description;
     _caption      = caption;
     _decorated    = decorated;
     _target       = target;
 }
Exemplo n.º 9
0
 public Input(ITimeSpaceInput iInput)
     : base(iInput)
 {
     if (iInput.Provider != null)
     {
         _provider = iInput.Provider.Caption;
     }
 }
Exemplo n.º 10
0
        private static void ConnectItems(ITimeSpaceComponent sourceComponentInstance, string outputItemId,
                                         ITimeSpaceComponent targetComponentInstance, string inputItemId)
        {
            ITimeSpaceOutput output = FindOutputItem(sourceComponentInstance, outputItemId);
            ITimeSpaceInput  input  = FindInputItem(targetComponentInstance, inputItemId);

            output.AddConsumer(input);
        }
Exemplo n.º 11
0
    public void CreateInitializeTest()
    {
      ITimeSpaceComponent gwModel = new GWModelLC();
      IBaseLinkableComponent lc = gwModel;
      Assert.IsTrue(gwModel.Status == LinkableComponentStatus.Created);

      List<IArgument> gwArguments = CreateTestArguments();

      gwModel.Arguments.ApplyArguments(gwArguments);
      gwModel.Initialize();
      Assert.IsTrue(gwModel.Status == LinkableComponentStatus.Initialized);
      Assert.AreEqual("GWModelLC", gwModel.Id);

      Assert.AreEqual(3, gwModel.Inputs.Count);
      Assert.AreEqual(3, gwModel.Outputs.Count);

      {
        // Check the ground water level output
        ITimeSpaceOutput gwLevel = lc.Outputs[2] as ITimeSpaceOutput;
        Assert.IsNotNull(gwLevel);
        Assert.AreEqual("Grid.gwLevel", gwLevel.Id);

        // Check quantity
        IQuantity quantity = gwLevel.ValueDefinition as IQuantity;
        Assert.IsNotNull(quantity);
        Assert.AreEqual("Ground water level", quantity.Caption);
        Assert.AreEqual("gw level", quantity.Unit.Caption);
        Assert.AreEqual(1, quantity.Unit.Dimension.GetPower(DimensionBase.Length));
        Assert.AreEqual(0, quantity.Unit.Dimension.GetPower(DimensionBase.Time));
        Assert.AreEqual(1, quantity.Unit.ConversionFactorToSI);

        // Check element set
        IElementSet gridSet = gwLevel.ElementSet();
        CheckRegularGridElmtSet(gridSet);

      }

      {
        // Check the ground water inflow input
        ITimeSpaceInput gwInput = lc.Inputs[2] as ITimeSpaceInput;
        Assert.IsNotNull(gwInput);
        Assert.AreEqual("Grid.Inflow", gwInput.Id);

        // Check quantity
        IQuantity quantity = gwInput.ValueDefinition as IQuantity;
        Assert.IsNotNull(quantity);
        Assert.AreEqual("Inflow", quantity.Caption);
        Assert.AreEqual("Discharge", quantity.Unit.Caption);
        Assert.AreEqual(3, quantity.Unit.Dimension.GetPower(DimensionBase.Length));
        Assert.AreEqual(-1, quantity.Unit.Dimension.GetPower(DimensionBase.Time));
        Assert.AreEqual(0.001, quantity.Unit.ConversionFactorToSI);

        // Check element set
        IElementSet gridSet = gwInput.ElementSet();
        CheckRegularGridElmtSet(gridSet);
      }

    }
Exemplo n.º 12
0
 public DecoratorWave(IIdentifiable identifiable, ITimeSpaceOutput decorated, ITimeSpaceInput target)
     : base(identifiable, "Wave: A*sin(F*t + P)",
            "Wave transformation y = Amplitude * sin(frequancy * time + phase)",
            decorated, target)
 {
     _arguments.Add(Argument.Create("Amplitude", "0.0", false, "A in A*sin(F*t + P)"));
     _arguments.Add(Argument.Create("Phase", "0.0", false, "P in y = A*sin(F*t + P)"));
     _arguments.Add(Argument.Create("Frequency", "0.0", false, "F in y = A*sin(F*t + P)"));
 }
Exemplo n.º 13
0
 public AddapterBase(IIdentifiable identifier, IDescribable described, ITimeSpaceOutput adapted, ITimeSpaceInput target)
 {
     _identifier = identifier;
     _described  = described;
     _target     = target;
     _adapted    = adapted;
     if (!_adapted.AdaptedOutputs.Contains(this))
     {
         _adapted.AddAdaptedOutput(this);
     }
 }
Exemplo n.º 14
0
        private static void ConnectItemsWithTimeInterpolator(ITimeSpaceComponent sourceComponentInstance,
                                                             string outputItemId,
                                                             ITimeSpaceComponent targetComponentInstance, string inputItemId)
        {
            ITimeSpaceOutput      output = FindOutputItem(sourceComponentInstance, outputItemId);
            ITimeSpaceInput       input  = FindInputItem(targetComponentInstance, inputItemId);
            IAdaptedOutputFactory derivedOutputFactory = sourceComponentInstance.AdaptedOutputFactories[0];

            IIdentifiable[]    derivedOutputIdentifiers = derivedOutputFactory.GetAvailableAdaptedOutputIds(output, input);
            IBaseAdaptedOutput timeInterpolator         = derivedOutputFactory.CreateAdaptedOutput(derivedOutputIdentifiers[0], output, input);
        }
Exemplo n.º 15
0
        public static void ConnectItemsUsingAdaptedOutput(ITimeSpaceComponent sourceComponentInstance,
                                                          string outputItemId,
                                                          ITimeSpaceComponent targetComponentInstance,
                                                          string inputItemId,
                                                          string derivedOutputName)
        {
            ITimeSpaceOutput output = FindOutputItem(sourceComponentInstance, outputItemId);
            ITimeSpaceInput  input  = FindInputItem(targetComponentInstance, inputItemId);

            ConnectItemsUsingAdaptedOutput(sourceComponentInstance, output, input, derivedOutputName);
        }
Exemplo n.º 16
0
        public static ITimeSpaceAdaptedOutput CreateAdaptedOutputMethod(IIdentifiable adaptedOutputId, IBaseOutput adaptee, IBaseInput target)
        {
            IElementSet     elmtSet  = null;
            ITimeSpaceInput tsTarget = target as ITimeSpaceInput;

            if (tsTarget != null && tsTarget.SpatialDefinition is IElementSet)
            {
                elmtSet = tsTarget.ElementSet();
            }

            return(CreateAdaptedOutputMethod(adaptedOutputId, adaptee, elmtSet));
        }
Exemplo n.º 17
0
        public virtual void RemoveConsumer(IBaseInput consumer)
        {
            ITimeSpaceInput timeSpaceConsumer = consumer as ITimeSpaceInput;

            if (timeSpaceConsumer == null || _consumers == null || !_consumers.Contains(timeSpaceConsumer))
            {
                throw new Exception("consumer \"" + consumer.Caption +
                                    "\" can not be removed from \"" + Caption +
                                    "\", because it was not added");
            }
            _consumers.Remove(timeSpaceConsumer);
            consumer.Provider = null;
        }
Exemplo n.º 18
0
        public virtual void AddConsumer(IBaseInput consumer)
        {
            ITimeSpaceInput timeSpaceConsumer = consumer as ITimeSpaceInput;

            if (timeSpaceConsumer == null)
            {
                throw new ArgumentException("Must be a ITimeSpaceInput - may need to add adaptor");
            }

            // Create list of consumers
            if (_consumers == null)
            {
                _consumers = new List <ITimeSpaceInput>();
            }

            // consumer should not be already added
            if (_consumers.Contains(timeSpaceConsumer))
            {
                throw new Exception("consumer \"" + consumer.Caption +
                                    "\" has already been added to \"" + Caption);
            }

            // Check if this consumer can be added
            if (!ExchangeItemHelper.ConsumerCanBeAdded(_consumers, timeSpaceConsumer))
            {
                throw new Exception("consumer \"" + consumer.Caption +
                                    "\" can not be added to \"" + Caption +
                                    "\", because it is incompatible with existing consumers");
            }

            _consumers.Add(timeSpaceConsumer);


            if (consumer.Provider != this)
            {
                consumer.Provider = this;
            }
            //// TODO (JG): EXPERIMENTAL CODE
            //if (consumer is IBaseMultiInput)
            //{
            //    ((IBaseMultiInput)consumer).AddProvider(this);
            //}
            //else
            //{
            //    if (consumer.Provider != this)
            //    {
            //        consumer.Provider = this;
            //    }
            //}
        }
Exemplo n.º 19
0
        private void LogIncomingValues(ITimeSpaceInput inputItem, ITimeSpaceValueSet providedValues)
        {
            string message = Caption + " " + inputItem.Caption + " values:";

            foreach (IList valuesArray in providedValues.Values2D)
            {
                foreach (object value in valuesArray)
                {
                    message += " " + value;
                }
            }
            message += " <= " + inputItem.Provider.Caption + " from " + inputItem.Provider.Component.Caption +
                       ")";
            log.Info(message);
        }
Exemplo n.º 20
0
        private void GetExchangeItemsFromOpenMIComponent()
        {
            // ZZZ
            // Match the Input and Output Exchange Items
            foreach (IBaseInput baseInput in _openMIComponent.Inputs)
            {
                foreach (IBaseOutput baseOutput in _openMIComponent.Outputs)
                {
                    if (baseInput.Id.CompareTo(baseOutput.Id) == 0)
                    {
                        ITimeSpaceInput  timeSpaceInput  = baseInput as ITimeSpaceInput;
                        ITimeSpaceOutput timeSpaceOutput = baseOutput as ITimeSpaceOutput;

                        var IO = new ExchangeItem(timeSpaceOutput);
                        IO.AddIn(timeSpaceInput);

                        if (IO != null && !_inout.ContainsKey(timeSpaceOutput.Id))
                        {
                            _inout.Add(timeSpaceOutput.Id, IO);
                        }
                    }
                }
            }

            foreach (IBaseInput baseIn in _openMIComponent.Inputs)
            {
                ITimeSpaceInput timeSpaceIn = baseIn as ITimeSpaceInput;

                if (timeSpaceIn != null && !_inout.ContainsKey(baseIn.Id))
                {
                    _inputs.Add(timeSpaceIn.Id, new ExchangeItem(timeSpaceIn));
                }
            }
            foreach (IBaseOutput baseOut in _openMIComponent.Outputs)
            {
                ITimeSpaceOutput timeSpaceOut = baseOut as ITimeSpaceOutput;
                if (timeSpaceOut != null && !_inout.ContainsKey(baseOut.Id))
                {
                    //ZZZ
                    var I = new ExchangeItem(timeSpaceOut);
                    if (I != null)
                    {
                        _outputs.Add(timeSpaceOut.Id, I);
                    }
                }
            }
        }
Exemplo n.º 21
0
        private static bool ConsumersCompatibleForTimeAndOrElementSet(IBaseOutput outputItem, IBaseInput consumer, bool doCheckTime, bool doCheckSpace)
        {
            // Check which time/space consumers are already there
            bool canBeAdded = true;

            if (outputItem.Consumers.Count > 0)
            {
                if (doCheckSpace)
                {
                    // TODO (JG): make instead check on exchangeItem.ElementSet instead of an arbitray elementSet
                    // check if #elements are consistent
                    if (consumer.ElementSet() != null &&
                        outputItem.Consumers[0].ElementSet() != null &&
                        consumer.ElementSet().ElementCount != outputItem.Consumers[0].ElementSet().ElementCount)
                    {
                        canBeAdded = false;
                    }
                }
                if (doCheckTime)
                {
                    ITimeSpaceInput consumerAsTimeSpace = consumer as ITimeSpaceInput;
                    if (consumerAsTimeSpace != null)
                    {
                        List <ITimeSpaceInput> existingConsumers = new List <ITimeSpaceInput>();
                        foreach (IBaseInput existingConsumer in outputItem.Consumers)
                        {
                            if (existingConsumer is ITimeSpaceOutput)
                            {
                                existingConsumers.Add((ITimeSpaceInput)existingConsumer);
                            }
                        }
                        if (existingConsumers.Count > 0)
                        {
                            // TODO (JG): Is this a requirement?
                            if (consumerAsTimeSpace.TimeSet != null &&
                                existingConsumers[0].TimeSet != null &&
                                consumerAsTimeSpace.TimeSet.HasDurations != existingConsumers[0].TimeSet.HasDurations
                                )
                            {
                                canBeAdded = false;
                            }
                        }
                    }
                }
            }
            return(canBeAdded);
        }
Exemplo n.º 22
0
 /// <summary>
 /// Find the input item with the provided id.
 /// </summary>
 /// <param name="component">Component to find input item in</param>
 /// <param name="id">Id of input item to search for</param>
 /// <returns>Returns input item with id, or null if not found</returns>
 public static ITimeSpaceInput FindInputItem(this ITimeSpaceComponent component, string id)
 {
     foreach (IBaseInput input in component.Inputs)
     {
         if (string.Equals(input.Id, id, StringComparison.OrdinalIgnoreCase))
         {
             ITimeSpaceInput timeSpaceInput = input as ITimeSpaceInput;
             if (timeSpaceInput == null)
             {
                 throw new Exception("Found exchange item, but it was not a TimeSpaceInput, id = '" + id + "'");
             }
             return(timeSpaceInput);
         }
     }
     return(null);
     //throw new Exception("Could not find input item with id = '" + id + "'");
 }
Exemplo n.º 23
0
        public static ITime GetEarliestConsumerTime(IBaseOutput output)
        {
            ITime earliestRequiredTime = null;

            foreach (IBaseAdaptedOutput adaptedOutput in output.AdaptedOutputs)
            {
                earliestRequiredTime = CheckTimeHorizonMinimum(earliestRequiredTime, GetEarliestConsumerTime(adaptedOutput));
            }
            foreach (IBaseInput input in output.Consumers)
            {
                ITimeSpaceInput timeSpaceInput = input as ITimeSpaceInput;
                if (timeSpaceInput != null && timeSpaceInput.TimeSet != null)
                {
                    earliestRequiredTime = CheckTimeHorizonMinimum(earliestRequiredTime, timeSpaceInput.TimeSet.TimeHorizon);
                }
            }
            return(earliestRequiredTime);
        }
Exemplo n.º 24
0
        // Called from source
        public ITimeSpaceValueSet GetValues(IBaseExchangeItem exchange)
        {
            if (!(exchange is ITimeSpaceInput))
            {
                throw new InvalidOperationException();
            }

            ITimeSpaceInput source = (ITimeSpaceInput)exchange;

            ValidTimeSet(source.TimeSet);

            // TODO Check Component.Status befor update ? gridlock issues?
            // this.GetValues(source) should

            bool unavailable      = false;
            bool forceCacheUpdate = false;

            while (!CacheUpdateSource(source, forceCacheUpdate))
            {
                // TODO Multithreading sleep and retry
                unavailable
                    = Component.Status != LinkableComponentStatus.Initialized &&
                      Component.Status != LinkableComponentStatus.Updated &&
                      Component.Status != LinkableComponentStatus.Valid;

                if (unavailable)
                {
                    forceCacheUpdate = true;
                }
                else
                {
                    Component.Update(new ITimeSpaceOutput[] { this });
                }
            }

            if (ItemChanged != null)
            {
                ItemChanged(this, new ExchangeItemChangeEventArgs {
                    ExchangeItem = this, Message = CurrentState()
                });
            }

            return(((ITimeSpaceInput)source).Values);
        }
Exemplo n.º 25
0
        private void GetExchangeItemsFromOpenMIComponent()
        {
            string message = "";

            foreach (IBaseInput baseInput in _openMIComponent.Inputs)
            {
                ITimeSpaceInput timeSpaceInput = baseInput as ITimeSpaceInput;
                if (timeSpaceInput != null)
                {
                    if (_inputs.ContainsKey(timeSpaceInput.Id))
                    {
                        string mess = "Input item " + timeSpaceInput.Id + " defined more then once";
                        ModelFactory.AppendLogMessage(mess);
                        message += "\n" + mess;
                    }
                    else
                    {
                        _inputs.Add(timeSpaceInput.Id, new ExchangeItem(timeSpaceInput));
                    }
                }
            }
            foreach (IBaseOutput baseOutput in _openMIComponent.Outputs)
            {
                ITimeSpaceOutput timeSpaceOutput = baseOutput as ITimeSpaceOutput;
                if (timeSpaceOutput != null)
                {
                    if (_outputs.ContainsKey(timeSpaceOutput.Id))
                    {
                        string mess = "Output item " + timeSpaceOutput.Id + " defined more then once";
                        ModelFactory.AppendLogMessage(mess);
                        message += "\n" + mess;
                    }
                    else
                    {
                        _outputs.Add(timeSpaceOutput.Id, new ExchangeItem(timeSpaceOutput, true));
                    }
                }
            }
            if (message.Length > 0)
            {
                throw new Exception("Multiple Input and/or Output items:" + message);
            }
        }
Exemplo n.º 26
0
        public Linear(ITimeSpaceOutput itemOut, ITimeSpaceInput itemIn)
            : base(_identifer, _describable, itemOut, itemIn)
        {
            IArgument arg = new ArgumentDouble("A", 1.0)
            {
                Caption     = "A",
                Description = "A [double] in y = A*x + B"
            };

            _arguments.Add(arg);

            arg = new ArgumentDouble("B", 0.0)
            {
                Caption     = "B",
                Description = "B [double] in y = A*x + B"
            };

            _arguments.Add(arg);
        }
Exemplo n.º 27
0
        public IIdentifiable[] GetAvailableAdaptedOutputIds(IBaseOutput adaptee, IBaseInput target)
        {
            ITimeSpaceOutput tsadaptee = adaptee as ITimeSpaceOutput;
            ITimeSpaceInput  tstarget  = target as ITimeSpaceInput;

            // This inly works with time space items, and target can not be null
            if (tsadaptee == null || tstarget == null)
            {
                return(new IIdentifiable[0]);
            }

            // This only works with element sets
            if (!(tsadaptee.SpatialDefinition is IElementSet && tstarget.SpatialDefinition is IElementSet))
            {
                return(new IIdentifiable[0]);
            }

            return(ElementMapper.GetAvailableMethods(tsadaptee.ElementSet().ElementType, tstarget.ElementSet().ElementType));
        }
Exemplo n.º 28
0
        public virtual void AddConsumer(IBaseInput consumer)
        {
            ITimeSpaceInput timeSpaceConsumer = consumer as ITimeSpaceInput;

            if (timeSpaceConsumer == null)
            {
                throw new ArgumentException("Must be a ITimeSpaceInput - may need to add adaptor");
            }

            // Create list of consumers
            if (_consumers == null)
            {
                _consumers = new List <ITimeSpaceInput>();
            }

            // consumer should not be already added
            if (_consumers.Contains(timeSpaceConsumer))
            {
                throw new Exception("consumer \"" + consumer.Caption +
                                    "\" has already been added to \"" + Caption);
            }

            _consumers.Add(timeSpaceConsumer);


            if (consumer.Provider != this)
            {
                consumer.Provider = this;
            }
            //// TODO (JG): EXPERIMENTAL CODE
            //if (consumer is IBaseMultiInput)
            //{
            //    ((IBaseMultiInput)consumer).AddProvider(this);
            //}
            //else
            //{
            //    if (consumer.Provider != this)
            //    {
            //        consumer.Provider = this;
            //    }
            //}
        }
Exemplo n.º 29
0
        private static bool ProviderConsumerConnectableForTimeAndOrElementSet(IBaseOutput provider, IBaseInput consumer, bool doCheckTime, bool doCheckSpace)
        {
            // Check which time/space consumers are already there
            if (doCheckSpace)
            {
                // check if #elements and elementType are consistent
                if (consumer.ElementSet() != null &&
                    provider.ElementSet() != null
                    )
                {
                    if (consumer.ElementSet().ElementCount != provider.ElementSet().ElementCount)
                    {
                        return(false);
                    }
                    if (consumer.ElementSet().ElementType != provider.ElementSet().ElementType&&
                        consumer.ElementSet().ElementCount != 1)
                    {
                        return(false);
                    }
                }
            }
            if (doCheckTime)
            {
                ITimeSpaceInput consumerAsTimeSpace = consumer as ITimeSpaceInput;
                ITimeSpaceInput providerAsTimeSpace = provider as ITimeSpaceInput;
                if (consumerAsTimeSpace != null && providerAsTimeSpace != null)
                {
                    if (consumerAsTimeSpace.TimeSet != null &&
                        providerAsTimeSpace.TimeSet != null &&
                        consumerAsTimeSpace.TimeSet.HasDurations != providerAsTimeSpace.TimeSet.HasDurations)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Connect the output defined by the <paramref name="outputId"/> with the input
        /// defined by the <paramref name="inputId"/>, and put the adaptors
        /// listed by the id's <paramref name="adaptorIds"/> in between.
        /// <para>
        /// If any of the adaptors needs custom parameters, this method can not be used.
        /// </para>
        /// </summary>
        /// <param name="outputComponent">Component that has the output</param>
        /// <param name="outputId">Id of output</param>
        /// <param name="inputComponent">Component that has the input</param>
        /// <param name="inputId">Id of input</param>
        /// <param name="adaptorIds">Id of adaptors. They must be available from the output component</param>
        /// <param name="scale">If scale is different from 0, a linear operation adaptor is also added.</param>
        public static void Connect(ITimeSpaceComponent outputComponent, string outputId, ITimeSpaceComponent inputComponent, string inputId, IList <string> adaptorIds, double scale)
        {
            ITimeSpaceInput  input  = inputComponent.FindInputItem(inputId);
            ITimeSpaceOutput output = outputComponent.FindOutputItem(outputId);

            // End point of connection
            ITimeSpaceOutput leaf = output;

            // Add all adaptors
            foreach (string adaptorID in adaptorIds)
            {
                ITimeSpaceAdaptedOutput adaptor = outputComponent.FindAdaptor(adaptorID, leaf, input);
                if (adaptor == null)
                {
                    throw new Exception("Coult not find output adaptor with id: " + adaptorID);
                }
                adaptor.Initialize();
                leaf = adaptor;
            }

            // Add a linear conversion adaptor
            if (scale != 0)
            {
                ITimeSpaceAdaptedOutput adaptor = outputComponent.FindAdaptor("LinearOperation", leaf, input);
                if (adaptor == null)
                {
                    throw new Exception("Coult not find output linear conversion adaptor");
                }
                adaptor.Arguments[0].Value = scale;
                adaptor.Initialize();
                leaf = adaptor;
            }

            // Connect leaf adaptor/output to input
            leaf.AddConsumer(input);
        }
Exemplo n.º 31
0
        public override bool CacheUpdateSource(ITimeSpaceInput source, bool forceCacheUpdate)
        {
            ValidTimeSet(source.TimeSet);

            double required = source.TimeSet.Times[0].StampAsModifiedJulianDay;

            int nAbove = -1;

            for (int n = 0; n < _cache.Count; ++n)
            {
                if (_cache[n].Time > required)
                {
                    nAbove = n;
                    break;
                }
            }

            double timeRatio, extrapolated, value;

            int nValues = ValueSet.GetElementCount(source.Values);

            Debug.Assert(nValues == _initial.Values.Length);

            if (nAbove == -1)
            {
                if (!forceCacheUpdate)
                {
                    return(false);
                }

                if (_cache.Count == 0)
                {
                    for (int n = 0; n < nValues; ++n)
                    {
                        source.Values.SetValue(0, n, _initial.Values[n]);
                    }
                }
                else if (_cache.Count == 1)
                {
                    for (int n = 0; n < nValues; ++n)
                    {
                        source.Values.SetValue(0, n, _cache[0].Values[n]);
                    }
                }
                else
                {
                    DataPair prev = _cache[_cache.Count - 2];
                    DataPair last = _cache[_cache.Count - 1];

                    timeRatio = (required - prev.Time) / (last.Time - prev.Time);

                    for (int n = 0; n < nValues; ++n)
                    {
                        extrapolated = prev.Values[n] + timeRatio * (last.Values[n] - prev.Values[n]);

                        value = last.Values[n] + (1 - _relaxation) * (extrapolated - last.Values[n]);

                        source.Values.SetValue(0, n, value);
                    }
                }

                return(true);
            }

            DataPair above = _cache[nAbove];
            DataPair below = nAbove > 0 ? _cache[nAbove - 1] : _initial;

            if (below == null)
            {
                throw new NotImplementedException();
            }

            timeRatio = (required - below.Time) / (above.Time - below.Time);

            for (int n = 0; n < nValues; ++n)
            {
                value = below.Values[n] + timeRatio * (above.Values[n] - below.Values[n]);

                source.Values.SetValue(0, n, value);
            }

            return(true);
        }
Exemplo n.º 32
0
    public void InputOutputTests()
    {
      GWModelLC gwlc = new GWModelLC();
      IBaseLinkableComponent lc = gwlc;

      List<IArgument> arguments = CreateTestArguments();
      lc.Initialize(arguments);

      IElementSet elementSet = ((ITimeSpaceExchangeItem)lc.Inputs[2]).ElementSet();

      Quantity dischargeQuantity = new Quantity(new Unit(PredefinedUnits.CubicMeterPerSecond), null, "Discharge");
      Quantity waterlevelQuantity = new Quantity(new Unit(PredefinedUnits.Meter), null, "Water Level");

      ElementSet idBasedElementSetA = new ElementSet(null, "ElmSet-A", ElementType.IdBased);
      idBasedElementSetA.AddElement(new Element("elm-1"));

      Input waterLevelTriggerInput = new Input("Water level, to be retrieved from some output item", waterlevelQuantity, elementSet);
      waterLevelTriggerInput.TimeSet = new TimeSet();

      SimpleOutput dischargeOutput = new SimpleOutput("Discharge, to be sent to GW model", dischargeQuantity, elementSet);
      dischargeOutput.ConstOutput = 6;
      dischargeOutput.TimeSet = new TimeSet();

      ITimeSpaceInput gwInflow = UTHelper.FindInputItem(lc, "Grid.Inflow");
      ITimeSpaceOutput gwLevel = UTHelper.FindOutputItem(lc, "Grid.gwLevel");

      // Connect discharge
      gwInflow.Provider = dischargeOutput;
      dischargeOutput.AddConsumer(gwInflow);

      // Connect triggering input
      gwLevel.AddConsumer(waterLevelTriggerInput);

      lc.Validate();
      lc.Prepare();

      // specify query times
      double firstTriggerGetValuesTime = gwLevel.TimeSet.Times[0].StampAsModifiedJulianDay;
      double secondTriggerGetValuesTime = firstTriggerGetValuesTime + 3;
      double thirdTriggerGetValuesTime = firstTriggerGetValuesTime + 5;

      // check initial values
      Assert.AreEqual(8, gwLevel.Values.Values2D[0].Count);
      Assert.AreEqual(-10, (double)gwLevel.Values.GetValue(0, 0));

      ITimeSpaceValueSet values;

      // get values for initial time, therefor intial values
      waterLevelTriggerInput.TimeSet.SetSingleTime(new Time(firstTriggerGetValuesTime));
      values = gwLevel.GetValues(waterLevelTriggerInput);
      Assert.AreEqual(-10, values.GetValue(0, 0), "value for first query time");

      // get values for second query time: -10 : base gw level.
      // 10 : storageHeight is multiplied by a factor of 10
      // 3 days, 6 constant inflow, 3600*24 seconds in a day, 1000 L/M3, (100 x 200) grid cell size 
      waterLevelTriggerInput.TimeSet.SetSingleTime(new Time(secondTriggerGetValuesTime));
      values = gwLevel.GetValues(waterLevelTriggerInput);
      Assert.AreEqual(-10.0 + 10 * 3 * 6.0 * 60 * 60 * 24 / 1000 / (100 * 200), values.GetValue(0, 0), "value for first query time");

      // get values for second query time:
      // 10 : storageHeight is multiplied by a factor of 10
      // 5 days, 6 constant inflow, 3600*24 seconds in a day, 1000 L/M3, (100 x 200) grid cell size 
      waterLevelTriggerInput.TimeSet.SetSingleTime(new Time(thirdTriggerGetValuesTime));
      values = gwLevel.GetValues(waterLevelTriggerInput);
      Assert.AreEqual(-10.0 + 10 * 5 * 6.0 * 60 * 60 * 24 / 1000 / (100 * 200), values.GetValue(0, 0), "value for first query time");

      lc.Finish();

    }