示例#1
0
        public void UpdateEntityTest()
        {
            var        ctx      = new SimulationContext(true);
            Random     random   = new Random();
            EntityPool pool     = new EntityPool(ctx);
            var        entities = CreateEntities(ctx.LocalSpace, 3);

            foreach (var e in entities)
            {
                Assert.IsTrue(pool.Insert(e));
            }

            for (int i = 0; i < 10; i++)
            {
                Entity old   = entities[0];
                Entity moved = Relocate(old);
                Assert.IsTrue(pool.Contains(old.ID));
                Assert.IsTrue(pool.UpdateEntity(entities[0], moved), "Update moved entity " + i);
                Assert.IsFalse(pool.Contains(old.ID));
                entities[0] = moved;
                Assert.AreEqual(pool.Count, entities.Count);
                foreach (var e in entities)
                {
                    Assert.IsTrue(pool.Contains(e.ID.Guid));
                    Assert.IsTrue(pool.Contains(e.ID));
                }
            }
        }
示例#2
0
        public Creature(int xPos, int yPos, SimulationContext context, int energy,
                        int strength, Species species, Direction direction) : base(xPos, yPos, context)
        {
            Species   = species;
            Energy    = energy;
            Strength  = strength;
            Direction = direction;
            _context  = context;
            IsAlive   = true;

            switch (species.Digestion)
            {
            case Digestion.Carnivore:
                Color = Color.Red;
                break;

            case Digestion.Herbivore:
                Color = Color.Brown;
                break;

            case Digestion.OmnivoreCreature:
            case Digestion.OmnivorePlant:
                Color = Color.Yellow;
                break;

            case Digestion.Nonivore:
                Color = Color.Purple;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#3
0
        private static bool IsModelEmpty(SimulationContext context)
        {
            bool isEmpty = true;

            if (personGenerator.PersonsPool.Count > 0)
            {
                isEmpty = false;
            }

            foreach (Lift l in lifts)
            {
                if (l.CurrentLoad > 0)
                {
                    isEmpty = false;
                }

                if (l.RequestedFloors.Count > 0)
                {
                    isEmpty = false;
                }
            }

            foreach (Floor f in personGenerator.Floors)
            {
                if (f.PersonsWaiting.Count > 0)
                {
                    isEmpty = false;
                }
            }
            return(isEmpty);
        }
示例#4
0
        public override void ProcessEntity(SimulationContext context, Entity entity, DirectControlComponent controller, PhysicsComponent physicsComponent)
        {
            var body = physicsComponent.Body;

            if (context.DeltaTime == 0)
            {
                return;
            }

            if (controller.Translational.Any(v => Math.Abs(v) > 0.1f))
            {
                body.ApplyLocalCentralImpulse((controller.Translational * maximumTranslational).ClampLength(maximumTranslational), context.DeltaTime);
            }
            else
            {
                body.ApplyGlobalCentralImpulse(-body.LinearVelocity.ClampLength(maximumTranslational), context.DeltaTime);
            }


            if (controller.Steering.Any(v => Math.Abs(v) > 0.1f))
            {
                body.ApplyLocalTorqueImpulse((controller.Steering * maximumRotational).ClampLength(maximumRotational), context.DeltaTime);
            }
            else
            {
                body.ApplyGlobalTorqueImpulse(-body.AngularVelocity.ClampLength(maximumRotational), context.DeltaTime);
            }

            // Console.WriteLine("DC Angular velocity length: {0}", body.AngularVelocity.Length());
            // Console.WriteLine(body.totalForce);

            base.ProcessEntity(context, entity, controller, physicsComponent);
        }
示例#5
0
        /// <summary>
        /// Creates a simulator with a provided desired end state.
        /// </summary>
        /// <param name="simulations">The simulations to execute.</param>
        /// <param name="initialContext">The initial simulation context.</param>
        /// <param name="endState">The desired end state of the simulation.</param>
        /// <returns>A simulator instance.</returns>
        public static Simulator CreateWithDesiredEndState(Simulation simulation, SimulationContext initialContext, IsSimulationCompleteDelegate checkForSuccessDelegate)
        {
            Simulator simulator = new Simulator(simulation, initialContext);

            simulator.IsSimulationComplete = checkForSuccessDelegate;
            return(simulator);
        }
示例#6
0
        public async Task <List <AgentStatistic> > RunSim(int simulationId, int simulationNumber)
        {
            AgentStatistic.Log = new List <string>();
            Debug.WriteLine("Simulation Starts");
            _messageHub.SendToAllClients("Simulation starts...");


            using (var context = new SimulationContext(isDefaultContextForProcess: true))
            {
                // initialise the model
                var system = await CreateModel(context : context, simulationId : simulationId, simNr : simulationNumber);

                // instantate a new simulator
                var simulator = new Simulator();


                // run the simulation
                await simulator.SimulateAsync(0);

                // Debug
                Debuglog(simulationContext: context, productionDomainContextContext: _productionDomainContext, simNr: simulationNumber, simId: simulationId);

                var simulationNr = _productionDomainContext.GetSimulationNumber(simulationId, SimulationType.Decentral);
                Statistics.UpdateSimulationId(simulationId, SimulationType.Decentral, simulationNumber);
                _productionDomainContext.SimulationWorkschedules.AddRange(SimulationWorkschedules);
                _productionDomainContext.SaveChanges();
                SaveStockExchanges(simulationId, simulationNr, context);
                //UpdateStockExchanges(simulationId, simulationNr);
            }
            return(Agent.AgentStatistics);
        }
示例#7
0
        private static void InitiateModel(SimulationContext context, int nbLifts, int nbFloors, int liftMaximumCapacity, int liftMethod, int simulationMinuteTime, int seed, long meanWorkTime, double meanPerson)
        {
            lifts = new List <Lift>();
            Random rand = new Random();

            List <ConcurrentQueue <Person> > personsQueues = new List <ConcurrentQueue <Person> >();

            for (int i = 0; i < nbFloors; i++)
            {
                personsQueues.Add(new ConcurrentQueue <Person>());
            }

            personGenerator = new PersonGenerator(personsQueues, nbFloors, meanPerson, simulationMinuteTime);

            for (int i = 0; i < nbLifts; i++)
            {
                if (liftMethod == 0)
                {
                    lifts.Add(new Lift(liftMaximumCapacity, nbFloors, new Random(seed), personGenerator, new LinearScanOrdonancer((int)LinearScanOrdonancer.Heading.UPWARDS, 0), meanWorkTime));
                }
                if (liftMethod == 1)
                {
                    lifts.Add(new Lift(liftMaximumCapacity, nbFloors, new Random(seed), personGenerator, new ShorterSeekTimeFirstOrdonancer((int)LinearScanOrdonancer.Heading.UPWARDS, 0), meanWorkTime));
                }
                if (liftMethod == 2)
                {
                    lifts.Add(new Lift(liftMaximumCapacity, nbFloors, new Random(seed), personGenerator, new DefaultOrdonancer((int)LinearScanOrdonancer.Heading.UPWARDS, 0), meanWorkTime));
                }
            }

            new SimulationEndTrigger(() => context.TimePeriod >= simulationMinuteTime * 60 && IsModelEmpty(context));
        }
示例#8
0
        /// <summary>
        /// Run this example
        /// </summary>
        public static void Run()
        {
            // Make a simulation context
            using (var context = new SimulationContext(isDefaultContextForProcess: true))
            {
                // Add the resources that represent the staff of the call center
                context.Register <Level1CallCenterStaffMember>(new Level1CallCenterStaffMember()
                {
                    Capacity = 10
                });
                context.Register <Level2CallCenterStaffMember>(new Level2CallCenterStaffMember()
                {
                    Capacity = 5
                });

                // Add the processes that represent the phone calls to the call center
                IEnumerable <Call> calls = GeneratePhoneCalls(context,
                                                              numberOfCalls: 500,
                                                              level1CallTime: 120,
                                                              level2CallTime: 300,
                                                              callTimeVariability: 0.5,
                                                              callStartTimeRange: 14400);

                // instantate a new simulator
                var simulator = new Simulator();

                // run the simulation
                simulator.Simulate();

                // output the statistics
                OutputResults(calls);
            }
        }
示例#9
0
        public void AddToTest()
        {
            var ctx = new SimulationContext(true);

            Random        random       = new Random();
            List <Entity> testEntities = CreateEntities(ctx.LocalSpace, 100);

            EntityPool original = new EntityPool(ctx);

            foreach (var e in testEntities)
            {
                Assert.IsTrue(original.Insert(e));
            }
            original.VerifyIntegrity();

            var h0 = original.HashDigest;

            for (int i = 0; i < 100; i++)
            {
                EntityPool compare = new EntityPool(ctx);
                random.Shuffle(testEntities);
                foreach (var e in testEntities)
                {
                    Assert.IsTrue(compare.Insert(e));
                }
                compare.VerifyIntegrity();
                var h1 = compare.HashDigest;
                Assert.AreEqual(h0, h1);
            }
        }
示例#10
0
        void SimulateScenariosCallback(object context)
        {
            Interval <int, object> pi      = (Interval <int, object>)context;
            SimulationContext      simData = pi.data as SimulationContext;

            SimulateScenariosCallback(simData.paths, simData.s0, simData.v0, simData.kappa, simData.theta, simData.sigma, simData.rho, simData.horizon, pi.sp, pi.ep);
        }
示例#11
0
        public void EntityMotionTest()
        {
            int        numEntities = 100;
            var        ctx         = new SimulationContext(true);
            EntityPool pool        = new EntityPool(EntityPoolTests.CreateEntities(ctx.LocalSpace, numEntities, i => new RandomMotion()), ctx);

            InconsistencyCoverage ic = InconsistencyCoverage.NewCommon();

            for (int i = 0; i < 100; i++)
            {
                var             old = pool.ToArray();
                EntityChangeSet set = new EntityChangeSet();
                ctx.SetGeneration(i);
                var errors = pool.TestEvolve(set, InconsistencyCoverage.NewCommon(), i, TimeSpan.FromSeconds(1));
                Assert.IsNull(errors, errors != null ? errors[0].ToString() : "");
                Assert.AreEqual(numEntities, set.FindNamedSet("motions").Size);
                foreach (var e in old)
                {
                    var m = set.FindMotionOf(e.ID.Guid);
                    Assert.IsNotNull(m);
                    Assert.AreNotEqual(m.TargetLocation, m.Origin.Position, i.ToString());
                    Assert.IsTrue(Simulation.FullSimulationSpace.Contains(m.TargetLocation));
                    Assert.IsTrue(Simulation.MySpace.Contains(m.TargetLocation));
                }

                Assert.AreEqual(0, set.Execute(pool, ic, ctx));
                Assert.AreEqual(numEntities, pool.Count);
                Entity e1;
                foreach (var e in old)
                {
                    Assert.IsTrue(pool.Find(e.ID.Guid, out e1));
                    Assert.AreNotEqual(e.ID.Position, e1.ID.Position);
                }
            }
        }
        public void CanComplete_BeforeAndAfterEvent_ReturnsTrueOnlyAfterEvent()
        {
            using (var context = new SimulationContext(isDefaultContextForProcess: true)){
                var waitInstruction = new WaitNotificationInstruction <object>();
                var process         = new InstructionListTestProcess(new List <InstructionBase>()
                {
                    waitInstruction
                });

                context.MoveToTimePeriod(0);
                process.SimulationState.InstructionEnumerator = process.Simulate();
                process.SimulationState.InstructionEnumerator.MoveNext();

                var testEvent        = new TestNotification();
                var raiseInstruction = new RaiseNotificationInstruction <object>(testEvent);

                long?nextTimePeriodCheck;
                bool canComplete = waitInstruction.CanComplete(context, out nextTimePeriodCheck);

                Assert.IsFalse(canComplete);
                Assert.IsNull(nextTimePeriodCheck);

                raiseInstruction.Complete(context);

                canComplete = waitInstruction.CanComplete(context, out nextTimePeriodCheck);

                Assert.IsTrue(canComplete);
                Assert.IsNull(nextTimePeriodCheck);
            }
        }
        public void Complete_ResourcesAllocated_ResourcesDeallocated()
        {
            using (var context = new SimulationContext())
            {
                int resouceCapacity  = 5;
                var testResourceSet1 = new TestResource(context, resouceCapacity)
                {
                    Code = "First", Priority = 10
                };
                context.Register <TestResource>(testResourceSet1);

                var allocateInstruction = new AllocateInstruction <TestResource>(resouceCapacity);
                allocateInstruction.Complete(context);

                Assert.AreEqual(resouceCapacity, testResourceSet1.Allocated);
                Assert.AreEqual(testResourceSet1.Allocated, allocateInstruction
                                .Allocations
                                .First(al => al.Key == testResourceSet1)
                                .Value);

                var releaseInstruction = new ReleaseInstruction <TestResource>(allocateInstruction);

                long?nextTimePeriodCheck;
                bool canComplete = releaseInstruction.CanComplete(context, out nextTimePeriodCheck);

                Assert.IsTrue(canComplete);
                Assert.IsNull(nextTimePeriodCheck);

                releaseInstruction.Complete(context);

                Assert.AreEqual(0, testResourceSet1.Allocated);
                Assert.IsTrue(allocateInstruction.IsReleased);
            }
        }
            public override bool CanComplete(SimulationContext context, out long?skipFurtherChecksUntilTimePeriod)
            {
                HasCanCompleteBeenCalled = true;

                skipFurtherChecksUntilTimePeriod = CanCompleteNextTimePeriodResult;
                return(CanCompleteResult);
            }
示例#15
0
        protected override void OnCreate()
        {
            m_BuildPhysicsWorldSystem = World.GetOrCreateSystem <KitchenBuildPhysicsWorld>();

            SimulationContext = new SimulationContext();
            SimulationContext.Reset(ref m_BuildPhysicsWorldSystem.PhysicsWorld);
        }
示例#16
0
        /// <summary>
        /// Determines whether this instruction can complete in the current time period
        /// </summary>
        /// <returns>
        /// <c>true</c> if this instance can complete.
        /// </returns>
        /// <param name='context'>
        /// Context providing state information for the current simulation
        /// </param>
        /// <param name='skipFurtherChecksUntilTimePeriod'>
        /// Output parameter used to specify a time period at which this instruction should be checked again.  This should be left null if it is not possible to determine when this instruction can complete.
        /// </param>
        public override bool CanComplete(SimulationContext context, out long?skipFurtherChecksUntilTimePeriod)
        {
            skipFurtherChecksUntilTimePeriod = null;

            // it is always possible to release
            return(true);
        }
        public void Complete_ActivitySpecified_ActivityScheduled()
        {
            using (var context = new SimulationContext(isDefaultContextForProcess:true)){

                long waitTime = 10;
                var activity = new Activity();

                var instruction = new ScheduleActivityInstruction(activity, waitTime);

                long? nextTimePeriod;
                bool canComplete = instruction.CanComplete(context, out nextTimePeriod);

                Assert.IsTrue(canComplete);
                Assert.IsNull(nextTimePeriod);

                instruction.Complete(context);

                context.MoveToTimePeriod(0);

                var process = context.ActiveProcesses.FirstOrDefault(p=>p is ActivityHostProcess);
                var activityHost = process as ActivityHostProcess;

                Assert.IsNotNull(process);
                Assert.IsNotNull(activityHost);

                Assert.AreEqual(waitTime, activityHost.WaitTime);
                Assert.AreEqual(activity, activityHost.Activity);
            }
        }
        public void Complete_Multiple_ReturnsTrueOnlyWhenEnoughResources()
        {
            using (var context = new SimulationContext(isDefaultContextForProcess:true)){

                int resouceCapacity = 5;
                var testResourceSet1 = new TestResource(resouceCapacity) { Code = "First", Priority = 10 };
                context.Register<TestResource>(testResourceSet1);

                // try to allocate one more than the total resources
                var allocateInstruction = new AllocateInstruction<TestResource>(resouceCapacity + 1);

                long? nextTimePeriodCheck;
                bool canComplete = allocateInstruction.CanComplete(context, out nextTimePeriodCheck);

                // allocation not possilbe
                Assert.IsNull(nextTimePeriodCheck);
                Assert.IsFalse(canComplete);

                // try to allocate the max available
                allocateInstruction = new AllocateInstruction<TestResource>(resouceCapacity);
                canComplete = allocateInstruction.CanComplete(context, out nextTimePeriodCheck);

                // allocation is possible
                Assert.IsNull(nextTimePeriodCheck);
                Assert.IsTrue(canComplete);

                allocateInstruction.Complete(context);

                Assert.AreEqual(resouceCapacity, testResourceSet1.Allocated);
                Assert.AreEqual(testResourceSet1.Allocated, allocateInstruction
                   .Allocations
                   .First(al=>al.Key == testResourceSet1)
                   .Value);
            }
        }
示例#19
0
        public void MoveToTimePeriod_TimePeriodSpecified_ProcessCollectionsInitialised()
        {
            using (var context = new SimulationContext()){
                var process1 = new Process(context);
                var process2 = new Process(context);
                var process3 = new Process(context);

                var processes = new List <Process>()
                {
                    process1,
                    process2,
                    process3
                };

                Assert.AreEqual(0, context.TimePeriod);
                context.MoveToTimePeriod(1);
                Assert.AreEqual(1, context.TimePeriod);

                Assert.AreEqual(processes.Count, context.ActiveProcesses.Count);
                foreach (var process in processes)
                {
                    Assert.IsTrue(context.ActiveProcesses.Contains(process));
                    Assert.IsTrue(context.ProcessesRemainingThisTimePeriod.Contains(process));
                }
            }
        }
示例#20
0
        /// <summary>
        /// Determines whether this instruction can complete in the current time period.  The composite instruction can complete, if all contained instructions can complete
        /// </summary>
        /// <returns>
        /// <c>true</c> if this instance can complete.
        /// </returns>
        /// <param name='context'>
        /// Context providing state information for the current simulation
        /// </param>
        /// <param name='skipFurtherChecksUntilTimePeriod'>
        /// Output parameter used to specify a time period at which this instruction should be checked again.  This should be left null if it is not possible to determine when this instruction can complete.
        /// </param>
        public override bool CanComplete(SimulationContext context, out long? skipFurtherChecksUntilTimePeriod)
        {
            skipFurtherChecksUntilTimePeriod = null;

            bool canComplete = true;
            bool nullCheckTimePeriodEncountered = false;

            // iterate through all contained instructions, check whether they can all complete
            // the value returned in skipFurtherChecksUntilTimePeriod is the lowest value of any instrution, and null if any return null for this value
            foreach(InstructionBase instruction in _instructions){
                long? nextCheckTimePeriod = null;

                bool thisInstructionCanComplete = instruction.CanComplete(context, out nextCheckTimePeriod);

                if (!thisInstructionCanComplete){
                    canComplete = false;

                    if (nextCheckTimePeriod == null){
                        nullCheckTimePeriodEncountered = true;
                        nextCheckTimePeriod = null;
                    }
                    else if (!nullCheckTimePeriodEncountered &&
                 			(skipFurtherChecksUntilTimePeriod == null || skipFurtherChecksUntilTimePeriod > nextCheckTimePeriod)){
                        skipFurtherChecksUntilTimePeriod = nextCheckTimePeriod;
                    }
                }
            }

            if (canComplete){
                skipFurtherChecksUntilTimePeriod = null;
            }

            return canComplete;
        }
示例#21
0
        public override void ProcessEntity(SimulationContext context, Entity entity, BehaviorComponent component1, PhysicsComponent component2)
        {
            Body body      = component2.Body;
            var  neighbors = Neighbors(radius, body);

            var desire = Vector3.Zero;

            desire += Steering.Cohesion(radius, body.LinearPosition, neighbors);
            desire += Steering.Separation(radius, body.LinearPosition, neighbors);
            desire += Steering.Traveling(neighbors);
            desire += Steering.Arrival(Vector3.Zero, body, 1, 1);

            var angularTarget   = Steering.Alignment(body.AngularPosition, neighbors);
            var angularDistance = Quaternion.Distance(body.AngularPosition, angularTarget);

            //Console.Write(angularDistance.ToString("n2") + ", ");

            if (angularDistance > 0)
            {
                var scaled = Math.Min(1, maxAngularVelocity * context.DeltaTime / angularDistance);
                body.AngularPosition = Quaternion.Lerp(body.AngularPosition, angularTarget, scaled);
            }

            body.LinearVelocity += desire * context.DeltaTime;

            body.ClearForces();
            body.AngularPosition = Quaternion.LookAt(-body.LinearVelocity, body.AngularPosition.Transform(Vector3.Up));
        }
示例#22
0
        public WindManager(SimulationContext ctx) : base(ctx)
        {
            //Create and fill UvData
            InitBuffer();

            _windLayers = new List <WindLayer>();
        }
        public void CanComplete_BeforeAndAfterEvent_ReturnsTrueOnlyAfterEvent()
        {
            using (var context = new SimulationContext(isDefaultContextForProcess:true)){

                var waitInstruction = new WaitNotificationInstruction<object>();
                var process = new InstructionListTestProcess(new List<InstructionBase>(){ waitInstruction});

                context.MoveToTimePeriod(0);
                process.SimulationState.InstructionEnumerator = process.Simulate();
                process.SimulationState.InstructionEnumerator.MoveNext();

                var testEvent = new TestNotification();
                var raiseInstruction = new RaiseNotificationInstruction<object>(testEvent);

                long? nextTimePeriodCheck;
                bool canComplete = waitInstruction.CanComplete(context, out nextTimePeriodCheck);

                Assert.IsFalse(canComplete);
                Assert.IsNull(nextTimePeriodCheck);

                raiseInstruction.Complete(context);

                canComplete = waitInstruction.CanComplete(context, out nextTimePeriodCheck);

                Assert.IsTrue(canComplete);
                Assert.IsNull(nextTimePeriodCheck);
            }
        }
示例#24
0
 public void Init(SimulationContext context, List<User> users, ReportProgressDelegate reporter)
 {
     List<User> ulRsrpFailUserList;
     List<User> dlRsrpFailUserList;
     ICommonChannelMeasure measure = context.ProcessorFactory.BuildCommonChannelMeasure();
     ITotalLossMatrix matrix = context.ProcessorFactory.BuildTotalLossMatrix(context.SimulationInfo.SubSysInterface, context.SimulationInfo.Coefficientabc);
     List<ISimulationUser> userList = this.InitSimulationUser(users);
     context.DataManager.SimulationUserList = userList;
     context.DataManager.UlUserNum = 0;
     context.DataManager.DlUserNum = 0;
     foreach (SimulationUser user in userList)
     {
         this.InitUserState(user, context.DataManager);
     }
     matrix.InitUserTotalLossList(userList, context.DataManager.SimulationCarrierList, reporter);
     context.ProcessorFactory.BuildBestServerCell().DetermineUserServerCell(userList, out dlRsrpFailUserList, out ulRsrpFailUserList);
     context.DataManager.DlRsrpFailUserList = dlRsrpFailUserList;
     context.DataManager.UlRsrpFailUserList = ulRsrpFailUserList;
     //所有用户
     List<ISimulationUser> userlist = new List<ISimulationUser>();
     foreach (SimulationCarrier carrier in context.DataManager.SimulationCarrierList)
     {
         userlist.AddRange(carrier.UlUserList);
         userlist.AddRange(carrier.DlUserList);
     }
     this.InitUsersMIMOClutterGain(userlist, context);
     this.GetMinAndMaxSinrTarget(userlist);
     //计算用户的初始的RS sinr,即IntialDlRsSinr
     measure.CalculateIntialDlRsSinr(userlist);
 }
示例#25
0
        /// <summary>
        /// Complete the instruction.  For this instruction type, this involves putting the simulation into the terminating state.
        /// </summary>
        /// <param name='context'>
        /// Context providing state information for the current simulation.
        /// </param>
        public override void Complete(SimulationContext context)
        {
            base.Complete(context);

            // Add the event to the wait instructions of all processes currently waiting
            if (context.ActiveProcesses != null)
            {
                foreach (Process process in context.ActiveProcesses)
                {
                    if (process.SimulationState != null &&
                        process.SimulationState.InstructionEnumerator != null &&
                        process.SimulationState.InstructionEnumerator.Current != null &&
                        process.SimulationState.InstructionEnumerator.Current is WaitNotificationInstruction <TNotification> )
                    {
                        var waitEventInstruction = (WaitNotificationInstruction <TNotification>)process.SimulationState.InstructionEnumerator.Current;

                        if (waitEventInstruction.MatchingCondition == null || waitEventInstruction.MatchingCondition(Notification))
                        {
                            waitEventInstruction.Notifications.Add(Notification);
                        }
                    }
                }
            }

            CompletedAtTimePeriod = context.TimePeriod;
        }
        public override IEnumerable<PlayerRecommendation> Analyse(Player player, Fixture fixture, SimulationContext context)
        {
            if (PointMapper == null)
                throw new ArgumentException("Invalid property", nameof(PointMapper));

            var res = new PlayerRecommendation();
            res.Type = PlayerRecommendationType.PlayerPlaytime;

            var playerTeam = player.GetLeagueTeam(fixture);
            double teamPlayedMinutes = playerTeam.GetPlayedMinutesBeforeFixtureForTeam(fixture);
            double playerMinutes = player.GetPlayedMinutesBeforeFixtureForPlayer(fixture);
            var percentage = teamPlayedMinutes > 0
                ? playerMinutes / teamPlayedMinutes
                : 0;

            var valueMap = new ValueMap();
            valueMap["minutes"] = playerMinutes;
            valueMap["percentage"] = percentage;
            //valueMap["playedgames"] = ;
            //valueMap["substitutes-in"] = ;
            //valueMap["substitutes-out"] = ;
            // todo: add more data points (subs, recent playtime (5 last team games), recent subs)

            res.Points = PointMapper.Test(valueMap).Sum(x => x.Points);
            yield return res;
        }
示例#27
0
        public void Simulate_Terminated_SimulationEndsAtTerminatedPeriod()
        {
            using (var context = new SimulationContext(isDefaultContextForProcess: true)){
                var processor1Instructions = new List <InstructionBase>()
                {
                    new WaitInstruction(5),
                    new WaitInstruction(10)
                };

                var processor2Instructions = new List <InstructionBase>()
                {
                    new WaitInstruction(2),
                    new TerminateSimulationInstruction(),
                    new WaitInstruction(9),
                };

                var processor1 = new InstructionListTestProcess(processor1Instructions);
                var processor2 = new InstructionListTestProcess(processor2Instructions);

                var simulator = new Simulator();

                simulator.Simulate();

                Assert.AreEqual(2, context.TimePeriod);

                Assert.IsNull(processor1Instructions[0].CompletedAtTimePeriod);
                Assert.IsNull(processor1Instructions[1].CompletedAtTimePeriod);
                Assert.AreEqual(2, processor2Instructions[0].CompletedAtTimePeriod);
                Assert.AreEqual(2, processor2Instructions[1].CompletedAtTimePeriod);
                Assert.IsNull(processor2Instructions[2].CompletedAtTimePeriod);
            }
        }
        public void Simulate_ActivitySpecified_ActivityFiredAtTheAppropriateTime()
        {
            using(var context = new SimulationContext(isDefaultContextForProcess: true)){

                var notification = new TestNotification();
                var activity = new TestActivity(new List<InstructionBase>() { new RaiseNotificationInstruction<TestNotification>(notification) });
                long waitTime = 10;

                var process = new ActivityHostProcess(activity, waitTime);

                Assert.IsNotNull(process.SimulationState);
                Assert.IsTrue(process.SimulationState.IsActive);

                var registeredProcesses = context.GetByType<Process>();
                Assert.IsTrue(registeredProcesses.Contains(process));

                var enumerator = process.Simulate();

                bool couldMove = enumerator.MoveNext();
                Assert.IsTrue(couldMove);

                // first instruction should be the wait instruction
                Assert.IsTrue(enumerator.Current is WaitInstruction);
                Assert.AreEqual(waitTime, ((WaitInstruction)enumerator.Current).NumberOfPeriodsToWait);

                couldMove = enumerator.MoveNext();
                Assert.IsTrue(couldMove);

                Assert.IsTrue(enumerator.Current is RaiseNotificationInstruction<TestNotification>);
                Assert.AreEqual(notification, ((RaiseNotificationInstruction<TestNotification>)enumerator.Current).Notification);

                couldMove = enumerator.MoveNext();
                Assert.IsFalse(couldMove);
            }
        }
示例#29
0
 public void NotifyOnSuccess(SimulationContext context, ref Violation newViolation)
 {
     if (this.OnSuccess != null)
     {
         this.OnSuccess(context, ref newViolation);
     }
 }
        public override IEnumerable<PlayerRecommendation> Analyse(Player player, Fixture fixture, SimulationContext context)
        {
            if (Mapper == null)
                throw new ArgumentException("Invalid property", nameof(Mapper));

            var res = new PlayerRecommendation();
            res.Type = PlayerRecommendationType.ChanceOfPlaying;

            // old:
            //// Negatives
            //if (player.Fantasy.ChanceOfPlayingNextFixture >= 0)
            //{
            //    if (player.Fantasy.ChanceOfPlayingNextFixture <= 0)
            //        res.Points = -10;
            //    else if (player.Fantasy.ChanceOfPlayingNextFixture <= 0.25)
            //        res.Points = -3;
            //    else if (player.Fantasy.ChanceOfPlayingNextFixture <= 0.50)
            //        res.Points = -2;
            //    else if (player.Fantasy.ChanceOfPlayingNextFixture <= 0.75)
            //        res.Points = -1;
            //}

            var valueMap = new ValueMap();
            valueMap["percentage"] = player.Fantasy.ChanceOfPlayingNextFixture;

            res.Points = Mapper.Test(valueMap).Sum(x => x.Points);
            yield return res;
        }
示例#31
0
        public void CreatureTestInitialize()
        {
            _layout = new Layout(1, "Layout 1", 100, 100);
            for (var i = 50; i <= 100; i++)
            {
                for (var j = 1; j <= 100; j++)
                {
                    _layout.addTerritory(i, j);
                }
            }
            _context = new SimulationContext(_layout);

            _species = new Species("Dog", 15, 4, Digestion.Carnivore, 20, 60, 10, 100, 0, 95, 20);

            _creature1 = new Creature(51, 56, _context, 70, 80, _species, Direction.N);
            _creature2 = new Creature(70, 82, _context, 70, 80, _species, Direction.E);
            _creature3 = new Creature(83, 85, _context, 70, 80, _species, Direction.S);
            _context.AddCreature(_creature1);
            _context.AddCreature(_creature2);
            _context.AddCreature(_creature3);
            _context.AddPlant(50, 51, 56);
            _context.AddPlant(60, 84, 63);
            _context.AddObstacle(84, 64);
            _context.AddObstacle(100, 100);
            _context.AddObstacle(83, 86);
        }
示例#32
0
        public override void ProcessEntity(SimulationContext context, Entity entity, TransformComponent component)
        {
            component.LocalTransform = Matrix4.Transformation(component.Scaling, component.Rotation, component.Translation);
            if (component.Parent == null)
            {
                component.GlobalTransform = component.LocalTransform;
            }
            else
            {
                switch (component.Inheritance)
                {
                case TransformInheritance.All:
                case TransformInheritance.Default:
                    //component.GlobalTransform = component.Parent.GlobalTransform * component.LocalTransform;
                    component.GlobalTransform = component.LocalTransform * component.Parent.GlobalTransform;
                    break;

                case TransformInheritance.Translation:
                    var global = component.LocalTransform;
                    //global.Row4 += component.Parent.GlobalTransform.Row4;
                    global.Row(3, global.Row(3) + component.Parent.GlobalTransform.Row(3));
                    global.M44 = 1;
                    component.GlobalTransform = global;
                    break;

                case TransformInheritance.Rotation | TransformInheritance.Translation:
                    component.GlobalTransform = component.LocalTransform * RemoveScale(component.Parent.GlobalTransform);
                    break;

                default:
                    break;
                }
            }
        }
        public void Complete_ResourcesAllocated_ResourcesDeallocated()
        {
            using (var context = new SimulationContext(isDefaultContextForProcess:true)){

                int resouceCapacity = 5;
                var testResourceSet1 = new TestResource(resouceCapacity) { Code = "First", Priority = 10 };
                context.Register<TestResource>(testResourceSet1);

                var allocateInstruction = new AllocateInstruction<TestResource>(resouceCapacity);
                allocateInstruction.Complete(context);

                Assert.AreEqual(resouceCapacity, testResourceSet1.Allocated);
                Assert.AreEqual(testResourceSet1.Allocated, allocateInstruction
                   .Allocations
                   .First(al=>al.Key == testResourceSet1)
                   .Value);

                var releaseInstruction = new ReleaseInstruction<TestResource>(allocateInstruction);

                long? nextTimePeriodCheck;
                bool canComplete = releaseInstruction.CanComplete(context, out nextTimePeriodCheck);

                Assert.IsTrue(canComplete);
                Assert.IsNull(nextTimePeriodCheck);

                releaseInstruction.Complete(context);

                Assert.AreEqual(0, testResourceSet1.Allocated);
                Assert.IsTrue(allocateInstruction.IsReleased);
            }
        }
示例#34
0
        public void Simulate_Terminated_SimulationEndsAtTerminatedPeriod()
        {
            using (var context = new SimulationContext(isDefaultContextForProcess: true)){
                var processor1Instructions = new List<InstructionBase>(){
                    new WaitInstruction(5),
                    new WaitInstruction(10)
                };

                var processor2Instructions = new List<InstructionBase>(){
                    new WaitInstruction(2),
                    new TerminateSimulationInstruction(),
                    new WaitInstruction(9),
                };

                var processor1 = new InstructionListTestProcess(processor1Instructions);
                var processor2 = new InstructionListTestProcess(processor2Instructions);

                var simulator = new Simulator();

                simulator.Simulate();

                Assert.AreEqual(2, context.TimePeriod);

                Assert.IsNull(processor1Instructions[0].CompletedAtTimePeriod);
                Assert.IsNull(processor1Instructions[1].CompletedAtTimePeriod);
                Assert.AreEqual(2, processor2Instructions[0].CompletedAtTimePeriod);
                Assert.AreEqual(2, processor2Instructions[1].CompletedAtTimePeriod);
                Assert.IsNull(processor2Instructions[2].CompletedAtTimePeriod);
            }
        }
        public void Complete_ContextPassed_ProcessActivated()
        {
            using (var context = new SimulationContext(isDefaultContextForProcess:true)){
                var testProcess = new InstructionListTestProcess(new WaitInstruction(10));
                var enumerator = testProcess.Simulate();
                testProcess.SimulationState.InstructionEnumerator = enumerator;

                context.MoveToTimePeriod(0);
                Assert.IsTrue(context.ActiveProcesses.Contains(testProcess));
                // clear the remaining process queue
                context.ProcessesRemainingThisTimePeriod.Clear();

                enumerator.MoveNext();

                var instruction = new InterruptInstruction(testProcess);

                long? nextTimePeriodCheck = null;
                bool canComplete = instruction.CanComplete(context, out nextTimePeriodCheck);

                Assert.IsTrue(canComplete);
                instruction.Complete(context);

                Assert.IsTrue(testProcess.SimulationState.IsInterrupted);
                // the process should be back in the queue
                Assert.IsTrue(context.ProcessesRemainingThisTimePeriod.Contains(testProcess));
                Assert.IsTrue(enumerator.Current.IsInterrupted);
                Assert.IsFalse(enumerator.Current.IsCompleted);
            }
        }
        protected override async Task Context()
        {
            await base.Context();

            _snapshot = await sut.MapToSnapshot(_populationSimulation, _project);

            var populationSimulation = new PopulationSimulation
            {
                Properties         = _simulationProperties,
                SimulationSettings = _settings,
                Model = _model
            };

            populationSimulation.AddUsedBuildingBlock(new UsedBuildingBlock("IndTemplateId", PKSimBuildingBlockType.Individual)
            {
                BuildingBlock = _individual
            });

            A.CallTo(() => _simulationFactory.CreateFrom(_population, A <IReadOnlyList <Compound> > ._, A <ModelProperties> ._, null)).Returns(populationSimulation);

            A.CallTo(() => _populationAnalysisChartMapper.MapToModel(_snapshotPopulationAnalysisChart, A <SimulationAnalysisContext> ._))
            .Invokes(x => _context = x.GetArgument <SimulationAnalysisContext>(1))
            .Returns(_populationSimulationAnalysisChart);

            _snapshotSimulationContext = new SimulationContext(run: false, new SnapshotContext(_project, 10));
        }
示例#37
0
        public void SimpleEntityFaultTest()
        {
            var        ctx  = new SimulationContext(true);
            EntityPool pool = new EntityPool(EntityPoolTests.CreateEntities(ctx.LocalSpace, 100,
                                                                            new RandomLogic(new Type[] { typeof(ConsistentLogic), typeof(FaultLogic) }).Instantiate), ctx);

            InconsistencyCoverage ic = InconsistencyCoverage.NewCommon();
            int any = -1;

            for (int i = 0; i < 8; i++)
            {
                EntityChangeSet set = new EntityChangeSet();
                ctx.SetGeneration(i);
                var errors = pool.TestEvolve(set, ic, i, TimeSpan.FromSeconds(1));
                if (errors != null)
                {
                    Assert.IsTrue(ic.OneCount > 0);
                    if (any == -1)
                    {
                        any = i;
                    }
                }
                ic = ic.Grow(true);
                Assert.IsTrue(ic.Size == InconsistencyCoverage.CommonResolution);
            }
            if (any == 0)
            {
                Assert.AreEqual(ic.OneCount, ic.Size.Product);
            }
        }
示例#38
0
        public void Complete_ActivitySpecified_ActivityScheduled()
        {
            using (var context = new SimulationContext()){
                long waitTime = 10;
                var  activity = new MyActivity();

                var instruction = new ScheduleActivityInstruction(activity, waitTime);

                long?nextTimePeriod;
                bool canComplete = instruction.CanComplete(context, out nextTimePeriod);

                Assert.IsTrue(canComplete);
                Assert.IsNull(nextTimePeriod);

                instruction.Complete(context);

                context.MoveToTimePeriod(0);

                var process      = context.ActiveProcesses.FirstOrDefault(p => p is ActivityHostProcess);
                var activityHost = process as ActivityHostProcess;

                Assert.IsNotNull(process);
                Assert.IsNotNull(activityHost);

                Assert.AreEqual(waitTime, activityHost.WaitTime);
                Assert.AreEqual(activity, activityHost.Activity);
            }
        }
        public void Complete_ContextPassed_ProcessActivated()
        {
            using (var context = new SimulationContext(isDefaultContextForProcess: true)){
                var testProcess = new InstructionListTestProcess(new WaitInstruction(10));
                var enumerator  = testProcess.Simulate();
                testProcess.SimulationState.InstructionEnumerator = enumerator;

                context.MoveToTimePeriod(0);
                Assert.IsTrue(context.ActiveProcesses.Contains(testProcess));
                // clear the remaining process queue
                context.ProcessesRemainingThisTimePeriod.Clear();

                enumerator.MoveNext();

                var instruction = new InterruptInstruction(testProcess);

                long?nextTimePeriodCheck = null;
                bool canComplete         = instruction.CanComplete(context, out nextTimePeriodCheck);

                Assert.IsTrue(canComplete);
                instruction.Complete(context);

                Assert.IsTrue(testProcess.SimulationState.IsInterrupted);
                // the process should be back in the queue
                Assert.IsTrue(context.ProcessesRemainingThisTimePeriod.Contains(testProcess));
                Assert.IsTrue(enumerator.Current.IsInterrupted);
                Assert.IsFalse(enumerator.Current.IsCompleted);
            }
        }
示例#40
0
        /// <summary>
        /// Run this example
        /// </summary>
        public static void Run()
        {
            // Make a simulation context
            using (var context = new SimulationContext(isDefaultContextForProcess: true))
            {
                // Add the resources that represent the staff of the call center
                context.Register<Level1CallCenterStaffMember>(new Level1CallCenterStaffMember(){ Capacity = 10 });
                context.Register<Level2CallCenterStaffMember>(new Level2CallCenterStaffMember(){ Capacity = 5 });

                // Add the processes that represent the phone calls to the call center
                IEnumerable<Call> calls = GeneratePhoneCalls(context,
                    numberOfCalls: 500,
                    level1CallTime: 120,
                    level2CallTime: 300,
                    callTimeVariability: 0.5,
                    callStartTimeRange: 14400);

                // instantate a new simulator
                var simulator = new Simulator();

                // run the simulation
                simulator.Simulate();

                // output the statistics
                OutputResults(calls);
            }
        }
        /// <summary>Establishes initial operating point for the transient analysis.</summary>
        public void EstablishDcBias(bool initCond = false)
        {
            context = null;             // reset;
            EnsureInitialized();

            // initial condition
            for (var i = 0; i < initialVoltages.Length; i++)
            {
                if (initialVoltages[i].HasValue)
                {
                    initVoltProxies[2 * i].Add(1);
                    initVoltProxies[2 * i + 1].Add(initialVoltages[i].Value);
                }
            }

            EstablishDcBias_Internal();

            var iterCount = LastNonLinearIterationCount;

            LastNonLinearIterationCount = 0;

            // rerun without initial voltages
            if (!initCond)
            {
                EstablishDcBias_Internal();
            }

            LastNonLinearIterationCount += iterCount;
            OnDcBiasEstablished();
        }
示例#42
0
        /// <summary>
        /// Creates the model.
        /// </summary>
        /// <param name='numberOfJobs'>
        /// Number of jobs to be generated.
        /// </param>
        private static List <Machine> CreateModel(SimulationContext context, int numberOfJobs)
        {
            var rand = new Random();

            var unprocessedJobsList = new List <Job>();

            // Create job queues of various work types
            var workTypeAJobQueue = new Queue <Job>();
            var workTypeBJobQueue = new Queue <Job>();
            var workTypeCJobQueue = new Queue <Job>();
            var workQueues        = new List <Queue <Job> >()
            {
                workTypeAJobQueue, workTypeBJobQueue, workTypeCJobQueue
            };

            var random = new Random();
            // create machines
            var machine1 = new Machine(jobQueue: workTypeAJobQueue, reliabilityPercentage: 95.0, repairTimeRequired: 15, unprocessedJobsList: unprocessedJobsList, random: random);
            var machine2 = new Machine(jobQueue: workTypeAJobQueue, reliabilityPercentage: 85.0, repairTimeRequired: 22, unprocessedJobsList: unprocessedJobsList, random: random);
            var machine3 = new Machine(jobQueue: workTypeBJobQueue, reliabilityPercentage: 99.0, repairTimeRequired: 15, unprocessedJobsList: unprocessedJobsList, random: random);
            var machine4 = new Machine(jobQueue: workTypeBJobQueue, reliabilityPercentage: 96.0, repairTimeRequired: 17, unprocessedJobsList: unprocessedJobsList, random: random);
            var machine5 = new Machine(jobQueue: workTypeCJobQueue, reliabilityPercentage: 98.0, repairTimeRequired: 20, unprocessedJobsList: unprocessedJobsList, random: random);

            var machines = new List <Machine>()
            {
                machine1,
                machine2,
                machine3,
                machine4,
                machine5
            };

            // create the jobs
            for (int i = 0; i < numberOfJobs; i++)
            {
                var newJob = new Job();

                newJob.ProcessingTimeRequiredByJobQueue[workTypeAJobQueue] = 5 + rand.Next(5);
                newJob.ProcessingTimeRequiredByJobQueue[workTypeBJobQueue] = 5 + rand.Next(5);
                newJob.ProcessingTimeRequiredByJobQueue[workTypeCJobQueue] = 5 + rand.Next(5);

                int index = rand.Next(workQueues.Count);
                // enque the job in one of the work queues
                workQueues[index].Enqueue(newJob);

                // and add it to the unprocessed job list
                unprocessedJobsList.Add(newJob);
            }

            // add a repair person
            new RepairPerson()
            {
                Capacity = 1
            };

            // add the end condition
            new SimulationEndTrigger(() => unprocessedJobsList.Count == 0);

            return(machines);
        }
        /// <summary>
        /// Complete the instruction.  For this instruction type, this involves putting the simulation into the stopping state.
        /// </summary>
        /// <param name='context'>
        /// Context providing state information for the current simulation.
        /// </param>
        public override void Complete(SimulationContext context)
        {
            base.Complete(context);

            context.IsSimulationStopping = true;

            CompletedAtTimePeriod = context.TimePeriod;
        }
示例#44
0
 public void init(SimulationContext context)
 {
     this.m_context = context;
     if (this.m_NextProcessor != null)
     {
         this.m_NextProcessor.init(context);
     }
 }
示例#45
0
 public void init(SimulationContext context)
 {
     this.m_context = context;
     this.m_PuschMeasure = context.ProcessorFactory.BuildPUSCHMeasure();
     if (this.m_NextProcessor != null)
     {
         this.m_NextProcessor.init(context);
     }
 }
        public void Constructor_SimulationContextExists_ResourceRegistered()
        {
            using(var context = new SimulationContext(isDefaultContextForProcess: true)){
                var element = new TestElement();

                var registeredElements = context.GetByType<TestElement>();
                Assert.IsTrue(registeredElements.Contains(element));
            }
        }
示例#47
0
 public void init(SimulationContext context)
 {
     this.m_context = context;
     this.m_UlScheduleProcessor = context.ProcessorFactory.BuildUlScheduleProcessor();
     this.m_UlScheduleProcessor.Init(this.m_context.DataManager.SimulationCarrierList);
     if (this.m_NextProcessor != null)
     {
         this.m_NextProcessor.init(this.m_context);
     }
 }
        public override IEnumerable<PlayerRecommendation> Analyse(Player player, Fixture fixture, SimulationContext context)
        {
            var res = new PlayerRecommendation();
            res.Type = PlayerRecommendationType.PlayerUnavailable;

            var unavailable = player.Fantasy.Unavailable;
            if (unavailable)
                res.Points = Points;
            yield return res;
        }
示例#49
0
 public void init(SimulationContext context)
 {
     this.m_context = context;
     this.m_PdschMeasure = context.ProcessorFactory.BuildPDSCHMeasure();
     this.m_PdschMeasure.DlPDSCHMeasureInit(context.DataManager.SimulationCarrierList);
     if (this.m_NextProcessor != null)
     {
         this.m_NextProcessor.init(context);
     }
 }
示例#50
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NSimulate.SimulationElement"/> class.
        /// </summary>
        /// <param name='context'>
        /// Context.
        /// </param>
        /// <param name='key'>
        /// Key.
        /// </param>
        public SimulationElement(SimulationContext context, object key)
        {
            Key = key;
            if (context != null)
            {
                context.Register(this.GetType(), this);
            }

            Context = context;
        }
示例#51
0
        /// <summary>
        /// Creates the model.
        /// </summary>
        /// <param name='numberOfJobs'>
        /// Number of jobs to be generated.
        /// </param>
        private static List<Machine> CreateModel(SimulationContext context, int numberOfJobs)
        {
            var rand = new Random();

            var unprocessedJobsList = new List<Job>();

            // Create job queues of various work types
            var workTypeAJobQueue = new Queue<Job>();
            var workTypeBJobQueue = new Queue<Job>();
            var workTypeCJobQueue = new Queue<Job>();
            var workQueues = new List<Queue<Job>>(){ workTypeAJobQueue, workTypeBJobQueue, workTypeCJobQueue };

            var random = new Random();
            // create machines
            var machine1 = new Machine(jobQueue: workTypeAJobQueue, reliabilityPercentage: 95.0, repairTimeRequired: 15, unprocessedJobsList: unprocessedJobsList, random: random);
            var machine2 = new Machine(jobQueue: workTypeAJobQueue, reliabilityPercentage: 85.0, repairTimeRequired: 22, unprocessedJobsList: unprocessedJobsList, random: random);
            var machine3 = new Machine(jobQueue: workTypeBJobQueue, reliabilityPercentage: 99.0, repairTimeRequired: 15, unprocessedJobsList: unprocessedJobsList, random: random);
            var machine4 = new Machine(jobQueue: workTypeBJobQueue, reliabilityPercentage: 96.0, repairTimeRequired: 17, unprocessedJobsList: unprocessedJobsList, random: random);
            var machine5 = new Machine(jobQueue: workTypeCJobQueue, reliabilityPercentage: 98.0, repairTimeRequired: 20, unprocessedJobsList: unprocessedJobsList, random: random);

            var machines = new List<Machine>()
            {
                machine1,
                machine2,
                machine3,
                machine4,
                machine5
            };

            // create the jobs
            for (int i = 0; i< numberOfJobs;i++){
                var newJob = new Job();

                newJob.ProcessingTimeRequiredByJobQueue[workTypeAJobQueue] = 5 + rand.Next(5);
                newJob.ProcessingTimeRequiredByJobQueue[workTypeBJobQueue] = 5 + rand.Next(5);
                newJob.ProcessingTimeRequiredByJobQueue[workTypeCJobQueue] = 5 + rand.Next(5);

                int index = rand.Next(workQueues.Count);
                // enque the job in one of the work queues
                workQueues[index].Enqueue(newJob);

                // and add it to the unprocessed job list
                unprocessedJobsList.Add(newJob);
            }

            // add a repair person
            new RepairPerson() { Capacity = 1};

            // add the end condition
            new SimulationEndTrigger(()=>unprocessedJobsList.Count == 0);

            return machines;
        }
示例#52
0
        public void Constructor_SimulationContextExists_ProcessRegistered()
        {
            using(var context = new SimulationContext(isDefaultContextForProcess: true)){
                var process = new Process();

                Assert.IsNotNull(process.SimulationState);
                Assert.IsTrue(process.SimulationState.IsActive);

                var registeredProcesses = context.GetByType<Process>();
                Assert.IsTrue(registeredProcesses.Contains(process));
            }
        }
        protected override void InitSimulation(int seed, LevelInfo level, PlayerInfo[] players, Slot[] slots)
        {
            Assembly levelAssembly = Assembly.Load(level.Type.AssemblyFile);
            Type levelType = levelAssembly.GetType(level.Type.TypeName);

            SimulationContext context = new SimulationContext(
                ExtensionLoader.DefaultTypeResolver,
                ExtensionLoader.ExtensionSettings);

            simulation = Activator.CreateInstance(levelType, context) as Level;

            // Player erzeugen
            LevelSlot[] levelSlots = new LevelSlot[AntMe.Level.MAX_SLOTS];
            for (int i = 0; i < AntMe.Level.MAX_SLOTS; i++)
            {
                // Skipp, falls nicht vorhanden
                if (players[i] == null)
                    continue;

                Assembly playerAssembly = Assembly.Load(players[i].Type.AssemblyFile);
                Type factoryType = playerAssembly.GetType(players[i].Type.TypeName);

                // Identify Name
                var playerAttributes = factoryType.GetCustomAttributes(typeof(FactoryAttribute), true);
                if (playerAttributes.Length != 1)
                    throw new Exception("Player does not have the right number of Player Attributes");

                FactoryAttribute playerAttribute = playerAttributes[0] as FactoryAttribute;

                // Find the right Mapping
                var mappingAttributes = playerAttribute.GetType().
                    GetCustomAttributes(typeof(FactoryAttributeMappingAttribute), false);
                if (mappingAttributes.Length != 1)
                    throw new Exception("Player Attribute has no valid Property Mapping Attribute");

                FactoryAttributeMappingAttribute mappingAttribute = mappingAttributes[0] as FactoryAttributeMappingAttribute;

                // Werte auslesen
                string name = playerAttribute.GetType().GetProperty(mappingAttribute.NameProperty).
                    GetValue(playerAttribute, null) as string;

                levelSlots[i] = new LevelSlot()
                {
                    FactoryType = factoryType,
                    Name = name,
                    Color = slots[i].ColorKey,
                    Team = slots[i].Team
                };
            }

            // Level initialisieren
            simulation.Init(seed, levelSlots);
        }
示例#54
0
        /// <summary>
        /// Determines whether this instruction can complete in the current time period
        /// </summary>
        /// <returns>
        /// <c>true</c> if this instance can complete.
        /// </returns>
        /// <param name='context'>
        /// Context providing state information for the current simulation
        /// </param>
        /// <param name='skipFurtherChecksUntilTimePeriod'>
        /// Output parameter used to specify a time period at which this instruction should be checked again.  This should be left null if it is not possible to determine when this instruction can complete.
        /// </param>
        public override bool CanComplete(SimulationContext context, out long? skipFurtherChecksUntilTimePeriod)
        {
            bool canComplete = false;

            long timePeriodToComplete = RaisedInTimePeriod + NumberOfPeriodsToWait;
            skipFurtherChecksUntilTimePeriod = timePeriodToComplete;
            if (context.TimePeriod >= timePeriodToComplete){
                canComplete = true;
            }

            return canComplete;
        }
        public void CanComplete_ConditionNotMet_ReturnsFalse()
        {
            using (var context = new SimulationContext(isDefaultContextForProcess: true)){
                var instruction = new WaitConditionInstruction(()=>1==2);

                long? nextTimePeriodCheck;
                bool canComplete = instruction.CanComplete(context, out nextTimePeriodCheck);

                Assert.IsFalse(canComplete);
                Assert.IsNull(nextTimePeriodCheck);
            }
        }
示例#56
0
        /// <summary>
        /// Determines whether this instruction can complete in the current time period
        /// </summary>
        /// <returns>
        /// <c>true</c> if this instance can complete.
        /// </returns>
        /// <param name='context'>
        /// Context providing state information for the current simulation
        /// </param>
        /// <param name='skipFurtherChecksUntilTimePeriod'>
        /// Output parameter used to specify a time period at which this instruction should be checked again.  This should be left null if it is not possible to determine when this instruction can complete.
        /// </param>
        public override bool CanComplete(SimulationContext context, out long? skipFurtherChecksUntilTimePeriod)
        {
            skipFurtherChecksUntilTimePeriod = null;

            bool canComplete = _hasPassed;

            if(!_hasPassed){
                _hasPassed = true;
            }

            return canComplete;
        }
        /// <summary>
        /// Complete the instruction.  For this instruction type, this involves interrupting a process.
        /// </summary>
        /// <param name='context'>
        /// Context providing state information for the current simulation.
        /// </param>
        public override void Complete(SimulationContext context)
        {
            base.Complete(context);

            var process = new ActivityHostProcess(Activity, WaitTime);
            context.Register(process);

            if (context.ActiveProcesses != null){
                // add it to te active process list
                context.ActiveProcesses.Add(process);
                context.ProcessesRemainingThisTimePeriod.Enqueue(process);
            }
        }
示例#58
0
        public void Constructor_SimulationContextExists_ResourceRegistered()
        {
            using(var context = new SimulationContext(isDefaultContextForProcess: true)){
                int capacity = 10;
                var resource = new Resource(capacity);

                Assert.AreEqual(0, resource.Allocated);
                Assert.AreEqual(capacity, resource.Capacity);

                var registeredResources = context.GetByType<Resource>();
                Assert.IsTrue(registeredResources.Contains(resource));
            }
        }
示例#59
0
        public AppleItem(SimulationContext context, Vector2 position, int amount)
            : base(context, position, AppleOuterRadius, Angle.Right)
        {
            #region Apfel abtragen

            //var apple = GetProperty<AppleCollectableProperty>();
            //apple.OnAmountChanged += (good, newValue) =>
            //{
            //    // Apfel entfernen, falls Value is 0
            //    if (newValue <= 0)
            //        Engine.RemoveItem(this);

            //    // Capacity sollte sich auch ändern
            //    good.Capacity = newValue;
            //};

            //#endregion

            //#region Ameisenhügel -> Apfel Interaktion

            //var collidable = GetProperty<CollidableProperty>();
            //collidable.OnCollision += (item, newValue) =>
            //{
            //    if (newValue.ContainsProperty<CollectableProperty>())
            //    {
            //        var target = newValue.GetProperty<CollectableProperty>();

            //        var targetGood = target.GetCollectableGood<AppleCollectableProperty>();

            //        // Prüfen, ob Apfel grundsätzlich aufgenommen werden kann
            //        if (targetGood == null)
            //            return;

            //        if (targetGood.Capacity - targetGood.Amount < apple.Amount)
            //        {
            //            // Apfel passt nicht vollständig in den Bau
            //            var diff = targetGood.Capacity - targetGood.Amount;
            //            apple.Amount -= diff;
            //            targetGood.Amount += diff;
            //        }
            //        else
            //        {
            //            // Apfel vollständig übertragen
            //            targetGood.Amount += apple.Amount;
            //            apple.Amount = 0;
            //        }
            //    }
            //};

            #endregion
        }
示例#60
0
 public SugarItem(SimulationContext context, Vector2 position, int amount)
     : base(context, position, SugarRadius, Angle.Right)
 {
     // Todesbedingung
     //_sugar = GetProperty<SugarCollectableProperty>();
     //_sugar.OnAmountChanged += (good, newValue) =>
     //{
     //    if (newValue <= 0)
     //    {
     //        // Entfernen von der Landkarte
     //        Engine.RemoveItem(this);
     //    }
     //};
 }