Exemplo n.º 1
0
        /// <summary>
        /// Realtime analysis enumerable
        /// </summary>
        /// <param name="dataConsumer">Data consumer</param>
        /// <param name="readers">Input</param>
        /// <param name="stop">Stop function</param>
        /// <param name="reason">Reason</param>
        /// <param name="timeType">Time type</param>
        /// <param name="isAbsoluteTime">The absolute time "sign"</param>
        /// <returns>The enumerable</returns>
        public static IEnumerable <object> RealtimeAnalysisEnumerableDirectory(this IDataConsumer dataConsumer,
                                                                               ILogReaderCollection readers, Func <object, bool> stop, string reason,
                                                                               TimeType timeType, bool isAbsoluteTime)
        {
            IComponentCollection cc = dataConsumer.CreateCollection(reason);

            cc.ForEach((ICalculationReason re) => { re.CalculationReason = reason; });
            cc.ForEach((IRealTimeStartStop ss) => { ss.Start(); });
            IEnumerable <ILogReader> r = readers.Readers;

            foreach (ILogReader reader in r)
            {
                cc.ForEach((IRealTimeStartStop ss) => { ss.Start(); });
                IEnumerable <object> en =
                    dataConsumer.RealtimeAnalysisEnumerable(reader, stop, reason, timeType, isAbsoluteTime);
                object ob = null;
                foreach (object o in en)
                {
                    ob = o;
                }
                yield return(ob);

                cc.ForEach((IRealTimeStartStop ss) => { ss.Stop(); });
            }
            cc.ForEach((IRealTimeStartStop ss) => { ss.Stop(); });
        }
Exemplo n.º 2
0
        IEnumerable <object> Enumerable(IBufferData data)
        {
            changeItem(data);
            IEnumerable <byte[]> eb = data.Buffer;
            bool first = true;

            foreach (byte[] b in eb)
            {
                Tuple <DateTime, Dictionary <string, object> > t
                        = bytesToObject(b) as Tuple <DateTime, Dictionary <string, object> >;
                current = t.Item2;
                time    = (t.Item1 - begin).TotalSeconds;
                if (first)
                {
                    if (externalComponentCollection != null)
                    {
                        externalComponentCollection.ForEach((IStarted started) =>
                                                            { started.Start(time); });
                    }
                    first = false;
                    continue;
                }
                yield return(t);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Starts all components
        /// </summary>
        /// <param name="time">Start time</param>
        public virtual void StartAll(double time)
        {
            provider.Time = time;
            List <IStarted> ls = new List <IStarted>();

            collection.ForEach <IStarted>((IStarted s) => { ls.Add(s); s.Start(time); });
            IStep st = this;

            st.Step = -1;
            IDifferentialEquationProcessor pr = DifferentialEquationProcessor.Processor;

            if (pr == null)
            {
                return;
            }
            ICollection <IDifferentialEquationSolver> de = pr.Equations;

            foreach (IDifferentialEquationSolver deq in de)
            {
                if (deq is IStarted)
                {
                    IStarted s = deq as IStarted;
                    if (!ls.Contains(s))
                    {
                        s.Start(time);
                    }
                }
            }
            dynamical.ForEach((IDynamical dyn) => { dyn.Time = time; });
        }
Exemplo n.º 4
0
 /// <summary>
 /// Preparation
 /// </summary>
 /// <param name="collection">Desktop</param>
 private void prepareAll(IComponentCollection collection)
 {
     components.Clear();
     components.AddRange(collection.AllComponents);
     collection.ForEach <ICategoryObject>((ICategoryObject l) => { objects.Add(l); });
     arrows.Clear();
     collection.ForEach <ICategoryArrow>((ICategoryArrow l) => { arrows.Add(l); });
     IDifferentialEquationProcessor processor = DifferentialEquationProcessor.Processor;
 }
Exemplo n.º 5
0
        /// <summary>
        /// Start
        /// </summary>
        /// <param name="collection">Components</param>
        /// <param name="timeUnit">Time unit</param>
        /// <param name="isAbsoluteTime">The "is absolute time" sign</param>
        /// <param name="stepAction">Step Action</param>
        /// <param name="dataConsumer">Data Consumer</param>
        /// <param name="log">log</param>
        /// <param name="reason">Reason</param>
        IRealtime IRealtime.Start(IComponentCollection collection,
                                  TimeType timeUnit, bool isAbsoluteTime, IAsynchronousCalculation stepAction,
                                  IDataConsumer dataConsumer, IEventLog log, string reason)
        {
            this.reason = reason;
            StaticExtensionEventPortable.StartRealtime(collection);
            StandardEventRuntime rt = new StandardEventRuntime();

            rt.collection = collection;
            try
            {
                ITimeMeasureProvider realTime = RealtimeProvider.Create(isAbsoluteTime, timeUnit, reason);
                Tuple <IDataConsumer, IComponentCollection, ITimeMeasureProvider, IAsynchronousCalculation> tuple =
                    new Tuple <IDataConsumer, IComponentCollection,
                               ITimeMeasureProvider, IAsynchronousCalculation>
                        (dataConsumer, collection, realTime, stepAction);
                rt.timeProvider = realTime;
                rt.timeBackup   =
                    new DataPerformer.TimeProviderBackup(dataConsumer, realTime, null,
                                                         reason, 0);
                IEvent[] events = (dataConsumer as IEventHandler).Events.EnumerableToArray();
                if (log != null)
                {
                    foreach (IEvent ev in events)
                    {
                        string name = (dataConsumer as
                                       IAssociatedObject).GetRelativeName(ev as IAssociatedObject);
                        ev.ConnectLog(log, name);
                    }
                    collection.ForEach((IEventReader reader) =>
                    {
                        string name = (dataConsumer as
                                       IAssociatedObject).GetRelativeName(reader as IAssociatedObject);
                        reader.ConnectLog(log, name);
                    });
                }
                collection.ForEach((ICalculationReason cr) => { cr.CalculationReason = reason; });
                collection.ForEach((IRealTimeStartStop ss) =>
                {
                    ss.Start();
                });
                rt.eventBackup = new EventBackup(tuple, events, reason);
            }
            catch (Exception exception)
            {
                onError(exception);
                (rt as IRealtime).Stop();
                rt = null;
            }
            return(rt);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Sets consumers
        /// </summary>
        /// <param name="collection">Consumers</param>
        /// <returns>Lists of parameters</returns>
        public virtual void Set(object collection)
        {
            IComponentCollection cc = collection as IComponentCollection;
            IDataRuntime         rt = StaticExtensionDataPerformerPortable.Factory.Create(cc, 0);

            Clear();
            variablesStr.Clear();

            /*           IEnumerable<IDataConsumer> consumers = cc.GetAll<IDataConsumer>();
             *         foreach (IDataConsumer c in consumers)
             *         {
             *             c.GetMeasurements(measurements);
             *         }*/
            List <object> l = new List <object>();

            cc.ForEach <IDifferentialEquationSolver>((IDifferentialEquationSolver solver) =>
            {
                if (solver is IMeasurements)
                {
                    if (!l.Contains(solver))
                    {
                        l.Insert(0, solver);
                    }
                }
                if (solver is IDataConsumer)
                {
                    (solver as IDataConsumer).GetDependentObjects(l);
                }
            }
                                                     );
            foreach (object o in l)
            {
                if (o is IMeasurements)
                {
                    measurements.Add(o as IMeasurements);
                }
            }
            foreach (IMeasurements m in measurements)
            {
                IDataRuntimeFactory s = StaticExtensionDataPerformerPortable.Factory;
                if (m is IDifferentialEquationSolver)
                {
                    IDifferentialEquationSolver ds = m as IDifferentialEquationSolver;
                    Add(ds);
                }
                else if (s != null)
                {
                    IDifferentialEquationSolver ds = rt.GetDifferentialEquationSolver(m);
                    if (ds != null)
                    {
                        Add(ds);
                    }
                }
                if (m is INormalizable)
                {
                    Add(m as INormalizable);
                }
            }
            measurements.SortMeasurements();
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates enumerator
        /// </summary>
        /// <param name="consumer">The consumer</param>
        /// <returns>The enumerator</returns>
        protected virtual IEnumerable <object> Create(IDataConsumer consumer)
        {
            Func <object, bool> stop    = (object o) => { return(false); };
            IDesktop            desktop = (consumer as IAssociatedObject).GetRootDesktop();
            object l = null;

            desktop.ForEach((BelongsToCollectionPortable b) =>
            {
                if (b.Source == consumer)
                {
                    object o = b.Target;
                    if (o is LogHolder)
                    {
                        LogHolder llh = o as LogHolder;
                        (llh as IAssociatedObject).Prepare(true);
                        l = llh.Reader;
                    }
                }
            });
            if (l != null)
            {
                string reason = Event.Interfaces.StaticExtensionEventInterfaces.PureRealtimeLogAnalysis;
                IComponentCollection collection = consumer.CreateCollection(reason);
                collection.ForEach((ICalculationReason r) =>
                {
                    r.CalculationReason = reason;
                });
                if (isDirectoryOriented)
                {
                    return(consumer.RealtimeAnalysisEnumerableDirectory(l, stop, reason, TimeType.Second, false));
                }
                return(consumer.RealtimeAnalysisEnumerable(l, stop, reason, TimeType.Second, false));
            }
            return(null);
        }
Exemplo n.º 8
0
        object IAnimationDriver.StartAnimation(IComponentCollection collection, string[] reasons,
                                               AnimationType animationType, TimeSpan pause, double timeScale, bool realTime, bool absoluteTime)
        {
            List <IAnimatedObject>   l    = new List <IAnimatedObject>();
            IAsynchronousCalculation calc = null;

            double[] changeFrameTime = new double[1];

            if (realTime)
            {
                collection.ForEach <IAnimatedObject>((IAnimatedObject animated) =>
                {
                    animated.InitRealtime(animationType, changeFrameTime);
                    l.Add(animated);
                });
                if (animationType == AnimationType.Asynchronous)
                {
                    calc = new Animated.WpfAsynchronousRealtimeAnimatedCalculation(l.ToArray(), 1, changeFrameTime, collection);
                }
            }
            else
            {
                collection.ForEach <IAnimatedObject>((IAnimatedObject animated) =>
                {
                    animated.InitAnimation(animationType);
                    l.Add(animated);
                    animated.InitAnimation(animationType);
                });
                if (animationType == AnimationType.Synchronous)
                {
                    if (pause > TimeSpan.FromSeconds(0))
                    {
                        calc       = new DataPerformer.AsynchronousCalculation.PauseAsynchronousCalculation(pause);
                        collection = null;
                    }
                }
                else
                {
                    calc = new Animated.WpfAsynchronousAnimatedCalculation(l.ToArray(), timeScale, collection);
                }
            }
            if (l.Count == null)
            {
                return(null);
            }
            return(calc);
        }
Exemplo n.º 9
0
        public override void Execute(GameState state)
        {
            // pass current state and instance as parameter to avoid heap allocations
            var param = (this, state);

            // process each component
            _objects.ForEach((id, obj, p) => Move(id, obj, p), param);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Prepares itself
        /// </summary>
        protected virtual void Prepare()
        {
            ClearAll();
            collection = factory.CreateCollection(consumer, priority, null);
            prepareAll(collection);
            IEnumerable <object> comp = collection.AllComponents;

            GetMeasurements();
            foreach (object o in comp)
            {
                IUpdatableObject up = o.GetLabelObject <IUpdatableObject>();
                if (up == null)
                {
                    continue;
                }
                if (up is IDynamical)
                {
                    continue;
                }
                if (up.ShouldUpdate)
                {
                    if (up.Update != null)
                    {
                        updatable.Add(up.Update);
                    }
                }
            }
            foreach (object obj in comp)
            {
                IDynamical dyn = obj.GetLabelObject <IDynamical>();
                if (dyn == null)
                {
                    continue;
                }
                dynamical.Add(dyn);
            }
            collection.ForEach <IStep>((IStep s) => { steps.Add(s); });
            if (updatable.Count == 0)
            {
                updateAll = UpdateMeasurements;
            }
            else
            {
                updateAll = () =>
                {
                    UpdateMeasurements();
                    foreach (Action up in updatable)
                    {
                        up();
                    }
                    UpdateMeasurements();
                };
            }
        }
Exemplo n.º 11
0
 void IDisposable.Dispose()
 {
     if (collection != null)
     {
         collection.ForEach <IStopped>((IStopped stop) => { stop.Stop(); });
         Reset(collection);
         dictionary.Clear();
         return;
     }
     Reset(consumer);
     dictionary.Clear();
     if (runtime is IDisposable)
     {
         IDisposable d = runtime as IDisposable;
         d.Dispose();
     }
     if (processor != null)
     {
         processor.Clear();
     }
 }
Exemplo n.º 12
0
        /// <summary>
        /// Gets names of appropriate objects
        /// </summary>
        /// <param name="collection">Component collection</param>
        /// <returns>Names</returns>
        public static List <string> GetNames(IComponentCollection collection)
        {
            List <string> l = new List <string>();

            collection.ForEach <IObjectTransformer>((IObjectTransformer t) =>
                                                    { if (IsAccessible(t) != null)
                                                      {
                                                          l.Add(t.GetName(collection));
                                                      }
                                                    });
            return(l);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Modelled after CreateList meotod. Both methods have to be roofed by a single method, with and object of Object class rather than IEnumerable or IITerator
        /// </summary>
        /// <param name="consumer"></param>
        /// <param name="list"></param>
        /// <param name="components"></param>
        /// <param name="dictionary"></param>
        /// <returns></returns>
        public static IIterator CreateIterator(this IDataConsumer consumer, IEnumerable <object> list, IComponentCollection components,
                                               out Dictionary <IReplacedMeasurementParameter, string> dictionary)
        {
            Dictionary <IReplacedMeasurementParameter, string> dict = new Dictionary <IReplacedMeasurementParameter, string>();
            List <object> ll = new List <object>();

            components.ForEach((IMeasurements m) =>
            {
                string name = consumer.GetMeasurementsName(m) + ".";
                for (int i = 0; i < m.Count; i++)
                {
                    IMeasurement me = m[i];
                    if (me is IReplacedMeasurementParameter)
                    {
                        dict[me as IReplacedMeasurementParameter] = name + me.Name;
                    }
                }
            });
            Dictionary <string, INativeReader> dnr = new Dictionary <string, INativeReader>();

            components.ForEach((INativeReader reader) =>
            {
                if (reader is IAssociatedObject)
                {
                    string name = (consumer as IAssociatedObject).GetRelativeName(
                        reader as IAssociatedObject);
                    dnr[name] = reader;
                }
            });
            Dictionary <string, INativeEvent> dna = new Dictionary <string, INativeEvent>();
            IAssociatedObject ao = consumer as IAssociatedObject;

            components.ForEach((INativeEvent ne) =>
            {
                dna[ao.GetRelativeName(ne as IAssociatedObject)] = ne;
            });
            dictionary = dict;

            return(null);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Gets state vector of collection
        /// </summary>
        /// <param name="collection">The collection</param>
        /// <param name="input">The state vector</param>
        public static void SetStateVector(this IComponentCollection collection, double[] input)
        {
            int i = 0;
            Action <IStateDoubleVariables> action = (IStateDoubleVariables v) =>
            {
                double[] x = v.Vector;
                int      n = x.Length;
                v.Set(input, i, x.Length);
                i += n;
            };

            collection.ForEach <IStateDoubleVariables>(action);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Gets state vector of collection
        /// </summary>
        /// <param name="collection">The collection</param>
        /// <param name="output">The state vector</param>
        public static void GetStateVector(this IComponentCollection collection, double[] output)
        {
            int i = 0;
            Action <IStateDoubleVariables> action = (IStateDoubleVariables v) =>
            {
                double[] x = v.Vector;
                int      n = x.Length;
                Array.Copy(x, 0, output, i, n);
                i += n;
            };

            collection.ForEach <IStateDoubleVariables>(action);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Writes itself
        /// </summary>
        public void Write()
        {
            WriteTypes();
            if (!(item is IBufferDirectory))
            {
                "Select directory please".Show();
                return;
            }
            directory = item as IBufferDirectory;
            object log = Log;

            if (log == null)
            {
                "Select log please".Show();
                return;
            }
            change = GetItem(log);
            if (change != null)
            {
                change.Change += Change;
            }
            componentCollection = this.CreateCollection();
            componentCollection.ForEach((IInitialize initialize) =>
                                        { initialize.Initialize(); });
            try
            {
                Func <bool> stop = () => { return(true); };
                if (log is ILogReaderCollection)
                {
                    ILogReaderCollection c = log as ILogReaderCollection;
                    foreach (ILogReader reader in c.Readers)
                    {
                        Perform(reader);
                    }
                }
                else
                {
                    Perform(log as ILogReader);
                }
                StaticExtensionDataPerformerInterfaces.Data.SubmitChanges();
            }
            catch (Exception exception)
            {
                exception.ShowError();
            }
            if (change != null)
            {
                change.Change -= Change;
            }
            change = null;
        }
Exemplo n.º 17
0
        public void ShouldIterateWhenEmpty(IComponentCollection <SampleComponent> storage)
        {
            var count = 0;

            foreach (var component in storage.GetValues())
            {
                count++;
            }
            count.Should().Be(0);

            var items = new List <int>();

            storage.ForEach((id, val, list) => list.Add(id), items);
            items.Should().BeEmpty();
        }
Exemplo n.º 18
0
 void IRealtime.Stop()
 {
     StaticExtensionEventInterfaces.DisconnectLog();
     if (eventBackup != null)
     {
         eventBackup.Dispose();
     }
     if (timeBackup != null)
     {
         timeBackup.Dispose();
     }
     collection.ForEach((IRealTimeStartStop ss) =>
     {
         ss.Stop();
     });
 }
Exemplo n.º 19
0
        /// <summary>
        /// Gets variables form collection
        /// </summary>
        /// <param name="collection">The collection</param>
        /// <returns>The variables</returns>
        public static List <string[]> GetDoubleVariables(this IComponentCollection collection)
        {
            List <string[]> l = new List <string[]>();
            Action <IStateDoubleVariables> action = (IStateDoubleVariables v) =>
            {
                object        o  = v;
                string        n  = o.GetName(collection);
                List <string> ll = v.Variables;
                foreach (string ss in ll)
                {
                    l.Add(new string[] { n, ss });
                }
            };

            collection.ForEach <IStateDoubleVariables>(action);
            return(l);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Creates processor
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        protected virtual IDifferentialEquationProcessor CreateProcessor(IComponentCollection collection)
        {
            IDifferentialEquationProcessor pr = null;

            collection.ForEach((IDifferentialEquationSolver s) =>
            {
                if (pr == null)
                {
                    pr = DifferentialEquationProcessor.Processor.New;
                    pr.Set(collection);
                }
            });
            if (realtime != null & pr != null)
            {
                pr.TimeProvider = realtime;
            }
            return(pr);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Checks invalid compilation of the collection
        /// </summary>
        /// <param name="collection">The collection</param>
        /// <returns>The invalid component</returns>
        static public IAssociatedObject InvalidCompilation(this IComponentCollection collection)
        {
            IAssociatedObject ao = null;

            collection.ForEach((ITreeCollection c) =>
            {
                if (ao == null)
                {
                    if (!c.IsValid | c.HasFiction())
                    {
                        if (c is IAssociatedObject)
                        {
                            ao = c as IAssociatedObject;
                        }
                    }
                }
            }
                               );
            return(ao);
        }
Exemplo n.º 22
0
        void IDisposable.Dispose()
        {
            if (dictionary != null)
            {
                dictionary.Set();
            }
            if (events != null)
            {
                foreach (IEvent ev in events)
                {
                    ev.IsEnabled = false;
                    ev.Event    -= actions[ev];
                }
                foreach (IEvent ev in events)
                {
                    if (ev.IsEnabled)
                    {
                        ev.IsEnabled = false;
                    }
                }
            }
            foreach (IEventReader r in readers)
            {
                if (r.IsEnabled)
                {
                    r.IsEnabled = false;
                }
            }
            return;

            collection.ForEach <IEvent>((IEvent ev) => { ev.IsEnabled = false; });
            foreach (IEvent ev in actions.Keys)
            {
                if (!lno.Contains(ev))
                {
                    ev.IsEnabled = false;
                }
                ev.Event -= actions[ev];
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Event backup
        /// </summary>
        /// <param name="tuple">Tuple</param>
        /// <param name="events">Events</param>
        /// <param name="reason">Reason</param>
        public EventBackup(Tuple <IDataConsumer, IComponentCollection, ITimeMeasureProvider,
                                  IAsynchronousCalculation> tuple,
                           IEvent[] events, string reason)
        {
            this.events = events;
            collection  = tuple.Item2;
            IDesktop desktop            = collection.Desktop.Root;
            IList <ICategoryObject> l   = collection.GetAll <ICategoryObject>();
            IRealtimeStart          rst = null;

            desktop.ForEach((BelongsToCollection arrow) =>
            {
                if (!l.Contains(arrow.Target))
                {
                    return;
                }
                ICategoryObject s = arrow.Source;
                if (s is IRealtimeStart)
                {
                    IRealtimeStart rs = s as IRealtimeStart;
                    if (rs.IsEnabled)
                    {
                        if (rst != null)
                        {
                            throw new Exception("Start already exists");
                        }
                        rst = rs;
                    }
                }
            });
            if (rst != null)
            {
                dictionary = rst.StartAlias;
                dictionary.Get();
            }
            Tuple <string, Tuple <IDataConsumer, IComponentCollection, ITimeMeasureProvider,
                                  IAsynchronousCalculation> > tt = new Tuple <string, Tuple <IDataConsumer, IComponentCollection,
                                                                                             ITimeMeasureProvider, IAsynchronousCalculation> >
                                                                       (reason, tuple);
            IActionFactory       f        = StaticExtensionEventPortable.ActionFactoryCreator[tt];
            List <INativeEvent>  lnative  = new List <INativeEvent>();
            List <INativeReader> lnativeR = new List <INativeReader>();

            if (events != null)
            {
                foreach (IEvent ev in events)
                {
                    Action a = f[ev];
                    actions[ev] = a;
                    ev.Event   += a;
                }
            }
            else
            {
                collection.ForEach(
                    (IEvent ev) =>
                {
                    Action a    = f[ev];
                    actions[ev] = a;
                    ev.Event   += a;
                });
            }
            if (reason.IsRealtimeAnalysis())
            {
                collection.ForEach((INativeEvent ne) => {
                    lnative.Add(ne);
                    lno.Add(ne);
                    if (ne is ICalculationReason)
                    {
                        (ne as ICalculationReason).CalculationReason = reason;
                    }
                    if (ne is IEvent)
                    {
                        (ne as IEvent).IsEnabled = true;
                    }
                });
                collection.ForEach(
                    (INativeReader re) =>
                {
                    lnativeR.Add(re);
                    lno.Add(re);
                    if (re is ICalculationReason)
                    {
                        (re as ICalculationReason).CalculationReason = reason;
                    }
                    if (re is IEventReader)
                    {
                        (re as IEventReader).IsEnabled = true;
                    }
                });
            }

            collection.ForEach(
                (IEvent ev) =>
            {
                ev.IsEnabled = true;
            });
            List <IEventReader> ler = new List <IEventReader>();

            collection.ForEach((IEventReader r) => {
                ler.Add(r);

                r.IsEnabled = true;
            });
            readers      = ler.ToArray();
            nativeEvents = lnative.ToArray();
        }
Exemplo n.º 24
0
        public void ShouldIterateAndModify(IComponentCollection <SampleComponent> storage)
        {
            var em                = new EntityManager(t => storage as IComponentCollectionStorage);
            var withComponents    = new List <int>();
            var withoutComponents = new List <int>();

            for (var i = 0; i < 5; i++)
            {
                withoutComponents.Add(em.Create());
                var entityWithComponent = em.Create();
                em.AddComponent <SampleComponent>(entityWithComponent);
                withComponents.Add(entityWithComponent);
            }

            // Check if components were added where necessary
            withComponents.Should().OnlyContain(id => em.HasComponent <SampleComponent>(id));
            withoutComponents.Should().OnlyContain(id => !em.HasComponent <SampleComponent>(id));

            // Check IEntityView implementation
            var view = storage.GetView();

            view.Should().BeEquivalentTo(withComponents);
            view.EntityCount.Should().Be(withComponents.Count);
            view.Filter.Should().BeEquivalentTo(new[] { typeof(SampleComponent) });
            Span <int> viewData       = stackalloc int[withComponents.Count];
            var        actualViewData = view.CopyTo(viewData).ToArray();

            actualViewData.Should().BeEquivalentTo(withComponents);

            // Try to iterate using foreach
            var count = 0;

            foreach (var component in storage.GetValues())
            {
                count++;
            }
            count.Should().Be(withComponents.Count);

            // Try to iterate and modify
            count = 0;
            var ids = storage.GetView().ToList();

            foreach (var id in ids)
            {
                var value = new SampleComponent()
                {
                    Foo = 1337,
                    Bar = true
                };
                storage.Update(id, value);
                count++;
            }

            count.Should().Be(withComponents.Count);

            // Check if they were modified
            storage.GetValues().Should().OnlyContain(c => c.Foo == 1337);
            storage.GetValues().Should().OnlyContain(c => c.Bar == true);

            // Modify again and delete component from every second entity
            var iterations = 0;

            count = 0;
            storage.ForEach((id, componentValue, _) =>
            {
                componentValue.Foo = id;
                storage.UpdateCurrent(componentValue);
                if (iterations % 2 == 1)
                {
                    em.RemoveComponent <SampleComponent>(id);
                }
                else
                {
                    count++;
                }
                iterations++;
            }, default(object));
            iterations.Should().Be(withComponents.Count);
            var oddsAndEvens = withComponents
                               .Select((item, i) => (item, isEven: i % 2 == 0))
                               .ToLookup(x => x.isEven, x => x.item);

            // Check if the components were removed
            oddsAndEvens[true].Should().OnlyContain(id => em.HasComponent <SampleComponent>(id));
            oddsAndEvens[false].Should().OnlyContain(id => !em.HasComponent <SampleComponent>(id));

            // Check if the alive ones was updated
            storage.ForEach((id, val, _) =>
            {
                val.Foo.Should().Be(id);
                val.Bar.Should().BeTrue();
            }, default(object));

            // Modify and get in different order
            // Note: this is slower than the ForEach due to additional lookups
            var alive = oddsAndEvens[true].Reverse();

            foreach (var id in alive)
            {
                var newValue = new SampleComponent()
                {
                    Foo = id + 1
                };
                storage.Update(id, newValue);
            }

            foreach (var id in alive.Reverse())
            {
                storage.Get(id).Foo.Should().Be(id + 1);
            }
        }
Exemplo n.º 25
0
        IComponentCollection CreateCollection(IEvent ev)
        {
            IComponentCollection cc = dCollection[ev];
            List <IEventBlock>   bl = new List <IEventBlock>();

            cc.ForEach <IEventBlock>((IEventBlock block) =>
            {
                if (block[ev])
                {
                    bl.Add(block);
                }
            });
            if (bl.Count == 0)
            {
                return(cc);
            }
            IDesktop      d = cc.Desktop;
            List <object> l = new List <object>();

            foreach (object o in bl)
            {
                if (!l.Contains(bl))
                {
                    l.Add((o as IAssociatedObject).Object);
                }
                Func <ICategoryObject, bool> fca  = (ICategoryObject cao) => { return(true); };
                Func <ICategoryArrow, bool>  fcar = (ICategoryArrow car) => { return(true); };
                List <ICategoryObject>       cl   = (o as ICategoryObject).GetSourceObjects(fca, fcar, fcar);
                foreach (ICategoryObject co in cl)
                {
                    object ob = co.Object;
                    if (!l.Contains(ob))
                    {
                        l.Add(ob);
                    }
                }
            }
            IEnumerable <object> en = cc.AllComponents;
            List <object>        ls = new List <object>();

            foreach (object oo in en)
            {
                if (oo is IArrowLabel)
                {
                    IArrowLabel al = oo as IArrowLabel;
                    if (l.Contains(al.Source) | l.Contains(al.Target))
                    {
                        continue;
                    }
                }
                if (!l.Contains(oo))
                {
                    ls.Add(oo);
                }
                else
                {
                }
            }
            ComponentCollection ccl = new ComponentCollection(ls, d);

            dCollection[ev] = ccl;
            return(ccl);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="collection">Collection of components</param>
        /// <param name="reason">Reason</param>
        /// <param name="priority">Priority</param>
        /// <param name="dataConsumer">Data consumer</param>
        /// <param name="realtimeStep">Realtime step</param>
        /// <param name="realtime">Realtime provider</param>
        public DataRuntime(IComponentCollection collection, string reason, int priority,
                           IDataConsumer dataConsumer            = null,
                           IAsynchronousCalculation realtimeStep = null,
                           ITimeMeasureProvider realtime         = null)
        {
            this.collection   = collection;
            this.priority     = priority;
            this.reason       = reason;
            this.realtimeStep = realtimeStep;
            Prepare();
            if (realtime != null & priority == 0)
            {
                if (reason == StaticExtensionEventInterfaces.Realtime |
                    reason.IsRealtimeAnalysis())
                {
                    List <IRealtimeUpdate> lr = new List <IRealtimeUpdate>();
                    realTimeData =
                        new Dictionary <IComponentCollection, Tuple <IDataRuntime, double[],
                                                                     IDifferentialEquationProcessor, Action> >();
                    this.realtime = realtime as RealtimeProvider;
                    provider      = realtime;
                    dCollection   = new Dictionary <object, IComponentCollection>();

                    /*!!!! * DECOMPOSITION THINK AFTER
                     * collections = collection.Decompose(dCollection);
                     */
                    //========== REPLACED========
                    collections = new List <IComponentCollection>()
                    {
                        collection
                    };
                    collection.ForEach((IEvent ev) => { dCollection[ev] = collection; });
                    //===========================
                    IEventLog log = null;
                    if (reason.Equals(StaticExtensionEventInterfaces.Realtime))
                    {
                        log = StaticExtensionEventInterfaces.NewLog;
                    }
                    Action logupd = null;
                    if (log != null)
                    {
                        Dictionary <IMeasurement, string> namem = new Dictionary <IMeasurement, string>();
                        List <IMeasurement> lim = new List <IMeasurement>();
                        collection.ForEach((IMeasurements mm) =>
                        {
                            string name = (dataConsumer).GetMeasurementsName(mm) + ".";
                            for (int i = 0; i < mm.Count; i++)
                            {
                                IMeasurement mea = mm[i];
                                if (mea is IReplacedMeasurementParameter)
                                {
                                    lim.Add(mea);
                                    namem[mea] = name + mea.Name;
                                }
                            }
                        });
                        if (lim.Count > 0)
                        {
                            if (reason == "Realtime")
                            {
                                logupd = () =>
                                {
                                    logDictionary = new Dictionary <string, object>();
                                    foreach (IMeasurement mea in namem.Keys)
                                    {
                                        string n = namem[mea];
                                        logDictionary[n] = mea.Parameter();
                                    }
                                    log.Write(logDictionary, DateTime.Now);
                                };
                            }
                        }
                    }

                    if (collections.Count == 1)
                    {
                        IDifferentialEquationProcessor pr = CreateProcessor(collection);
                        double[] dt   = new double[1];
                        bool     find = (reason.Equals(StaticExtensionEventInterfaces.Realtime) |
                                         reason.Equals(StaticExtensionEventInterfaces.RealtimeLogAnalysis));
                        collection.ForEach((IRealtimeUpdate ru) => { lr.Add(ru); }, find);
                        collection.ForEach((IEvent ev) =>
                        {
                            IComponentCollection cc = CreateCollection(ev);
                            if (!realTimeData.ContainsKey(cc))
                            {
                                List <IRealtimeUpdate> lru = new List <IRealtimeUpdate>();
                                cc.ForEach((IRealtimeUpdate rud) => { lru.Add(rud); }, find);
                                IDataRuntime drc = Copy(cc);
                                double[] dtt     = new double[1];
                                Action actp      = CreateAction(drc, dtt, pr, logupd, lru.ToArray());
                                realTimeData[cc] =
                                    new Tuple <IDataRuntime, double[], IDifferentialEquationProcessor, Action>
                                        (drc, dtt, pr, actp);
                            }
                        });
                    }
                    else
                    {
                        foreach (IComponentCollection coll in collections)
                        {
                            List <IRealtimeUpdate> lu = new List <IRealtimeUpdate>();
                            foreach (object o in coll.AllComponents)
                            {
                                if (o is IObjectLabel)
                                {
                                    IRealtimeUpdate ru = (o as IObjectLabel).Object.GetObject <IRealtimeUpdate>();
                                    if (ru != null)
                                    {
                                        lu.Add(ru);
                                    }
                                }
                            }
                            IDataRuntime rt = Copy(coll);
                            IDifferentialEquationProcessor pr = CreateProcessor(collection);
                            double[] dt  = new double[1];
                            Action   act = CreateAction(rt, dt, pr, null, lr.ToArray());
                            realTimeData[coll] = new Tuple <IDataRuntime, double[], IDifferentialEquationProcessor, Action>
                                                     (rt, dt, pr, act);
                        }
                    }
                    (realtime as RealtimeProvider).Update();
                    startRuntime = provider.Time;
                    foreach (Tuple <IDataRuntime, double[], IDifferentialEquationProcessor, Action> t in realTimeData.Values)
                    {
                        t.Item2[0] = startRuntime;
                    }
                    collection.ForEach <IStarted>((IStarted st) => { st.Start(startRuntime); });
                }
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Realtime analysis
        /// </summary>
        /// <param name="dataConsumer">Data consumer</param>
        /// <param name="input">Input</param>
        /// <param name="stop">Stop function</param>
        /// <param name="reason">Reason</param>
        /// <param name="timeType">Time type</param>
        /// <param name="isAbsoluteTime">The absolute time "sign"</param>
        public static void RealtimeAnalysis(this IDataConsumer dataConsumer,
                                            object input, Func <object, bool> stop, string reason,
                                            TimeType timeType, bool isAbsoluteTime)
        {
            cadr = 0;
            IComponentCollection cc = dataConsumer.CreateCollection(reason);

            if (input is ILogReader)
            {
                ILogReader lr = input as ILogReader;
                cc.ForEach((ICalculationReason re) => { re.CalculationReason = reason; });
                cc.ForEach((IRealTimeStartStop ss) => { ss.Start(); });
                dataConsumer.RealtimeAnalysis(lr, stop, reason, timeType, isAbsoluteTime);
                cc.ForEach((IRealTimeStartStop ss) => { ss.Stop(); });
                return;
            }
            if (input is ILogReaderCollection)
            {
//                IComponentCollection cc = dataConsumer.CreateCollection(reason);
                cc.ForEach((ICalculationReason re) => { re.CalculationReason = reason; });
                cc.ForEach((IRealTimeStartStop ss) => { ss.Start(); });
                IEnumerable <ILogReader> lr = (input as ILogReaderCollection).Readers;
                foreach (ILogReader r in lr)
                {
                    cc.ForEach((IRealTimeStartStop ss) => { ss.Start(); });
                    bool b = dataConsumer.RealtimeAnalysis(r, stop, reason, timeType, isAbsoluteTime);
                    cc.ForEach((IRealTimeStartStop ss) => { ss.Stop(); });
                    if (b)
                    {
                        return;
                    }
                }
                cc.ForEach((IRealTimeStartStop ss) => { ss.Stop(); });
            }

            if (input is IIterator)
            {
                IIterator it = input as IIterator;
                cc.ForEach((ICalculationReason re) => { re.CalculationReason = reason; });
                cc.ForEach((IRealTimeStartStop ss) => { ss.Start(); });
//                bool b = dataConsumer.RealtimeAnalysis(it, stop, reason, timeType, isAbsoluteTime);
                cc.ForEach((IRealTimeStartStop ss) => { ss.Stop(); });
                return;
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Crerates SCADA
        /// </summary>
        protected virtual void CreateScada()
        {
            IEnumerable <ICategoryObject> categoryObjects = desktop.CategoryObjects;

            foreach (ICategoryObject ob in categoryObjects)
            {
                IObjectLabel  l    = ob.Object as IObjectLabel;
                string        name = l.RootName;
                List <string> list = null;
                if (objects.ContainsKey(name))
                {
                    list = objects[name];
                }
                else
                {
                    list          = new List <string>();
                    objects[name] = list;
                }
                list.Add(ob.GetType().AssemblyQualifiedName);
            }
            events.Clear();
            dEvents.Clear();
            if (consumerName == null)
            {
                return;
            }
            dataConsumer = desktop.GetObject <IDataConsumer>(consumerName);
            collection   = dataConsumer.CreateCollection("Realtime");
            collection.ForEach((Event.Interfaces.IEvent ev) =>
            {
                string s = (ev as IAssociatedObject).GetRootName();
                events.Add(s);
                dEvents[s] = new EventWrapper(ev);
            }
                               );
            collection.ForEach((IEventHandler eventHandler) =>
            {
                IEnumerable <Event.Interfaces.IEvent> evs = eventHandler.Events;
                foreach (Event.Interfaces.IEvent ev in evs)
                {
                    string s = (ev as IAssociatedObject).GetRootName();
                    if (events.Contains(s))
                    {
                        continue;
                    }
                    events.Add(s);
                    dEvents[s] = new EventWrapper(ev);
                }
            });
            inputs.Clear();
            dInput.Clear();
            collection.ForEach((ForcedEventData f) =>
            {
                string s = (f as IAssociatedObject).GetRootName();
                List <Tuple <string, object> > l = f.Types;
                for (int i = 0; i < l.Count; i++)
                {
                    Tuple <string, object> t = l[i];
                    int[] k  = new int[] { i };
                    string n = s + "." + t.Item1;
                    inputs.Add(n, t.Item2);
                    dInput[n] = (object obj) =>
                    {
                        object[] arr = f.Data;
                        arr[k[0]]    = obj;
                        f.Force();
                    };
                }
            });
            outputs.Clear();
            dOutput.Clear();
            collection.ForEach((IMeasurements measurements) =>
            {
                string s = (measurements as IAssociatedObject).GetRootName();
                for (int i = 0; i < measurements.Count; i++)
                {
                    IMeasurement measurement = measurements[i];
                    string n = s + "." + measurement.Name;
                    outputs.Add(n, measurement.Type);
                    dOutput[n] = measurement.Parameter;
                }
            });
            dConstant.Clear();
            collection.ForEach((IAlias alias) =>
            {
                string s = (alias as IAssociatedObject).GetRootName();
                foreach (string name in alias.AliasNames)
                {
                    string n = s + '.' + name;
                    Tuple <string, object> t = new Tuple <string, object>(n, alias.GetType(name));
                    dConstant[n]             = (object o) =>
                    {
                        alias[name] = o;
                    };
                }
            });
        }