public OrphanedInputSpaceTime(ITimeSpaceOutput output)
        {
            var describes = new Describes("Temporal Target", "= Temporal Target");
            SetIdentity(new Identity("FluidEarth2.Sdk.OrphanedInputSpaceTime", describes));

            Component = null;

            ValueDefinition = output.ValueDefinition;
            SpatialDefinition = output.SpatialDefinition;

            TimeSet = new TimeSet();
        }
Exemple #2
0
 public static Time GetHour(int turn, TimeSet ts)
 {
     switch(turn)
     {
         case 0:
             if (ts == TimeSet.START)
                 return new Time { Hour = 8, Minute = 0 };
             else
                 return new Time { Hour = 9, Minute = 30 };
         case 1:
             if (ts == TimeSet.START)
                 return new Time { Hour = 9, Minute = 30 };
             else
                 return new Time { Hour = 11, Minute = 0 };
         case 2:
             if (ts == TimeSet.START)
                 return new Time { Hour = 11, Minute = 0 };
             else
                 return new Time { Hour = 12, Minute = 30 };
         case 3:
             if (ts == TimeSet.START)
                 return new Time { Hour = 12, Minute = 30 };
             else
                 return new Time { Hour = 14, Minute = 0 };
         case 4:
             if (ts == TimeSet.START)
                 return new Time { Hour = 14, Minute = 0 };
             else
                 return new Time { Hour = 15, Minute = 30 };
         case 5:
             if (ts == TimeSet.START)
                 return new Time { Hour = 15, Minute = 30 };
             else
                 return new Time { Hour = 17, Minute = 0 };
         case 6:
             if (ts == TimeSet.START)
                 return new Time { Hour = 17, Minute = 0 };
             else
                 return new Time { Hour = 18, Minute = 30 };
         case 7:
             if (ts == TimeSet.START)
                 return new Time { Hour = 18, Minute = 30 };
             else
                 return new Time { Hour = 21, Minute = 30 };
         default:
             return null;
     }
 }
Exemple #3
0
    // Update is called once per frame
    void Update()
    {
        MainScript.Hit = Attacking;
        TimeSet time = GameObject.Find("Time Manager").GetComponent <TimeSet> ();

        anim.SetBool("Time Stop", time.TimeIsStop);
        Distance = Vector3.Distance(Player.transform.position, this.transform.position);
        if (time.TimeIsStop == true)
        {
            Stopall();
        }
        else
        {
            Work();
        }
    }
Exemple #4
0
 public bool Verification( )
 {
     if (Debug_TimeSkipFlag)
     {
         return(true);
     }
     if (moduleWakeup == null && moduleSleep == null)
     {
         return(true);
     }
     if (moduleWakeup.Hour == int.MaxValue && moduleSleep.Hour == int.MaxValue)
     {
         return(true);
     }
     return(TimeSet.Verification(new TimeSet(DateTime.Now), this.moduleWakeup, this.moduleSleep));
 }
        /// <summary>
        /// Loads population data and returns a list of populated Areas.
        /// </summary>
        /// <param name="timeSet"></param>
        /// <returns></returns>
        public static List <Area> LoadData(TimeSet timeSet)
        {
            var assembly     = Assembly.GetExecutingAssembly();
            var resourceName = GetDataResource(timeSet);
            var list         = new List <Area>();

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
                using (StreamReader reader = new StreamReader(stream))
                    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                    {
                        csv.Context.RegisterClassMap <AgeFileMap>();
                        var records = csv.GetRecords <Area>();

                        list.AddRange(records);
                    }
            return(list);
        }
 public ElementMapperAdaptedOutput(IIdentifiable methodId, ITimeSpaceOutput adaptee, IElementSet target)
     : base(adaptee.Id + "->" + methodId, adaptee)
 {
     _timeSet       = new TimeSet();
     _methodId      = methodId;
     _target        = target;
     _elementMapper = new ElementMapper();
     _elementMapper.Initialise(_methodId, adaptee.ElementSet(), target);
     _query = new Input(_id)
     {
         Caption           = _caption,
         Description       = _description,
         ValueDefinition   = _valueDefinition,
         SpatialDefinition = _spatialDefinition,
         Component         = adaptee.Component, // because this._component is not set yet.
     };
 }
Exemple #7
0
        public override Module CreateModule(object[] @params)
        {
            var moduleName = (string)@params[0];
            var StringSet  = (string)@params[0];
            var Time       = (int)@params[0];
            var Delay      = (int)@params[0];
            var StartTime  = (string)@params[0];
            var EndTime    = (string)@params[0];

            var module = new ReactorModule(moduleName);

            module.stringset = StringSet;
            module.LoadStringsets(StringSet);
            module.ExpireTime   = Time;
            module.ExpireDelay  = Delay;
            module.moduleWakeup = TimeSet.FromString(StartTime);
            module.moduleSleep  = TimeSet.FromString(EndTime);
            return(module);
        }
        /// <summary>
        /// Constructor for native coded IEngine
        /// </summary>
        /// <param name="identity">Identity for the component</param>
        /// <param name="derivedComponentType">Type of derived class encapsulated as an ExternalType</param>
        /// <param name="engineType">Type of IEngine derived class encapsulated as an ExternalType</param>
        /// <param name="useNativeDllArgument">True if engineType is actually a .NEt wrapper for
        /// a native implementation of IEngine, i.e. uses C interface to talk to engine which
        /// might be in some non .NET language e.g. C++/FORTRAN/Python etc</param>
        public BaseComponentTimeWithEngine(IIdentifiable identity, ExternalType derivedComponentType, ExternalType engineType, bool useNativeDllArgument)
            : base(identity, derivedComponentType, engineType, useNativeDllArgument)
        {
            _timeExtent = new TimeSet();
            _timeExtent.SetTimeHorizon(new Time());

            var argTime = new ArgumentTime(GetArgumentIdentity(ArgsWithEngineTime.TimeHorizon),
                new Time(_timeExtent.TimeHorizon));

            argTime.ValueChanged += new EventHandler<Argument<ArgumentValueTime>.ValueChangedEventArgs>(OnArgumentChangedTimeHorizon);

            Arguments.Add(argTime);

            // Base class sets typeof(RemotingServerEngineTime) not typeof(RemotingServerEngine)
            // Dont have a RemotingServerEngine as RemotingServerEngineTime only has one additional time method
            // which we can jsut ensure not to call!
            //((ArgumentParametersRemoting)Argument(GetArgumentIdentity(ArgsWithEngine.Remoting))).ParametersRemoting
            //    = new ParametersRemoting(typeof(RemotingServerEngineTime);
        }
Exemple #9
0
      public override ITimeSpaceValueSet GetValues(IBaseExchangeItem querySpecifier)
      {
        ITimeSpaceExchangeItem item = (ITimeSpaceExchangeItem)querySpecifier;

        TimeSet.SetSingleTime(item.TimeSet.Times[0]);

        int count = item.ElementSet().ElementCount;

        double[] vals = new double[count];
        for (int i = 0; i < count; i++)
        {
          vals[i] = ConstOutput;
        }

        ValueSetArray<double> valueset = new ValueSetArray<double>(vals);

        return valueset;

      }
Exemple #10
0
        /// <summary>
        /// Updates the values in the exchange item and the times in the time set.
        /// <para>
        /// This method is called just after the <see cref="LinkableEngine.PerformTimestep"/>
        /// of the <see cref="LinkableEngine"/>. If it returns true, all its output adaptors
        /// are refreshed.
        /// </para>
        /// <para>
        /// If a particular output item is not updated by a performed time step,
        /// override this method and let it return false when not updated.
        /// </para>
        /// </summary>
        /// <returns>true if output item was updated, false if not</returns>
        public virtual bool Update()
        {
            ITime time = GetOutputTime();

            if (time == null)
            {
                return(false);
            }

            TimeSet.SetSingleTime(time);
            if (_storeValuesInExchangeItem)
            {
                _values = GetValueFromEngine();
            }
            else
            {
                // no action needed, engine update call has fill exchange item
            }
            return(true);
        }
Exemple #11
0
        public ItemInDoubleBase(string id, ITimeSet componentTimeExtent, double defaultValue, double timeTolerance)
            : base(id)
        {
            TimeSet ts = new TimeSet();

            ts.HasDurations         = false;
            ts.OffsetFromUtcInHours = 0;
            double startTime = componentTimeExtent.TimeHorizon.StampAsModifiedJulianDay;

            ts.TimeHorizon = componentTimeExtent.TimeHorizon;
            ts.SetSingleTimeStamp(startTime);

            _currentTimeSet = ts;
            _defaultValue   = defaultValue;
            _timeTolerance  = timeTolerance;

            DefaultValues();

            ValidTimeSet(_currentTimeSet);
            ValidValue(Values);
        }
        protected override void EngineUpdateFromTargets()
        {
            TimeSet timeSet = new TimeSet();

            timeSet.SetSingleTimeStamp(_engine.GetCurrentTime());

            foreach (ITimeSpaceInput item in ActiveTargets)
            {
                if (item is ItemInBase)
                {
                    ((ItemInBase)item).Update(timeSet);
                }
                else
                {
                    throw new InvalidCastException("InputItemBase");
                }

                // TODO (ADH) Presumption is item contains 1 and only 1
                // set of values, at the update time, when is this false?
                Debug.Assert(item.TimeSet.Times.Count == 1);
                Debug.Assert(ValueSet.GetElementCount(item.Values) == 1);

                if (item is InflowAtNode)
                {
                    _engine.SetExternalNodeInflow(
                        _nodeIndexs[item],
                        (double)item.Values.GetElementValuesForTime(0)[0]);
                }
                else if (item is GroundWaterLevelAtNode)
                {
                    _engine.SetGroundWaterLevel(
                        _nodeIndexs[item],
                        (double)item.Values.GetElementValuesForTime(0)[0]);
                }
                else
                {
                    throw new NotImplementedException("EngineUpdateFromTargets");
                }
            }
        }
Exemple #13
0
        protected override void EngineUpdateSources()
        {
            TimeSet timeSet = new TimeSet();

            timeSet.SetSingleTimeStamp(_gwEngine.CurrentTime);

            List <double> values = new List <double>();

            foreach (ITimeSpaceOutput item in ActiveSources)
            {
                values.Clear();

                if (item is AquiferLevel)
                {
                    values.AddRange(_gwEngine.GetAquiferLevels());
                }
                else if (item is AquiferStorage)
                {
                    values.AddRange(_gwEngine.GetAquiferStorage());
                }
                else
                {
                    throw new NotImplementedException();
                }

                if (item is ItemOutBase)
                {
                    ((ItemOutBase)item).Update(timeSet, values);

                    foreach (ITimeSpaceAdaptedOutput decorator in item.AdaptedOutputs)
                    {
                        decorator.Refresh();
                    }
                }
                else
                {
                    throw new InvalidCastException("OutputItemBase");
                }
            }
        }
        private void FireUpTimer()
        {
            var time = TimeSet.Text;

            try
            {
                ParseTime(time);

                if (TimerSetToZero() == true)
                {
                    return;
                }
                Timer.Start();
                ResetScreen();
                ShowCountDown();
                DisplayTime();
            }
            catch
            {
                TimeSet.Focus();
            }
        }
        public ElementMapperAdaptedOutput(IIdentifiable methodId, ITimeSpaceOutput adaptee, IElementSet target)
            : base(adaptee.Id + "->" + methodId, adaptee)
        {
            _timeSet       = new TimeSet();
            _methodId      = methodId;
            _target        = target;
            _elementMapper = new ElementMapper();
            IElementSet set = adaptee.ElementSet();

            _elementMapper.Initialise(ref _methodId, ref set, ref target);

            // The query item must match the adaptee on every point but
            // the timeset.
            _query = new Input(_id)
            {
                Caption           = _caption,
                Description       = _description,
                ValueDefinition   = adaptee.ValueDefinition,
                SpatialDefinition = adaptee.SpatialDefinition,
                Component         = adaptee.Component, // because this._component is not set yet.
            };
        }
    private void UpdateStuff(TimeSet currentTimeSet)
    {
        //Update Skybox
        RenderSettings.skybox = currentTimeSet.skybox;

        //Update Sun Light
        sun.intensity           = currentTimeSet.sunIntensity;
        sun.color               = currentTimeSet.SunColor;
        sun.transform.rotation  = Quaternion.Euler(currentTimeSet.sunAngle);

        sun.GetComponent<LensFlare>().brightness= currentTimeSet.sunIntensity;

        //Update Ambient Lighting
        RenderSettings.ambientLight = currentTimeSet.ambientLightingColor;

        // Update Fog
        RenderSettings.fog              = currentTimeSet.enableFog;
        RenderSettings.fogColor         = currentTimeSet.fogColor;
        RenderSettings.fogMode          = currentTimeSet.fogMode;
        RenderSettings.fogDensity       = currentTimeSet.fogDensity;
        RenderSettings.fogStartDistance = currentTimeSet.linearFogStart;
        RenderSettings.fogEndDistance   = currentTimeSet.linearFogEnd;
    }
 private void FocusCatcher_GotFocus(object sender, MouseButtonEventArgs e)
 {
     TimeSet.Focus();
 }
        public override void Initialize()
        {
            var properties = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);

            foreach (IArgument argument in Arguments)
            {
                properties.Add(argument.Id, argument.Value);
            }
            string simFileName = "SimpleRiver.sim";
            object value;

            if (properties.TryGetValue("SimFileName", out value) && value != null && value.ToString().Length > 1)
            {
                simFileName = value.ToString();
            }
            // -- Create and initialize the engine --
            if (properties.TryGetValue("FilePath", out value) && value != null && value.ToString().Length > 1)
            {
                _simpleRiverEngine.Initialize(value.ToString(), simFileName);
            }
            else
            {
                string currentDir = System.IO.Directory.GetCurrentDirectory();
                _simpleRiverEngine.Initialize(currentDir, simFileName);
                //When running from the GUI, the assembly is started with the current dir
                //to the location of the OMI files. It is assumed that the data files are
                //located in the same directory.
            }

            if (properties.TryGetValue("TimeStepLength", out value) && value != null && ((double)value) > 0.0)
            {
                _simpleRiverEngine.SetTimeStepLength(Convert.ToDouble(value));
            }

            if (properties.TryGetValue("ModelId", out value) && value != null)
            {
                // Note: This does strictly not set the id to the fortran engine (no setter available)
                Id = value.ToString();
            }
            else
            {
                Id = _simpleRiverEngine.GetModelID();
            }

            Description = _simpleRiverEngine.GetModelDescription();

            // -- Time horizon --
            char[]   delimiter   = new char[] { '-', ' ', ':' };
            string[] strings     = _simpleRiverEngine.GetSimulationStartDate().Split(delimiter);
            int      StartYear   = Convert.ToInt32(strings[0]);
            int      StartMonth  = Convert.ToInt32(strings[1]);
            int      StartDay    = Convert.ToInt32(strings[2]);
            int      StartHour   = Convert.ToInt32(strings[3]);
            int      StartMinute = Convert.ToInt32(strings[4]);
            int      StartSecond = Convert.ToInt32(strings[5]);
            DateTime startDate   = new DateTime(StartYear, StartMonth, StartDay, StartHour, StartMinute, StartSecond);

            _simulationStartTime = new Time(startDate).StampAsModifiedJulianDay;


            // -- Build exchange items ---
            Dimension flowDimension = new Dimension();

            flowDimension.SetPower(DimensionBase.Length, 3);
            flowDimension.SetPower(DimensionBase.Time, -1);

            Unit flowUnit = new Unit("m3/sec", 1, 0, "m3/sec");

            flowUnit.Dimension = flowDimension;

            Quantity flowQuantity   = new Quantity(flowUnit, "Flow description", "Flow");
            Quantity inFlowQuantity = new Quantity(flowUnit, "Inflow description", "InFlow");

            // ADH: Might not be unreasonable to set double as default in backbone constructor
            flowQuantity.ValueType   = typeof(double);
            inFlowQuantity.ValueType = typeof(double);

            int numberOfNodes = _simpleRiverEngine.GetNumberOfNodes();

            TimeSet timeset = new TimeSet();

            timeset.TimeHorizon = GetTimeHorizon();

            TimeSet extentTimeSet = new TimeSet();

            extentTimeSet.TimeHorizon = GetTimeHorizon();
            extentTimeSet.Times.Add(GetTimeHorizon());
            _timeExtent = extentTimeSet;

            int nCount = 0;

            for (int i = 0; i < numberOfNodes - 1; i++)
            {
                ElementSet branch = new ElementSet("description", "Branch:" + i, ElementType.PolyLine, "");
                branch.AddElement(new Element("Branch:" + i.ToString()));
                branch.Elements[0].AddVertex(new Coordinate(_simpleRiverEngine.GetXCoordinate(i), _simpleRiverEngine.GetYCoordinate(i), 0));
                branch.Elements[0].AddVertex(new Coordinate(_simpleRiverEngine.GetXCoordinate(i + 1), _simpleRiverEngine.GetYCoordinate(i + 1), 0));

                EngineEOutputItem flowFromBrach = new EngineEOutputItem("Branch:" + i + ":Flow", flowQuantity, branch, this);

                int branchIndex = i;
                EngineDInputItem inflowToBranch = new EngineDInputItem("Branch:" + i + ":InFlow", inFlowQuantity, branch, this);
                inflowToBranch.ValueSetter = delegate(ITimeSpaceValueSet values)
                {
                    _simpleRiverEngine.AddInflow(branchIndex, (double)values.GetValue(0, 0));
                };

                flowFromBrach.TimeSet = timeset;

                EngineOutputItems.Add(flowFromBrach);
                EngineInputItems.Add(inflowToBranch);
            }

            for (int i = 0; i < numberOfNodes; i++)
            {
                ElementSet node = new ElementSet("description", "Node:" + i.ToString(), ElementType.IdBased, "");
                node.AddElement(new Element("Node:" + i.ToString()));

                int nodeIndex = i;
                EngineDInputItem inflowToNode = new EngineDInputItem(node.Caption + ":InFlow", inFlowQuantity, node, this);
                inflowToNode.ValueSetter = delegate(ITimeSpaceValueSet values)
                {
                    _simpleRiverEngine.AddInflow(nodeIndex, (double)values.GetValue(0, 0));
                };
                Inputs.Add(inflowToNode);
            }

            ElementSet branches = new ElementSet("description", "AllBranches", ElementType.PolyLine, "");

            for (int i = 0; i < numberOfNodes - 1; i++)
            {
                Element branch = new Element("Branch: " + i.ToString());
                branch.AddVertex(new Coordinate(_simpleRiverEngine.GetXCoordinate(i), _simpleRiverEngine.GetYCoordinate(i), 0));
                branch.AddVertex(new Coordinate(_simpleRiverEngine.GetXCoordinate(i + 1), _simpleRiverEngine.GetYCoordinate(i + 1), 0));
                branches.AddElement(branch);
            }

            EngineEInputItem inFlowToBraches = new EngineEInputItem(branches.Caption + ":inFlow", inFlowQuantity, branches, this);

            Inputs.Add(inFlowToBraches);

            Status = LinkableComponentStatus.Initialized;
        }
Exemple #19
0
 public ReactorModule(string name) : base(name)
 {
     this.moduleWakeup = this.moduleSleep = new TimeSet(-1);
 }
Exemple #20
0
    // Update is called once per frame
    void Update()
    {
        MainScript.Hit = Attacking;
        TimeSet time = GameObject.Find("Time Manager").GetComponent <TimeSet> ();

        anim.SetBool("Time Stop", time.TimeIsStop);
        Distance = Vector3.Distance(Player.transform.position, this.transform.position);
        if (time.TimeIsStop == true)
        {
            anim.speed = 0;
            nav.speed  = 0;
        }
        else
        {
            anim.speed = 1;
            if (Attacking == true)
            {
                anim.speed = MainScript.SpeedAttack;
            }
            if (IsTrigger == false)
            {
                if (MainScript.isInFov == true)
                {
                    anim.SetBool("Idle", true);
                    anim.SetBool("Break", false);
                    IsTrigger = true;
                }
            }
            else
            {
                if (Distance <= 20 && Distance > 3)
                {
                    Walk();
                }
                else if (Distance < 3)
                {
                    Vector3 TransformRay = new Vector3(transform.position.x, transform.position.y + 1, transform.position.z);
                    RotateWhenAttackFalse();
                    if (CanAttack == true)
                    {
                        RaycastHit hit;
                        if (Physics.Raycast(TransformRay, transform.forward, out hit))
                        {
                            if (hit.transform.tag == ("PLayer"))
                            {
                                Debug.Log("hit");
                                StartAttack();
                            }
                        }
                    }
                    else
                    {
                        if (Time.time - lastTimeAttack > 4)
                        {
                            CanAttack = true;
                        }
                    }
                }
                else if (Distance >= 20)
                {
                    anim.SetBool("Break", true);
                    anim.SetBool("Idle", false);
                    MainScript.isInFov = false;
                    IsTrigger          = false;
                }
            }
        }
    }
 private PopulationDataSet(TimeSet timeSet)
 {
     Areas.Clear();
     Areas.AddRange(DataLoader.LoadData(timeSet));
 }
 /// <summary>
 /// Creates a population dataset for use.
 /// </summary>
 /// <param name="timeSet"></param>
 /// <returns></returns>
 public static PopulationDataSet DataSet(TimeSet timeSet = TimeSet.Newest)
 {
     return(new PopulationDataSet(timeSet));
 }
Exemple #23
0
        protected internal override void Update()
        {
            if (_providers.Count > 0)
            {
                ITime inputTime = GetInputTime();
                if (inputTime == null)
                {
                    return;
                }

                TimeSet.SetSingleTime(inputTime);

                // the set of values that is set to the engine
                ITimeSpaceValueSet values = null;

                // Loop through all providers
                for (int i = 0; i < _providers.Count; i++)
                {
                    ITimeSpaceOutput provider = _providers[i];

                    // Create the values variable for the first provider
                    // and add the result from the remaining providers to this
                    if (i == 0)
                    {
                        values = provider.GetValues(this);
                    }
                    else
                    {
                        ITimeSpaceValueSet addValues = provider.GetValues(this);

                        // Add the addValues to the values
                        int times = values.TimesCount();
                        int elmts = values.ElementCount();

                        if (addValues.TimesCount() != times ||
                            addValues.ElementCount() != elmts)
                        {
                            throw new Exception("Size of inputs differs, valuesets can not be added");
                        }

                        for (int j = 0; j < times; j++)
                        {
                            for (int k = 0; k < elmts; k++)
                            {
                                // would be really nice if the value set was templated (to avoid casting)
                                values.Values2D[j][k] = ((double)values.Values2D[j][k]) + ((double)addValues.Values2D[j][k]);
                            }
                        }
                    }
                }
                ITimeSpaceValueSet incomingValues = values;


                if (StoreValuesInExchangeItem)
                {
                    _values = incomingValues;
                    _linkableEngine.InputItemsToBeProcessed.Add(this);
                    HasBeenProcessed = false;
                }
                else
                {
                    // Here we do not add this input item to the list of InputItemsToBeProcessed, we process immediately
                    SetValuesToEngine(incomingValues);
                    HasBeenProcessed = true;
                }
            }
            else
            {
                throw new Exception("Trying to update an input item without a provider.");
            }
        }
 private void UpdateSkydome(TimeSet currentTimeSet)
 {
     //Material skydomeMaterial = skydome.GetComponent<MeshRenderer>().material;
 }
        protected override ITime EngineInitialize(List <IArgument> arguments)
        {
            Debug.Assert(true);
            _engine = new Engine();

            FileInfo fileInNetwork = base.GetFirstCaptionMatchArgumentValueAsRootedFileInfo(
                "FileInNetwork");

            FileInfo fileInBoundaryConditions = base.GetFirstCaptionMatchArgumentValueAsRootedFileInfo(
                "FileInBoundaryConditions");

            FileInfo fileOut = base.GetFirstCaptionMatchArgumentValueAsRootedFileInfo(
                "FileOut");

            _monitorExchangeEvents = (bool)base.GetArgumentValueFirstCaptionMatch(
                "MonitorExchangeEvents");
            _showGroundWaterLevelTargets = (bool)base.GetArgumentValueFirstCaptionMatch(
                "ShowGroundWaterLevelTargets");

            _engine.ReadInputFiles(fileInNetwork.FullName, fileInBoundaryConditions.FullName);
            _engine.init(fileOut.FullName);

            _describes.Caption = _engine.GetModelID();

            // Time horizon --
            DateTime startTime         = _engine.GetSimulationStartTime();
            int      numberOfTimeSteps = _engine.GetNumberOfTimeSteps();
            double   timeStepLength    = _engine.GetTimeStepLength();

            double  duration   = (numberOfTimeSteps * timeStepLength) / (3600 * 24.0);
            double  start      = Time.ToModifiedJulianDay(startTime);
            TimeSet timeExtent = new TimeSet();

            timeExtent.TimeHorizon = new Time(start, duration);
            TimeExtent             = timeExtent;

            int nNodes    = _engine.GetNumberOfNodes();
            int nBranches = nNodes - 1;

            Point2D[] points = new Point2D[nNodes];

            for (int n = 0; n < nNodes; ++n)
            {
                points[n] = new Point2D(_engine.GetXCoordinate(n), _engine.GetYCoordiante(n));
            }

            double initialValue  = 0;
            double defaultValue  = 0;
            double relaxation    = 1;                                  // for linear extrapolation, 1 = None
            double timeTolerance = 1.0 / (24.0 * 60.0 * 60.0 * 100.0); // 1/100th sec

            ItemOutBase source;
            ItemInBase  target;

            for (int n = 0; n < nBranches; ++n)
            {
                source = new FlowAlongBranch(
                    string.Format("River branch [{0}]", n),
                    new List <Point2D[]> {
                    new Point2D[2] {
                        points[n], points[n + 1]
                    }
                },
                    initialValue,
                    relaxation,
                    this);

                if (_monitorExchangeEvents)
                {
                    source.ItemChanged += new EventHandler <ExchangeItemChangeEventArgs>(ForwardExchangeEvent);
                }

                _branchIndexs.Add(source, n);

                Sources.Add(source);
            }

            for (int n = 0; n < nNodes; ++n)
            {
                target = new InflowAtNode(
                    string.Format("Inflow location [{0}]", n),
                    points[n],
                    defaultValue,
                    timeTolerance,
                    this);

                if (_monitorExchangeEvents)
                {
                    target.ItemChanged += new EventHandler <ExchangeItemChangeEventArgs>(ForwardExchangeEvent);
                }

                _nodeIndexs.Add(target, n);

                Targets.Add(target);

                if (_showGroundWaterLevelTargets)
                {
                    target = new GroundWaterLevelAtNode(
                        string.Format("Ground Water level, location [{0}]", n),
                        points[n],
                        defaultValue,
                        timeTolerance,
                        this);

                    if (_monitorExchangeEvents)
                    {
                        target.ItemChanged += new EventHandler <ExchangeItemChangeEventArgs>(ForwardExchangeEvent);
                    }

                    _nodeIndexs.Add(target, n);

                    Targets.Add(target);
                }
            }

            return(new Time(_engine.GetCurrentTime()));
        }
Exemple #26
0
        public void UpdateTimeSet(TimeSet timeSet)
        {
            var t = _ctx.TimeSets.Update(timeSet);

            _ctx.SaveChanges();
        }
        private void ReadFile(string inputFile)
        {
            TimeBufferer output = new TimeInterpolator();

            TimeSet     timeSet = output.TTimeSet;
            IElementSet elementSet;

            StreamReader reader = new StreamReader(inputFile);

            // Read quantity and imply unit
            string   line     = GetNextLine(reader).Trim(' ', '"');
            Quantity quantity = new Quantity(line);

            if (line.Equals("Flow", StringComparison.InvariantCultureIgnoreCase))
            {
                quantity.Unit = new Unit(PredefinedUnits.CubicMeterPerSecond);
            }
            else if (line.Equals("WaterLevel", StringComparison.InvariantCultureIgnoreCase))
            {
                quantity.Unit = new Unit(PredefinedUnits.Meter);
            }
            else
            {
                quantity.Unit = new Unit("Unspecified unit");
            }
            output.ValueDefinition = quantity;

            // Read elementset
            line = GetNextLine(reader);
            string[] elements          = line.Split(';');
            string   elementTypeString = elements[0].Trim('"');

            if (elementTypeString.Equals("IdBased", StringComparison.InvariantCultureIgnoreCase))
            {
                var idelementSet = new ElementSet(inputFile + "-" + quantity.Caption, inputFile, ElementType.IdBased, "");
                for (int i = 1; i < elements.Length; i++)
                {
                    idelementSet.AddElement(new Element(elements[i].Trim('"')));
                }
                elementSet = idelementSet;
            }

            else if (elementTypeString.Equals("Points", StringComparison.InvariantCultureIgnoreCase))
            {
                var pelementSet = new ElementSet(inputFile + "-" + quantity.Caption, inputFile, ElementType.Point, "");
                for (int i = 1; i < elements.Length; i++)
                {
                    string[] coordinates = elements[i].Trim('"', '(', ')').Split(',');
                    if (coordinates.Length < 2)
                    {
                        throw new InvalidDataException("Invalid file format: only one coordinate for point: " + inputFile);
                    }
                    Element    element  = new Element();
                    double     x        = Double.Parse(coordinates[0], NumberFormatInfo.InvariantInfo);
                    double     y        = Double.Parse(coordinates[1], NumberFormatInfo.InvariantInfo);
                    Coordinate elmtCoor = new Coordinate(x, y);
                    element.Vertices = new Coordinate[] { elmtCoor };
                    pelementSet.AddElement(element);
                }
                elementSet = pelementSet;
            }
            else if (elementTypeString.Equals("RegularGrid", StringComparison.InvariantCultureIgnoreCase))
            {
                Spatial2DRegularGrid grid = new Spatial2DRegularGrid();
                grid.IsNodeBased = false;
                string[] parts = elements[1].Trim('"', '(', ')').Split(',');
                grid.X0          = Double.Parse(parts[0], NumberFormatInfo.InvariantInfo);
                grid.Y0          = Double.Parse(parts[1], NumberFormatInfo.InvariantInfo);
                grid.Dx          = Double.Parse(parts[2], NumberFormatInfo.InvariantInfo);
                grid.Dy          = Double.Parse(parts[3], NumberFormatInfo.InvariantInfo);
                grid.XCount      = Int32.Parse(parts[4], NumberFormatInfo.InvariantInfo);
                grid.YCount      = Int32.Parse(parts[5], NumberFormatInfo.InvariantInfo);
                grid.Orientation = (parts.Length < 5) ? 0 : Int32.Parse(parts[6], NumberFormatInfo.InvariantInfo);

                elementSet = new Spatial2DGridWrapper(grid);
            }
            else
            {
                throw new InvalidDataException("Invalid file format: Element type not reckognized: " + inputFile);
            }
            output.SpatialDefinition = elementSet;

            // Read times and values. First element is time, following are element values.
            ITimeSpaceValueSet valueSet = output.Values;

            while ((line = GetNextLine(reader)) != null)
            {
                string[] fileValues = line.Split(';');
                if (fileValues.Length - 1 != elementSet.ElementCount)
                {
                    throw new InvalidDataException("Number of data does not match number of elements on line: \n" + line);
                }

                DateTime timestamp = DateTime.ParseExact(fileValues[0].Trim('"'), "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
                Time     time      = new Time(timestamp);

                double[] locationValues = new double[fileValues.Length - 1];
                for (int i = 1; i < fileValues.Length; i++)
                {
                    locationValues[i - 1] = Double.Parse(fileValues[i].Trim('"'), NumberFormatInfo.InvariantInfo);
                }
                timeSet.Times.Add(time);
                valueSet.Values2D.Add(locationValues);
            }

            reader.Close();

            timeSet.SetTimeHorizonFromTimes();

            _outputs.Add(output);
        }
Exemple #28
0
 public void Patch([FromBody] TimeSet timeSet)
 {
     _tSvc.UpdateTimeSet(timeSet);
 }
        protected override ITimeSpaceValueSet GetValuesTimeImplementation(IBaseExchangeItem querySpecifier)
        {
            if (!(querySpecifier is ITimeSpaceExchangeItem))
                return _valueSetConverterTime.GetValueSetLatest() as ITimeSpaceValueSet;

            TimeSet = ((ITimeSpaceExchangeItem)querySpecifier).TimeSet;
            TimeSet queryTime = new TimeSet(((ITimeSpaceExchangeItem)querySpecifier).TimeSet);

            if (Component == null) // Orphaned Exchange item
                return _valueSetConverterTime.GetValueSetAt(TimeSet) as ITimeSpaceValueSet;

            int updateCount = 0;

            while (!_valueSetConverterTime.CanGetValueSetWithoutExtrapolationAt(queryTime))
            {
                if (Component.Status == LinkableComponentStatus.Updating)
                {
                    // Bidirectional link and component is busy

                    string warning = string.Format("WARNING: Component \"{0}\" busy extrapolated for required values", Component.Caption);

                    Trace.TraceWarning(warning);
                    SendItemChangedEvent(warning);

                    return _valueSetConverterTime.GetValueSetAt(queryTime) as ITimeSpaceValueSet;
                }
                else if (updateCount > _updatelimitBeforeExtrapolating)
                {
                    string error = string.Format(
                        "ERROR: Component \"{0}\" reached update limit of {1}, aborted updates and extrapolated for required values",
                        Component.Caption, _updatelimitBeforeExtrapolating);

                    Trace.TraceError(error);
                    SendItemChangedEvent(error);

                    return _valueSetConverterTime.GetValueSetAt(queryTime) as ITimeSpaceValueSet;
                }
                else
                {
                    Component.Update(this);
                    ++updateCount;
                }
            }

            return _valueSetConverterTime.GetValueSetAt(queryTime) as ITimeSpaceValueSet;
        }
Exemple #30
0
        protected override ITime EngineInitialize(List <IArgument> arguments)
        {
            _modelId = (string)base.GetArgumentValueFirstCaptionMatch(
                OmiArguments.ModelID.ToString());

            _simulationStart = (DateTime)base.GetArgumentValueFirstCaptionMatch(
                OmiArguments.SimulationStart.ToString());
            _simulationEnd = (DateTime)base.GetArgumentValueFirstCaptionMatch(
                OmiArguments.SimulationEnd.ToString());

            _gridInfo = new GridInfo(
                (double)base.GetArgumentValueFirstCaptionMatch(OmiArguments.OriginX.ToString()),
                (double)base.GetArgumentValueFirstCaptionMatch(OmiArguments.OriginY.ToString()),
                (double)base.GetArgumentValueFirstCaptionMatch(OmiArguments.CellSize.ToString()),
                (int)base.GetArgumentValueFirstCaptionMatch(OmiArguments.NX.ToString()),
                (int)base.GetArgumentValueFirstCaptionMatch(OmiArguments.NY.ToString()),
                (double)base.GetArgumentValueFirstCaptionMatch(OmiArguments.GridAngle.ToString()));

            FileInfo fileOut = base.GetFirstCaptionMatchArgumentValueAsRootedFileInfo(
                "FileOut");

            _groundWaterLevel = (double)base.GetArgumentValueFirstCaptionMatch(OmiArguments.GroundWaterLevel.ToString());

            _monitorExchangeEvents = (bool)base.GetArgumentValueFirstCaptionMatch(
                OmiArguments.MonitorExchangeEvents.ToString());

            _gwEngine = new Engine(_simulationStart, _simulationEnd, _gridInfo, _groundWaterLevel, fileOut);

            IElementSet elementSet = new Grid(_gridInfo);

            _describes.Caption = _modelId;

            TimeSet timeExtent = new TimeSet();

            timeExtent.TimeHorizon = new Time(_simulationStart, _simulationEnd);

            TimeExtent = timeExtent;

            double[] zeros  = new double[_gridInfo.NumberOfCells];
            double[] levels = new double[_gridInfo.NumberOfCells];

            for (int n = 0; n < _gridInfo.NumberOfCells; ++n)
            {
                zeros[n]  = 0;
                levels[n] = 0;
            }

            double relaxation    = 1;                                  // for linear extrapolation, 1 = None
            double timeTolerance = 1.0 / (24.0 * 60.0 * 60.0 * 100.0); // 1/100th sec

            Targets.Add(new Inflow((Targets.Count + Sources.Count).ToString(),
                                   zeros,
                                   timeTolerance,
                                   new Grid(_gridInfo),
                                   this));

            Sources.Add(new AquiferLevel((Targets.Count + Sources.Count).ToString(),
                                         zeros,
                                         relaxation,
                                         new Grid(_gridInfo),
                                         this));

            Sources.Add(new AquiferStorage((Targets.Count + Sources.Count).ToString(),
                                           zeros,
                                           relaxation,
                                           new Grid(_gridInfo),
                                           this));

            return(new Time(_gwEngine.CurrentTime));
        }
Exemple #31
0
        private TweetMatchResult IsMatch(string category, string input, ITweet status)
        {
            TweetMatchResult state = TweetMatchResult.NotMatch;

            var originText  = status.Text.Replace(" ", "").Replace("\n", "");
            var compareText = input.Replace(" ", "").Replace("\n", "");


            // TODO: Use IsCategoryMatch()
            if (ParseEscapeInput(originText, compareText))
            {
                switch (category)
                {
                case "All":
                    if ((status.InReplyToStatusId == null && status.InReplyToScreenName == null && !new Regex("^\\s@\\s").IsMatch(status.Text)) ||
                        status.InReplyToUserId == Globals.Instance.User.Id)
                    {
                        Log.Print(this.Name, "catch tweet (all) [{0}({1}) : {2}]", status.CreatedBy.Name, status.CreatedBy.ScreenName, status.Text);
                        state = TweetMatchResult.Match;
                    }
                    break;

                case "Mention":
                    if (status.InReplyToUserId == Globals.Instance.User.Id)
                    {
                        Log.Print(this.Name, "catch tweet (Mention) [{0}({1}) : {2}]", status.CreatedBy.Name, status.CreatedBy.ScreenName, status.Text);
                        state = TweetMatchResult.Match;
                    }
                    break;

                case "Public":
                    if (status.InReplyToStatusId == null && status.InReplyToScreenName == null && !new Regex("^\\s@\\s").IsMatch(status.Text))
                    {
                        Log.Print(this.Name, "catch tweet (Public) [{0}({1}) : {2}]", status.CreatedBy.Name, status.CreatedBy.ScreenName, status.Text);
                        state = TweetMatchResult.Match;
                    }
                    break;

                default:

                    break;
                }


                if (ExpireTime != 0 && !Debug_ExpireSkipFlag)
                {
                    lock ( ExpireUsers )
                    {
                        if (ExpireUsers.ContainsKey(status.CreatedBy.Id))
                        {
                            var ExpireTimeset = ExpireUsers[status.CreatedBy.Id];
                            if (TimeSet.Verification(new TimeSet(DateTime.Now), ExpireTimeset, new TimeSet(ExpireTimeset.Hour, ExpireTimeset.Minute + ExpireTime)))
                            {
                                Log.Print(this.Name, "User {0} rejected by expire : to {1}", status.CreatedBy.ScreenName, ExpireTimeset);
                                state = TweetMatchResult.Expire;
                            }
                            else
                            {
                                ExpireUsers.Remove(status.CreatedBy.Id);
                            }
                        }
                    }
                }
            }
            return(state);
        }
        public override void Initialise(XElement xElement, IDocumentAccessor accessor)
        {
            xElement = Persistence.ThisOrSingleChild(XName, xElement);

            base.Initialise(xElement, accessor);

            _timeExtent = Persistence.TimeSet.Parse(xElement, accessor);

            _engineDone = false;
        }
        public override void Initialize()
        {
            Status = LinkableComponentStatus.Initializing;

            foreach (IArgument argument in Arguments)
            {
                if (argument.Caption.ToLower().Equals("id"))
                {
                    Id = (string)argument.Value;
                }
                else if (argument.Caption.ToLower().Equals("timehorizonoffset"))
                {
                    double timeHorizonOffset = Double.Parse((string)argument.Value);
                    _startTimeAsMJD += timeHorizonOffset;
                    _endTimeAsMJD   += timeHorizonOffset;
                }
                else if (argument.Caption.ToLower().Equals("deltaT"))
                {
                    _deltaT = Double.Parse((string)argument.Value);
                }
                else if (argument.Caption.ToLower().Equals("quantity"))
                {
                    AddQuantity((string)argument.Value);
                }
                else if (argument.Caption.ToLower().Equals("elementset"))
                {
                    if (argument.Value.Equals("catchment-polygons"))
                    {
                        IDictionary <string, IElementSet> spatialElmSets =
                            RainRrCfElementSets.CreateRainfallRunoffElementSets();
                        foreach (var spatialElmSet in spatialElmSets)
                        {
                            _elementSets.Add(spatialElmSet.Key, spatialElmSet.Value);
                        }
                    }
                    else
                    {
                        AddElementset((string)argument.Value);
                    }
                }
                else if (argument.Caption.ToLower().EndsWith("putitem"))
                {
                    AddExchangeItem(argument.Caption.ToLower(), (string)argument.Value);
                }
                else
                {
                    throw new Exception("Unknown key \"" + argument.Caption + "\" in component " + Id);
                }
            }

            _currentTime = _startTimeAsMJD;

            _timeSetForOutputExchangeItems = new TimeSet();
            _timeSetForInputExchangeItems  = new TimeSet();

            _timeSetForInputExchangeItems.TimeHorizon      =
                _timeSetForOutputExchangeItems.TimeHorizon =
                    new Time(_startTimeAsMJD, _endTimeAsMJD - _startTimeAsMJD);

            _adaptedOutputFactories = new List <IAdaptedOutputFactory>();
            _adaptedOutputFactories.Add(new AdaptedOutputFactory("AdaptedOutputFactory for " + Id));

            foreach (EngineInputItem inputItem in EngineInputItems)
            {
                inputItem.TimeSet = _timeSetForInputExchangeItems;
            }
            foreach (EngineOutputItem outputItem in EngineOutputItems)
            {
                outputItem.TimeSet = _timeSetForOutputExchangeItems;
            }

            Status = LinkableComponentStatus.Initialized;
        }