Esempio n. 1
0
        /// <summary>
        /// Creates/starts a rollup/simulation
        /// </summary>
        /// <param name="model">SimulationModel</param>
        /// <returns>string Task</returns>
        public Task <string> RunSimulation(SimulationModel model)
        {
            try
            {
                var connectionString = ConfigurationManager.ConnectionStrings["BridgeCareContext"].ConnectionString;
                DBMgr.NativeConnectionParameters = new ConnectionParameters(connectionString, false, "MSSQL");
#if DEBUG
                var mongoConnection = Settings.Default.MongoDBDevConnectionString;
#else
                var mongoConnection = Settings.Default.MongoDBProdConnectionString;
#endif
                var simulation = new Simulation.Simulation(model.SimulationName, model.NetworkName, model.SimulationId, model.NetworkId, mongoConnection);

                Thread simulationThread = new Thread(new ParameterizedThreadStart(simulation.CompileSimulation));

                simulationThread.Start(true);

                return(Task.FromResult("Simulation running..."));
            }
            catch (Exception ex)
            {
                DBMgr.CloseConnection();
                return(Task.FromResult($"Simulation run failed::{ex.Message}"));
            }
        }
Esempio n. 2
0
        private void StartSimulation()
        {
            _sheetController.DeselectAll();

            try
            {
                if (simulation == null)
                {
                    var block      = _sheetController.State.ContentBlock;
                    var serializer = new Simulation.Serializer();
                    var solution   = serializer.Serialize(block);

                    simulation = new Simulation.Simulation(solution, 100);
                    simulation.Start(new WpfUpdate());

                    var window = new Window()
                    {
                        Title  = "Tags",
                        Width  = 300,
                        Height = 500,
                        WindowStartupLocation = WindowStartupLocation.CenterScreen
                    };

                    window.Owner       = this;
                    window.Content     = new TagsControl();
                    window.DataContext = solution.Tags;
                    window.Show();
                }
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
                Debug.Print(ex.StackTrace);
            }
        }
Esempio n. 3
0
 public void EmitOnSimulationRemoval(Simulation.Simulation simulation, EntityRemovalReason?reason)
 {
     foreach (EntityComponent simulationComponent in EntityComponents)
     {
         simulationComponent?.OnSimulationRemove(simulation, this, reason);
     }
 }
Esempio n. 4
0
        public RoutingDataModel CreateFixedDataModel(Simulation.Simulation simulation)   //test and debug
        {
            List <Vehicle> dataModelVehicles      = new List <Vehicle>();
            int            numberVehicles         = 1;
            List <long>    startDepotsArrivalTime = new List <long>(numberVehicles);

            //Creates two available vehicles to be able to perform flexible routing for the pdtwdatamodel
            for (int i = 0; i < numberVehicles; i++)
            {
                var vehicle = new Vehicle(simulation.Params.VehicleSpeed, simulation.Params.VehicleCapacity, simulation.Context.Depot, simulation.Context.Depot);
                dataModelVehicles.Add(vehicle);
                startDepotsArrivalTime.Add(0);//startDepotArrival time  = 0 for all the vehicles
            }

            var customersToBeServed = new List <Customer>();

            customersToBeServed.Add(new Customer(new Stop[] { simulation.Context.Stops[1], simulation.Context.Stops[2] }, new long[] { 600, 1600 }, 0, false));
            customersToBeServed.Add(new Customer(new Stop[] { simulation.Context.Stops[5], simulation.Context.Stops[3] }, new long[] { 1000, 2000 }, 0, false));
            //customersToBeServed.Add(new Customer(new Stop[] { TransportationNetwork.Stops[5], TransportationNetwork.Stops[4] }, new long[] { 800,3500 }, 0));
            //customersToBeServed.Add(new Customer(new Stop[] { TransportationNetwork.Stops[8], TransportationNetwork.Stops[9] }, new long[] {3000, 5000 }, 0));

            var indexManager     = new DataModelIndexManager(dataModelVehicles, customersToBeServed, startDepotsArrivalTime);
            var routingDataModel = new RoutingDataModel(indexManager, simulation.Params.MaximumRelativeCustomerRideTime, simulation.Params.MaximumAllowedDeliveryDelay);

            return(routingDataModel);
        }
Esempio n. 5
0
        public static void Main(string[] args)
        {
            var circuitName = "simple-circuit";
            var circuitPath = Path.GetFullPath($"{assetsDirectoryPath}/tracks/{circuitName}");

            var perceptionPeriod = TimeSpan.FromSeconds(1.0 / 10.0);
            var simulationStep   = TimeSpan.FromSeconds(1.0 / 20.0);

            Console.WriteLine($"Loading track {circuitName}");
            var track = Track.Load($"{circuitPath}/circuit_definition.json");
            var world = new StandardWorld(track, simulationStep, safetyMargin: 0.5);

            var planName = "plan-HybridAStarPlanner-1551383968-15200.json";

            Console.WriteLine($"Loading plan {planName}");
            var plan       = Plans.Load($"{assetsDirectoryPath}/plans/{planName}");
            var trajectory = new Trajectory(plan.Trajectory);

            var agent = new DynamcWindowApproachAgent(
                trajectory,
                world,
                4 * world.VehicleModel.Length,
                perceptionPeriod,
                4 * perceptionPeriod);

            //var agent = new PIDAgent(plan.Trajectory, world.MotionModel, perceptionPeriod);

            Console.WriteLine($"Simulating agent {agent.GetType().Name}");
            var simulation = new Simulation.Simulation(agent, world);
            var summary    = simulation.Simulate(simulationStep, perceptionPeriod, TimeSpan.FromSeconds(60));

            IO.Simulation.StoreResult(track, world.VehicleModel, summary, $"{circuitPath}/visualization.svg", "C:/Users/simon/Projects/racer-experiment/simulator/src/report.json");
            Console.WriteLine($"Time to finish: {summary.SimulationTime.TotalSeconds}s");
        }
Esempio n. 6
0
        private void UpdateVisibleChunks(Simulation.Simulation simulation)
        {
            //Clear visible chunks so we dont have to figure out which chunks are no longer being seen
            VisibleChunks.Clear();
            Chunk rootChunk = simulation.World.ChunkIndex[ChunkKey];

            //find the chunks that the player is currently simulating
            for (int y = rootChunk.ChunkY - simulation.SimulationDistance;
                 y < rootChunk.ChunkY + simulation.SimulationDistance;
                 y++)
            {
                for (int x = rootChunk.ChunkX - simulation.SimulationDistance;
                     x < rootChunk.ChunkX + simulation.SimulationDistance;
                     x++)
                {
                    //Get a chunk if it exist at the location
                    Chunk visibleChunk;
                    if ((visibleChunk = simulation.World.ChunkFromChunkLocation(x, y)) == null)
                    {
                        continue;
                    }

                    //Add chunk to visible chunks
                    VisibleChunks.Add(visibleChunk.ChunkKey);

                    //update chunk history if new with a negative number so a full chunk update will be forced
                    if (!ChunkVersions.ContainsKey(visibleChunk.ChunkKey))
                    {
                        ChunkVersions[visibleChunk.ChunkKey] = -1;
                    }
                }
            }
        }
Esempio n. 7
0
        private static void WorldBoundaryCheck(Simulation.Simulation simulation, SimulationEntity entity)
        {
            //World Boundaries
            if (entity.Position.X < 0)
            {
                if (entity.EmitOnWorldBoundaryCollision(simulation, CollisionSide.LeftBorder))
                {
                    entity.Position.X = entity.OldPosition.X = 0;
                    entity.Velocity.X = 0;
                }
            }

            if (entity.Position.X > simulation.World.MapPixelWidth() - entity.Dimensions.X)
            {
                if (entity.EmitOnWorldBoundaryCollision(simulation, CollisionSide.RightBorder))
                {
                    entity.Position.X = entity.OldPosition.X = simulation.World.MapPixelWidth() - entity.Dimensions.X;
                    entity.Velocity.X = 0;
                }
            }

            if (entity.Position.Y < 0)
            {
                entity.EmitOnWorldBoundaryCollision(simulation, CollisionSide.TopBorder);
            }

            if (entity.Position.Y > simulation.World.MapPixelHeight())
            {
                entity.EmitOnWorldBoundaryCollision(simulation, CollisionSide.BottomBorder);
            }
        }
Esempio n. 8
0
 public static void PlayerDisconnected(this Simulation.Simulation simulation, int photonPlayerId)
 {
     simulation.EnqueueCommand(new PlayerDisconnectedCommand
     {
         PlayerExternalId = photonPlayerId
     });
 }
Esempio n. 9
0
 private static void EntityCollisions(Simulation.Simulation simulation, SimulationEntity entity)
 {
     foreach (SimulationEntity targetEntity in simulation.World.QueryEntities(entity.Bounds, entity.CollideWithFilters, entity.EntityId))
     {
         if (targetEntity.EntityId != entity.EntityId)
         {
             entity.EmitOnEntityCollision(simulation, targetEntity);
         }
     }
 }
Esempio n. 10
0
        public void UseItemRightClick(Simulation.Simulation simulation, SimulationEntity entity)
        {
            if (Configuration.RightClickComponents.Count == 0)
            {
                return;
            }

            foreach (string componentKey in Configuration.RightClickComponents)
            {
                ConfigurationRegistry.GetInstance().GetItemComponent(componentKey).Use(simulation, entity, this);
            }
        }
Esempio n. 11
0
        public bool EmitOnTileCollision(Simulation.Simulation simulation, TileCollision tc)
        {
            bool defaultAction = true;

            foreach (EntityComponent simulationComponent in EntityComponents)
            {
                if (!simulationComponent.OnTileCollision(simulation, this, tc))
                {
                    defaultAction = false;
                }
            }

            return(defaultAction);
        }
Esempio n. 12
0
        public bool EmitOnWorldBoundaryCollision(Simulation.Simulation simulation, CollisionSide side)
        {
            bool defaultAction = true;

            foreach (EntityComponent simulationComponent in EntityComponents)
            {
                if (!simulationComponent.OnWorldBoundaryCollision(simulation, this, side))
                {
                    defaultAction = false;
                }
            }

            return(defaultAction);
        }
Esempio n. 13
0
        public void UseItemLeftClick(Simulation.Simulation simulation, SimulationEntity entity)
        {
            if (Configuration.LeftClickComponents.Count == 0)
            {//Do default actions if no specified item components
                ConfigurationRegistry.GetInstance().GetItemComponent("Hit").Use(simulation, entity, this);
                ConfigurationRegistry.GetInstance().GetItemComponent("BreakBlock").Use(simulation, entity, this);
                return;
            }

            foreach (string componentKey in Configuration.LeftClickComponents)
            {
                ConfigurationRegistry.GetInstance().GetItemComponent(componentKey).Use(simulation, entity, this);
            }
        }
Esempio n. 14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="simulation"></param>
        /// <param name="entity"></param>
        public static void DetectCollision(Simulation.Simulation simulation, SimulationEntity entity)
        {
            WorldBoundaryCheck(simulation, entity);

            EntityCollisions(simulation, entity);

            if (!entity.CollideWithFilters?.Contains("tile") ?? false)
            {
                return;
            }

            //Left and right tile collisions
            BroadPhaseHorizontal(simulation, entity);

            //Detect up and down tile collisions
            BroadPhaseVertical(simulation, entity);
        }
Esempio n. 15
0
        public void UseItemRightHold(Simulation.Simulation simulation, SimulationEntity entity, int holdTicks)
        {
            if (holdTicks % Configuration.CoolDown != 0)
            {
                return;
            }

            if (Configuration.RightHoldComponents.Count == 0)
            {
                return;
            }

            foreach (string componentKey in Configuration.RightHoldComponents)
            {
                ConfigurationRegistry.GetInstance().GetItemComponent(componentKey).Use(simulation, entity, this);
            }
        }
Esempio n. 16
0
        private static void BroadPhaseVertical(Simulation.Simulation simulation, SimulationEntity entity)
        {
            float tileSize = simulation.World.WorldOptions.WorldScale;

            if (entity.Position.Y - entity.OldPosition.Y > 0)
            {//movin down
                TileCollision tc = GetTileCollisionTemplate(entity, CollisionSide.TopBorder, tileSize);

                //in between bounds corners
                for (int i = tc.LeftBlockX; i <= tc.RightBlockX; i++)
                {
                    if ((tc.Tile = simulation.World.GetBlock(i, tc.BottomBlockY)) == 0)
                    {
                        continue;
                    }

                    tc.TilePosition.X = i;

                    if (TopBorderCollision(simulation, entity, tc))
                    {
                        return;
                    }
                }
            }
            else if (entity.Position.Y - entity.OldPosition.Y < 0)
            {//move up
                TileCollision tc = GetTileCollisionTemplate(entity, CollisionSide.BottomBorder, tileSize);

                //in between bounds corners
                for (int i = tc.LeftBlockX; i <= tc.RightBlockX; i++)
                {
                    if ((tc.Tile = simulation.World.GetBlock(i, tc.TopBlockY)) == 0)
                    {
                        continue;
                    }

                    tc.TilePosition.X = i;

                    if (BottomBorderCollision(simulation, entity, tc))
                    {
                        return;
                    }
                }
            }
        }
Esempio n. 17
0
        private void StopSimulation()
        {
            try
            {
                if (simulation != null)
                {
                    simulation.Stop();
                    simulation = null;
                }
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
                Debug.Print(ex.StackTrace);
            }

            _sheetController.DeselectAll();
        }
Esempio n. 18
0
        private static void BroadPhaseHorizontal(Simulation.Simulation simulation, SimulationEntity entity)
        {
            float tileSize = simulation.World.WorldOptions.WorldScale;

            if (entity.Position.X - entity.OldPosition.X < 0) //works now :D
            {                                                 //Left step this time
                TileCollision tc = GetTileCollisionTemplate(entity, CollisionSide.RightBorder, tileSize);

                for (int i = tc.TopBlockY; i <= tc.BottomBlockY; i++)
                {
                    if ((tc.Tile = simulation.World.GetBlock(tc.LeftBlockX, i)) == 0)
                    {
                        continue;
                    }

                    tc.TilePosition.Y = i;

                    if (RightBorderCollision(simulation, entity, tc))
                    {
                        return;
                    }
                }
            }
            else if (entity.Position.X - entity.OldPosition.X > 0) //Works dont touch!!
            {                                                      //Right step this time
                TileCollision tc = GetTileCollisionTemplate(entity, CollisionSide.LeftBorder, tileSize);

                for (int i = tc.TopBlockY; i <= tc.BottomBlockY; i++)
                {
                    if ((tc.Tile = simulation.World.GetBlock(tc.RightBlockX, i)) == 0)
                    {
                        continue;
                    }

                    tc.TilePosition.Y = i;

                    if (LeftBorderCollision(simulation, entity, tc))
                    {
                        return;
                    }
                }
            }
        }
Esempio n. 19
0
        private void MoveEntity(Simulation.Simulation simulation)
        {
            //Place entity in correct chunk if in new position
            string chunkKey =
                simulation.World.ChunkFromPixelLocation((int)Position.X, (int)Position.Y)
                ?.ChunkKey;

            if (chunkKey != ChunkKey && chunkKey != null)
            {
                simulation.World.MoveEntity(EntityId, simulation.World.ChunkIndex[ChunkKey],
                                            simulation.World.ChunkIndex[chunkKey]);
                ChunkKey = chunkKey;
            }

            if (EntityType != EntityType.Player || ChunkKey == null)
            {
                return;
            }

            UpdateVisibleChunks(simulation);
        }
Esempio n. 20
0
        private static bool RightBorderCollision(Simulation.Simulation simulation, SimulationEntity entity, TileCollision tc)
        {
            int tileSize = simulation.World.WorldOptions.WorldScale;

            //if entity is not moving left
            if (!(entity.Position.X - entity.OldPosition.X < 0))
            {
                return(false);
            }

            Rectangle block = tc.TileRectangle(tileSize);

            if (entity.Left >= (block.X + block.Width) || entity.OldLeft < block.X + block.Width)
            {
                return(false);
            }

            int   sectionYPointCount = (int)(entity.Dimensions.Y / tileSize) * 2;
            float sectionYOffset     = tileSize / 2f;

            for (int i = 0; i < sectionYPointCount; i++)
            {
                if (!IsPointColliding(entity.Left, entity.Top + (i * sectionYOffset), block))
                {
                    continue;
                }

                if (!entity.EmitOnTileCollision(simulation, tc))
                {
                    return(true);
                }

                entity.Velocity.X = 0;
                entity.Position.X = entity.OldPosition.X = block.X + tileSize;

                return(true);
            }

            return(false);
        }
Esempio n. 21
0
        private static bool BottomBorderCollision(Simulation.Simulation simulation, SimulationEntity entity, TileCollision tc)
        {
            int tileSize = simulation.World.WorldOptions.WorldScale;

            // if the object is not moving up
            if (!(entity.Position.Y - entity.OldPosition.Y < 0))
            {
                return(false);
            }

            Rectangle block = tc.TileRectangle(tileSize);

            if (entity.Top >= (block.Y + block.Height) || entity.OldTop < (block.Y + block.Height))
            {
                return(false);
            }

            int   sectionXPointCount = (int)(entity.Dimensions.X / tileSize) * 2;
            float sectionXOffset     = tileSize / 2f;

            for (int i = 0; i <= sectionXPointCount; i++)
            {
                if (!IsPointColliding(entity.Left + (i * sectionXOffset), entity.Top, block))
                {
                    continue;
                }

                if (!entity.EmitOnTileCollision(simulation, tc))
                {
                    return(true);
                }

                entity.Velocity.Y = -0.001f;
                entity.Position.Y = entity.OldPosition.Y = block.Y + block.Height;

                return(true);
            }

            return(false);
        }
        public FitnessInfo Evaluate(IBlackBox phenome)
        {
            var fitness = 0.0;

            foreach (var world in worlds)
            {
                var lidar      = createLidarFor(world.Track);
                var agent      = new NeuralNetworkAgent(lidar, phenome);
                var simulation = new Simulation.Simulation(agent, world);

                var simulationResult = simulation.Simulate(simulationStep, perceptionStep, maximumSimulationTime);
                fitness += fitnessOf(simulationResult);
            }

            lock (evaluationLock)
            {
                EvaluationCount++;
            }

            return(new FitnessInfo(
                       fitness: fitness / worlds.Length,
                       new AuxFitnessInfo[0]));
        }
Esempio n. 23
0
        /// <summary>
        /// Updates this entity as part of the chunks in the simulation of this entity
        /// </summary>
        /// <param name="simulation"></param>
        public void Tick(Simulation.Simulation simulation)
        {
            TicksSinceCreation++;

            //Only tick entity once per frame
            if (simulation.Tick == _currentTick)
            {
                return;
            }

            //Record last tick
            _currentTick = simulation.Tick;

            //Record current position
            OldPosition = new BfbVector(Position.X, Position.Y);

            //the future
            foreach (EntityComponent gameComponent in EntityComponents)
            {
                gameComponent?.Update(this, simulation);
            }

            MoveEntity(simulation);
        }
Esempio n. 24
0
 public WorkController(Simulation.Simulation simulation)
 {
     _simulation = simulation;
 }
Esempio n. 25
0
 public SimulationController(Simulation.Simulation simulation, WorkflowProvider workflowProvider)
 {
     _simulation = simulation;
     _workflowProvider = workflowProvider;
 }
Esempio n. 26
0
        public static void FightPeople(SimulationEntity entity, List <SimulationEntity> targets, Simulation.Simulation simulation)
        {
            if (targets.Count <= 0)
            {
                return;
            }

            ushort damage    = entity.Inventory?.GetActiveSlot()?.Configuration?.Damage ?? 0;
            ushort knockback = entity.Inventory?.GetActiveSlot()?.Configuration?.KnockBack ?? 20;


            foreach (SimulationEntity target in targets)
            {
                if (target.Meta == null || (entity.EntityConfiguration.EntityKey == target.EntityConfiguration.EntityKey))
                {
                    continue;
                }

                target.Meta.Health -= damage;

                if (entity.Facing == DirectionFacing.Left)
                {
                    target.Velocity.Y = -knockback / 2f;
                    target.Velocity.X = -knockback;
                }
                else
                {
                    target.Velocity.Y = -knockback / 2f;
                    target.Velocity.X = knockback;
                }
            }
        }
Esempio n. 27
0
        public RoutingDataModel CreateCurrentSimulationDataModel(Simulation.Simulation simulation, Customer newCustomer, int currentTime)
        {
            var             flexibleRoutingVehicles = simulation.Context.VehicleFleet.FindAll(v => v.FlexibleRouting);
            List <Vehicle>  dataModelVehicles       = new List <Vehicle>();
            List <Customer> allExpectedCustomers    = new List <Customer>();

            foreach (var vehicle in flexibleRoutingVehicles)
            {
                dataModelVehicles.Add(vehicle);
                if (vehicle.TripIterator?.Current != null)
                {
                    List <Customer> expectedCustomers = new List <Customer>(vehicle.TripIterator.Current.ExpectedCustomers);
                    foreach (var customer in expectedCustomers)
                    {
                        if (!allExpectedCustomers.Contains(customer) && !customer.AlreadyServed)
                        {
                            allExpectedCustomers.Add(customer);
                        }
                    }
                    List <Customer> currentCustomers = vehicle.Customers;
                    foreach (var currentCustomer in currentCustomers)
                    {
                        if (!allExpectedCustomers.Contains(currentCustomer) && !currentCustomer.AlreadyServed)
                        {
                            allExpectedCustomers.Add(currentCustomer);
                        }
                    }

                    //debug
                    foreach (var customer in allExpectedCustomers)
                    {
                        if (customer.IsInVehicle)
                        {
                            var v = simulation.Context.VehicleFleet.Find(veh => veh.Customers.Contains(customer));
                            //Console.WriteLine(" Customer " + customer.Id + " is already inside vehicle" + v.Id + ": Already visited: " + customer.PickupDelivery[0] +", Need to visit:" + customer.PickupDelivery[1]);
                        }
                    }
                    //end of debug
                }
            }
            if (!allExpectedCustomers.Contains(newCustomer))
            {
                allExpectedCustomers.Add(newCustomer);
            }
            //--------------------------------------------------------------------------------------------------------------------------
            //Calculation of startDepotArrivalTime, if there is any moving vehicle, otherwise startDepotArrivalTime will be the current event Time
            var         movingVehicles             = simulation.Context.VehicleFleet.FindAll(v => !v.IsIdle && v.FlexibleRouting);
            List <long> startDepotArrivalTimesList = new List <long>(dataModelVehicles.Count);

            for (int i = 0; i < dataModelVehicles.Count; i++)
            {
                startDepotArrivalTimesList.Add(currentTime); //initializes startDepotArrivalTimes with the current event time
            }
            if (movingVehicles.Count > 0)                    //if there is a moving vehicle calculates the baseArrivalTime
            {
                foreach (var movingVehicle in movingVehicles)
                {
                    var vehicleArrivalEvents = simulation.Events.FindAll(e =>
                                                                         e is VehicleStopEvent vse && e.Category == 0 && e.Time >= currentTime && vse.Vehicle == movingVehicle);
                    foreach (var arrivalEvent in vehicleArrivalEvents)
                    {
                        if (arrivalEvent is VehicleStopEvent vehicleStopEvent)
                        {
                            if (movingVehicle.CurrentStop != null && movingVehicle.CurrentStop == vehicleStopEvent.Stop)
                            {
                                var currentStartDepotArrivalTime = startDepotArrivalTimesList[dataModelVehicles.IndexOf(movingVehicle)];
                                startDepotArrivalTimesList[dataModelVehicles.IndexOf(movingVehicle)] = Math.Max(vehicleStopEvent.Time, (int)currentStartDepotArrivalTime); //finds the biggest value between the current baseArrivalTime and the current vehicle's next stop arrival time, and updates its value on the array
                            }
                        }
                    }
                }
            }
            //end of calculation of startDepotsArrivalTime
            //--------------------------------------------------------------------------------------------------------------------------
            var indexManager = new DataModelIndexManager(dataModelVehicles, allExpectedCustomers, startDepotArrivalTimesList);
            var dataModel    = new RoutingDataModel(indexManager, simulation.Params.MaximumRelativeCustomerRideTime, simulation.Params.MaximumAllowedDeliveryDelay);

            return(dataModel);
        }
Esempio n. 28
0
        public RoutingDataModel CreateInitialSimulationDataModel(bool allowDropNodes, Simulation.Simulation simulation)
        {
            var numberCustomers = simulation.Params.NumberInitialRequests;
            var numberVehicles  = simulation.Params.VehicleNumber;

            Console.WriteLine(this.ToString() + "Creating new random DataModel for " + numberVehicles + " Vehicles and " + numberCustomers + " Customers, AllowDropNodes: " + allowDropNodes);
GenerateNewDataModelLabel:
            List <Vehicle> dataModelVehicles   = new List <Vehicle>();
            List <long> startDepotsArrivalTime = new List <long>(numberVehicles);

            //Creates two available vehicles to be able to perform flexible routing for the pdtwdatamodel
            for (int i = 0; i < numberVehicles; i++)
            {
                var vehicle = new Vehicle(simulation.Params.VehicleSpeed, simulation.Params.VehicleCapacity, simulation.Context.Depot, simulation.Context.Depot);
                dataModelVehicles.Add(vehicle);
                startDepotsArrivalTime.Add(0);//startDepotArrival time  = 0 for all the vehicles
            }

            var         customersToBeServed = new List <Customer>();
            List <Stop> excludedStops       = new List <Stop>();

            foreach (var vehicle in dataModelVehicles)
            {
                if (!excludedStops.Contains(vehicle.StartStop))
                {
                    excludedStops.Add(vehicle.StartStop);
                }

                if (!excludedStops.Contains(vehicle.EndStop))
                {
                    excludedStops.Add(vehicle.EndStop);
                }
            }

            for (int i = 0; i < numberCustomers; i++) //generate 5 customers with random timeWindows and random pickup and delivery stops
            {
                var requestTime      = 0;
                var pickupTimeWindow = new int[] { requestTime, simulation.Params.SimulationTimeWindow[1] };                                                                                           //the customer pickup time will be between the current request time and the end of simulation time
                var customer         = CustomerFactory.Instance().CreateRandomCustomer(simulation.Context.Stops, excludedStops, requestTime, pickupTimeWindow, false, simulation.Params.VehicleSpeed); //Generates a random static customer
                customersToBeServed.Add(customer);
            }
            var indexManager = new DataModelIndexManager(dataModelVehicles, customersToBeServed, startDepotsArrivalTime);

            var routingDataModel = new RoutingDataModel(indexManager, simulation.Params.MaximumRelativeCustomerRideTime, simulation.Params.MaximumAllowedDeliveryDelay);
            var solver           = new RoutingSolver(routingDataModel, allowDropNodes);
            RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters();

            searchParameters.LocalSearchMetaheuristic = LocalSearchMetaheuristic.Types.Value.Automatic;
            searchParameters.SolutionLimit            = 1; //until it finds 1 solution
            var solution = solver.TryGetSolution(searchParameters);

            if (solution == null)
            {
                goto GenerateNewDataModelLabel;
            }
            return(routingDataModel);
        }
Esempio n. 29
0
        public static void Main(string[] args)
        {
            var random   = new Random();
            var circuits = circuitsFilePaths().ToArray();

            var perceptionStep        = TimeSpan.FromSeconds(0.1);
            var simulationStep        = TimeSpan.FromSeconds(0.05); // 20Hz
            var maximumSimulationTime = TimeSpan.FromSeconds(60);

            var tracks = circuits.Select(circuitPath => Track.Load($"{circuitPath}/circuit_definition.json"));
            var worlds = tracks.Select(track => new StandardWorld(track, simulationStep)).ToArray();

            var inputSamplesCount       = 3;
            var maximumScanningDistance = 200;

            ILidar createLidarFor(ITrack track)
            => new Lidar(track, inputSamplesCount, Angle.FromDegrees(135), maximumScanningDistance);

            var settings = new EvolutionSettings
            {
                PopulationSize      = 1000,
                SpeciesCount        = 30,
                ElitismProportion   = 0,
                ComplexityThreshold = 50
            };

            // prepare simulation
            var parameters = new NeatEvolutionAlgorithmParameters
            {
                ElitismProportion = settings.ElitismProportion,
                SpecieCount       = settings.SpeciesCount
            };

            var distanceMetric  = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            var parallelOptions = new ParallelOptions {
                MaxDegreeOfParallelism = 4
            };
            var speciationStrategy           = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, parallelOptions);
            var complexityRegulationStrategy = new DefaultComplexityRegulationStrategy(ComplexityCeilingType.Absolute, settings.ComplexityThreshold);

            var evolutionaryAlgorithm = new NeatEvolutionAlgorithm <NeatGenome>(
                parameters,
                speciationStrategy,
                complexityRegulationStrategy);

            var phenomeEvaluator = new RaceSimulationEvaluator(
                random,
                simulationStep,
                perceptionStep,
                maximumSimulationTime,
                worlds,
                createLidarFor);

            var genomeDecoder       = new NeatGenomeDecoder(NetworkActivationScheme.CreateAcyclicScheme());
            var genomeListEvaluator = new ParallelGenomeListEvaluator <NeatGenome, IBlackBox>(
                genomeDecoder,
                phenomeEvaluator);

            evolutionaryAlgorithm.Initialize(
                genomeListEvaluator,
                genomeFactory: new NeatGenomeFactory(
                    inputNeuronCount: inputSamplesCount,
                    outputNeuronCount: 2,
                    DefaultActivationFunctionLibrary.CreateLibraryNeat(new BipolarSigmoid()),
                    new NeatGenomeParameters
            {
                FeedforwardOnly                     = true,
                AddNodeMutationProbability          = 0.03,
                DeleteConnectionMutationProbability = 0.05,
                ConnectionWeightMutationProbability = 0.08,
                FitnessHistoryLength                = 10,
            }),
                settings.PopulationSize);

            var lastVisualization = DateTimeOffset.Now;

            evolutionaryAlgorithm.UpdateEvent += onUpdate;
            evolutionaryAlgorithm.StartContinue();

            Console.WriteLine("Press enter to stop the evolution.");
            Console.ReadLine();
            Console.WriteLine("Finishing the evolution.");

            evolutionaryAlgorithm.Stop();
            Console.WriteLine("Evolution is stopped.");

            // simulate best individual
            Console.WriteLine("Simulating best individual...");
            evaluate(evolutionaryAlgorithm.CurrentChampGenome);
            Console.WriteLine("Done.");

            void onUpdate(object sender, EventArgs e)
            {
                Console.WriteLine($"Generation #{evolutionaryAlgorithm.CurrentGeneration}");
                Console.WriteLine($"- max fitness:  {evolutionaryAlgorithm.Statistics._maxFitness}");
                Console.WriteLine($"- mean fitness: {evolutionaryAlgorithm.Statistics._meanFitness}");
                Console.WriteLine();

                if (DateTimeOffset.Now - lastVisualization > TimeSpan.FromSeconds(35))
                {
                    lastVisualization = DateTimeOffset.Now;
                    Console.WriteLine("Simulating currently best individual...");
                    evaluate(evolutionaryAlgorithm.CurrentChampGenome);
                }
            }

            void evaluate(NeatGenome genome)
            {
                var worldId = random.Next(0, worlds.Length - 1);
                var world   = worlds[worldId];

                var bestIndividual = genomeDecoder.Decode(genome);
                var agent          = new NeuralNetworkAgent(createLidarFor(world.Track), bestIndividual);
                var simulation     = new Simulation.Simulation(agent, world);
                var summary        = simulation.Simulate(simulationStep, perceptionStep, maximumSimulationTime);

                File.Copy($"{circuits[worldId]}/visualization.svg", "C:/Users/simon/Projects/racer-experiment/simulator/src/visualization.svg", overwrite: true);
                IO.Simulation.StoreResult(world.Track, world.VehicleModel, summary, "", "C:/Users/simon/Projects/racer-experiment/simulator/src/report.json");
            }
        }