private void CheckUnavailable(RoutingData actual)
        {
            Assert.AreEqual(actual.Visits.Length, actual.Unavailable.Length);

            // visit 1
            {
                Assert.AreEqual(4, actual.Unavailable[0].Length);
                var(from, to) = actual.Unavailable[0].Last();
                Assert.AreEqual(TestDataset1.StartDay1 - TestDataset1.Duration1, from);
                Assert.AreEqual(TestDataset1.EndDay1, to);
            }

            // visit2
            {
                Assert.AreEqual(4, actual.Unavailable[1].Length);
                var(from, to) = actual.Unavailable[1].Last();
                Assert.AreEqual(TestDataset1.StartDay2 - TestDataset1.Duration2, from);
                Assert.AreEqual(TestDataset1.EndDay2, to);
            }

            // normal visits have default unavailables
            for (int i = 0; i < actual.Unavailable.Length; i++)
            {
                if (actual.HomeIndex.Contains(i) || actual.Visits[i].IsBreak)
                {
                    // home / breaks
                    continue;
                }

                CheckUnavailableDefault(actual.Unavailable[i], actual.Visits[i].Duration);
            }
        }
Example #2
0
        public void TestCompression()
        {
            var tree = CreateDefault();

            var routingData = new RoutingData(null);
            var service     = new Service(null, null, routingData);

            service.Initialise("Service1Test", "node1", new string[0], "Address1Test", 10000).Wait();
            var service2 = new Service(null, null, routingData);

            service2.Initialise("Service1Test", "node1", new string[0], "Address2Test", 10000).Wait();

            tree.AddServiceToRoute("/test1/test2/test3/test4/test5", service);
            tree.AddServiceToRoute("/test1/test2/test3/test4/test5/test6", service2);

            Assert.Equal(1, tree.GetTopNode().ChildrenNodes.Count);

            tree.Compress();

            //We should have 1 node in the tree
            Assert.Equal(1, tree.GetTopNode().ChildrenNodes.Count);

            //The key length should be 5 long
            Assert.Equal(5, tree.GetTopNode().ChildrenNodes.KeyLength);

            var returnservice = tree.GetServiceFromRoute("/test1/test2/test3/test4/test5/test7", out var matchedpath);

            Assert.Equal("/test1/test2/test3/test4/test5".ToUpperInvariant(), matchedpath);
            //Assert.Equal(returnservice.ServiceId, service.ServiceId);
        }
Example #3
0
 public ServiceWithCustomClient(ILoggerFactory loggingFactory, PipeFactory factory, RoutingData routingData)
 {
     _routingData       = routingData;
     _logger            = loggingFactory?.CreateLogger <ServiceWithCustomClient>();
     _pooledConnections = new ConcurrentQueue <IPipeConnection>();
     _factory           = factory;
 }
        /// <summary>
        /// requires data.SantaIds
        /// creates data.Visits
        /// creates data.HomeIndex
        /// </summary>
        private static void CreateVisits(RoutingData data)
        {
            if (data.SantaIds == null)
            {
                throw new ArgumentNullException();
            }

            var visits = new List<Visit>();
            foreach (var visit in data.Input.Visits)
            {
                if (data.SantaIds.Contains(visit.SantaId) && visit.IsBreak)
                {
                    // break
                    var santaIndex = -1;
                    foreach (var (from, to) in data.Input.Days)
                    {
                        // create a break for each day
                        var breakVisit = (Visit)visit.Clone();

                        // remove desired on other days
                        breakVisit.Desired = breakVisit.Desired?.Where(d => Core.Utility.IntersectionLength(d.from, d.to, from, to) > 0).ToArray() ?? new (int, int)[0];

                        // not needed because of the new santaId
                        // which assigns this break to a specific day
                        breakVisit.Unavailable = new (int, int)[0];
Example #5
0
        public async Task CanWeFindARouteAndGetAPageHttps()
        {
            var informationService = new InformationService
            {
                Address = "www.google.com",
                Port    = 80
            };

            var router     = BuildRouter();
            var routerData = new RoutingData(null);
            var service    = new Service(null, null, routerData);
            await service.Initialise("service1", "node1", new[] { UrlPrefix + "/search", "protocolScheme-https" }, "www.google.com", 443);

            router.AddNewService(service);

            var context = new DefaultHttpContext();

            context.Request.Method = "GET";
            context.Request.Path   = "/search";

            var routedService = router.GetServiceFromRoute(context.Request.Path, out string matchedPath);
            await routedService.CallService(context);

            Assert.Equal(200, context.Response.StatusCode);
        }
Example #6
0
        public void TestSplitting()
        {
            var tree = CreateDefault();

            var routingData = new RoutingData(null);
            var service     = new Service(null, null, routingData);

            service.Initialise("Service1Test", "node1", new string[0], "Adress1Test", 10000).Wait();
            var service2 = new Service(null, null, routingData);

            service2.Initialise("Service1Test", "node1", new string[0], "Address2Test", 10000).Wait();
            tree.AddServiceToRoute("/test1/test2/test3/test4/test5", service);
            tree.AddServiceToRoute("/test1/test2/test3/test4/test5/test6", service);

            tree.Compress();

            ////Time to split the tree it should be 5 long at the moment but this should make it 2 long and then split
            tree.AddServiceToRoute("/test1/test2/test10/test6/test4/test6", service);

            var topNode = tree.GetTopNode();

            //Check the first node is two long
            Assert.Equal(2, topNode.ChildrenNodes.KeyLength);

            //find the root common node
            var commonNode = topNode.ChildrenNodes[new string[] { "TEST1", "TEST2" }];

            //check the keys are consistant
            foreach (var kv in commonNode.ChildrenNodes)
            {
                Assert.Equal(kv.Item1.Length, commonNode.ChildrenNodes.KeyLength);
            }
        }
Example #7
0
        public void TestRemovingAService()
        {
            var tree = CreateDefault();

            var routingData = new RoutingData(null);
            var service     = new Service(null, null, routingData);

            service.Initialise("Service1Test", "node1", new string[0], "Address1Test", 10000).Wait();
            var service2 = new Service(null, null, routingData);

            service2.Initialise("Service1Test", "node1", new string[0], "Address2Test", 10000).Wait();

            tree.AddServiceToRoute("/test1/test2/test3/test4/test5", service);
            tree.AddServiceToRoute("/test1/test2/test3/test4/test5/test6", service2);

            var returnservice = tree.GetServiceFromRoute("/test1/test2/test3/test4/test5/test7", out var matchedpath);

            Assert.Equal("/test1/test2/test3/test4/test5".ToUpperInvariant(), matchedpath);

            ////now remove the service
            tree.RemoveService(service);

            //Now we should get no match
            returnservice = tree.GetServiceFromRoute("/test1/test2/test3/test4/test5/test7", out matchedpath);
            Assert.Null(returnservice);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        /// <param name="costCoefficient">way will be multiplied with this</param>
        /// <param name="startCost">Additional cost from home to any visit</param>
        public CostEvaluator(RoutingData data, int costCoefficient, int startCost)
        {
            timeEvaluator = new TimeEvaluator(data);

            this.data            = data;
            this.costCoefficient = costCoefficient;
            this.startCost       = startCost;
        }
Example #9
0
 public RoutingData(string userCommand, string path, string[] pathParts, string content, RoutingData previous)
 {
     Path        = path;
     PathParts   = pathParts;
     UserCommand = userCommand;
     Content     = content;
     Previous    = previous;
 }
Example #10
0
 public ChangeRoutingStrategy(RoutingData routingData,
                              IServiceProvider provider,
                              IDefaultRouting <IService> defaultRouting)
 {
     _routingData    = routingData;
     _provider       = provider;
     _defaultRouting = defaultRouting;
 }
Example #11
0
 public RoutingData(string userCommand, string path, string[] pathParts, string content)
 {
     Path        = path;
     PathParts   = pathParts;
     Content     = content;
     UserCommand = userCommand;
     Previous    = null;
 }
Example #12
0
        public SessionFeature SetRoutingData(RoutingData routingData)
        {
            var newContext = MessageContext.Builder()
                             .SetRoutingData(routingData)
                             .Build()
                             .Join(Context);

            return(new SessionFeature(newContext));
        }
Example #13
0
        public void AddConstraints(RoutingData data, RoutingModel model, IntVar cumulTime, RoutingDimension timeDim, int visit)
        {
            // forbid visit in unavailable
            var unavailableStarts = data.Unavailable[visit].Select(u => u.startFrom).ToList();
            var unavailableEnds   = data.Unavailable[visit].Select(u => u.startEnd).ToList();
            var constraint        = model.solver().MakeNotMemberCt(cumulTime, new CpIntVector(unavailableStarts), new CpIntVector(unavailableEnds));

            model.solver().Add(constraint);
        }
 public NetworkMessageContainer(
     MessagePackSerializableObject data,
     MessageTypes messageType,
     RoutingData routingData = null
     )
 {
     MessageData = data;
     MessageType = messageType;
     RoutingData = routingData;
 }
 private void CheckSantas(RoutingData actual)
 {
     Assert.AreEqual(TestDataset1.NumberOfDays * NumberOfSantas, actual.SantaIds.Length);
     Assert.AreEqual(TestDataset1.SantaId1, actual.SantaIds[0]);
     Assert.AreEqual(TestDataset1.SantaId2, actual.SantaIds[1]);
     Assert.AreEqual(TestDataset1.SantaId2 + 1, actual.SantaIds[2]);
     Assert.AreEqual(TestDataset1.SantaId1, actual.SantaIds[3]);
     Assert.AreEqual(TestDataset1.SantaId2, actual.SantaIds[4]);
     Assert.AreEqual(TestDataset1.SantaId2 + 1, actual.SantaIds[5]);
 }
        /// <summary>
        /// Returns the one desired that should get a soft time window.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="visit"></param>
        /// <returns></returns>
        public static (int from, int to)? GetDesired(RoutingData data, int visit)
        {
            var candidates = data.BestDesired[visit];

            if (candidates.Length == 0)
            {
                return(null);
            }
            return(candidates[candidates.Length / 2]);
        }
Example #17
0
 public override NSDU Decode(BACPacket cm)
 {
     nlm   = (Network_Layer_Message)cm.getNextByte();
     Ports = cm.getNextByte();
     rd    = new RoutingData[Ports];
     for (int x = 0; x < Ports; x++)
     {
         rd[x] = new RoutingData().Decoder(cm);
     }
     return(this);
 }
        /// <summary>
        /// Builds the OptimizationResult.
        /// Note: OptimizationResult.TimeElapsed will not be set.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="model"></param>
        /// <param name="solution"></param>
        /// <returns></returns>
        private static OptimizationResult CreateResult(RoutingData data, RoutingModel model, Assignment solution)
        {
            var ret = new OptimizationResult
            {
                OptimizationInput = data.Input,
                ResultState       = GetResultState(model),
                Routes            = GetRoutes(data, model, solution),
            };

            return(ret);
        }
        public static RoutingData Convert(OptimizationInput input, int maxNumberOfAdditionalSantas)
        {
            var data = new RoutingData(input);

            CreateSantas(data, maxNumberOfAdditionalSantas);
            CreateVisits(data);
            CreateUnavailable(data);
            CreateDesired(data);
            CreateStartEnd(data);

            return data;
        }
Example #20
0
        private CustomRouter BuildRouter()
        {
            Func <ChildContainer <IService> > createNode = () =>
            {
                var randomRoutingStrategy = new RandomRoutingStrategy <IService>();
                return(new ChildContainer <IService>(new DefaultRouting <IService>(new[] { randomRoutingStrategy },
                                                                                   null)));
            };
            var data = new RoutingData(new RadixTree <IService>(createNode));

            return(new CustomRouter(null, data));
        }
        /// <summary>
        /// Returns the cost coefficient if the soft time window is not met.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="visit"></param>
        /// <returns></returns>
        public static int GetDesiredCoefficient(RoutingData data, int visit)
        {
            var desired = GetDesired(data, visit);

            if (desired.HasValue)
            {
                const int hour       = 3600;
                var       duration   = data.Visits[visit].Duration;
                var       maxDesired = Math.Min(duration, Utility.GetRealDesiredLength(data, desired.Value));
                return(data.Cost.CostVisitInDesiredPerHour * maxDesired / hour);
            }
            return(0);
        }
        /// <summary>
        /// Returns the Routes from the solution.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="model"></param>
        /// <param name="solution"></param>
        /// <returns></returns>
        private static Route[] GetRoutes(RoutingData data, RoutingModel model, Assignment solution)
        {
            if (solution == null)
            {
                return(new Route[0]);
            }

            // Routes
            var routes = new List <Route>();

            for (int santa = 0; santa < data.NumberOfSantas; ++santa)
            {
                long visit = model.Start(santa);
                if (model.IsEnd(solution.Value(model.NextVar(visit))))
                {
                    // empty
                }
                else
                {
                    var waypoints = new List <Waypoint>();
                    void AddWaypoint(long v)
                    {
                        var startTime = solution.Value(model.CumulVar(v, DimensionTime));
                        var visitId   = (v >= data.Visits.Length || v < 0) ? Constants.VisitIdHome : data.Visits[v].Id;

                        waypoints.Add(new Waypoint
                        {
                            StartTime = (int)startTime,
                            VisitId   = visitId,
                        });
                    }

                    for (; !model.IsEnd(visit); visit = solution.Value(model.NextVar(visit)))
                    {
                        AddWaypoint(visit);
                    }

                    // add end
                    {
                        AddWaypoint(visit);
                    }
                    routes.Add(new Route
                    {
                        SantaId   = data.SantaIds[santa],
                        Waypoints = waypoints.ToArray(),
                    });
                }
            }

            return(routes.ToArray());
        }
Example #23
0
        public RouteMatch Match(RoutingData routingData)
        {
            if (routingData.PathParts.Length > Parts.Length)
            {
                return(RouteMatch.Unsuccess);
            }

            var matched = Parts.Zip(routingData.PathParts, (patternPart, pathPart) => new { patternPart, pathPart })
                          .Where(t => t.pathPart != null && t.patternPart.IsMatch(t.pathPart))
                          .ToArray();

            if (matched.Length != routingData.PathParts.Length)
            {
                return(RouteMatch.Unsuccess);
            }

            var fields = new Dictionary <string, string>();

            if (Defaults != null)
            {
                fields.Merge(Defaults);
            }
            matched
            .Select(t => new KeyValuePair <string, string>((t.patternPart as NamedRoutePatternPart)?.Name, t.pathPart))
            .Where(kvp => kvp.Key != null)
            .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
            .MergeTo(fields);

            var completed = routingData.PathParts.Length == Parts.Length;

            if (completed)
            {
                return(RouteMatch.CreateCompleted(this, fields));
            }

            var nextPart      = Parts[routingData.PathParts.Length];
            var nextExactPath = nextPart as ExactRoutePatternPart;

            if (nextExactPath == null)
            {
                throw new InvalidOperationException("Cannot create completion link for route part " + nextPart.GetType());
            }

            var completionPath = "/" + Parts.Take(routingData.PathParts.Length + 1)
                                 .Cast <ExactRoutePatternPart>()
                                 .Select(p => p.ExactValue)
                                 .JoinToString(":");
            var completionData = new RouteCompletionData(Details, completionPath);

            return(RouteMatch.CreateUncompleted(this, fields, completionData));
        }
Example #24
0
        public void AddConstraints(RoutingData data, RoutingModel model, IntVar cumulTime, RoutingDimension timeDim, int visit)
        {
            var desired = InternalSolver.GetDesired(data, visit);

            if (desired.HasValue)
            {
                // add soft time window for desired
                cumulTime.SetRange(desired.Value.from, desired.Value.to);
            }
            else
            {
                // forbid visit in unavailable
                new UnavailableOnlyStrategy().AddConstraints(data, model, cumulTime, timeDim, visit);
            }
        }
Example #25
0
        public void AddConstraints(RoutingData data, RoutingModel model, IntVar cumulTime, RoutingDimension timeDim, int visit)
        {
            // forbid visit in unavailable
            new UnavailableOnlyStrategy().AddConstraints(data, model, cumulTime, timeDim, visit);

            // add soft time window for desired
            var desired = InternalSolver.GetDesired(data, visit);

            if (desired.HasValue)
            {
                var cost = InternalSolver.GetDesiredCoefficient(data, visit);
                timeDim.SetCumulVarSoftUpperBound(visit, desired.Value.to, cost);
                timeDim.SetCumulVarSoftLowerBound(visit, desired.Value.from, cost);
            }
        }
        public async void SetupCustomRouterAndRouteToService()
        {
            var router     = BuildRouter();
            var routerData = new RoutingData(null);
            var service    = new Service(null, null, routerData);
            await service.Initialise("Service1Test", "node1", new string[] { UrlPrefix + "/test1/test2/test3/test4/test5" }, "Address1Test", 10000);

            router.AddNewService(service);

            var context = new DefaultHttpContext();

            context.Request.Method = "GET";
            context.Request.Path   = "/test1/test2/test3/test4/test5/test6";

            var routedService = router.GetServiceFromRoute(context.Request.Path, out var matchedPath);

            Assert.Equal(service, routedService);
        }
        public async void SetupCustomRouterAndLookForbadRoute()
        {
            var router = BuildRouter();

            var routerData = new RoutingData(null);
            var service    = new Service(null, null, routerData);
            await service.Initialise("Service1Test", "node1", new string[] { UrlPrefix + "/test1/test2/test3/test4/test5" }, "Address1Test", 10000);

            router.AddNewService(service);

            var context = new DefaultHttpContext();

            context.Request.Method = "GET";
            context.Request.Path   = "/test2/test2/test3/test4/test5/test6";
            var routeContext = new RouteContext(context);

            //await router.RouteAsync(routeContext);

            Assert.Null(routeContext.Handler);
        }
        private void CheckVisits(RoutingData actual)
        {
            // 4 normal
            // 2 breaks
            // 2 homes
            Assert.AreEqual(8, actual.Visits.Length);
            for (int i = 0; i < actual.Input.Visits.Length; i++)
            {
                Assert.AreEqual(actual.Input.Visits[i].Id, actual.Visits[i].Id);
            }

            // test break on day1
            Assert.AreEqual(1, actual.Visits[4].SantaId);
            Assert.AreEqual(1, actual.Visits[4].Desired.Length);
            Assert.AreEqual(TestDataset1.StartDay1 + TestDataset1.BreakDesiredStart, actual.Visits[4].Desired[0].from);
            Assert.AreEqual(TestDataset1.StartDay1 + TestDataset1.BreakDesiredEnd, actual.Visits[4].Desired[0].to);

            // test break on day2
            Assert.AreEqual(4, actual.Visits[5].SantaId);
            Assert.AreEqual(1, actual.Visits[5].Desired.Length);
            Assert.AreEqual(TestDataset1.StartDay2 + TestDataset1.BreakDesiredStart, actual.Visits[5].Desired[0].from);
            Assert.AreEqual(TestDataset1.StartDay2 + TestDataset1.BreakDesiredEnd, actual.Visits[5].Desired[0].to);

            // homes
            var home0 = 6;
            var home1 = 7;

            Assert.AreEqual(-1, actual.Visits[home0].Id);
            Assert.AreEqual(-1, actual.Visits[home1].Id);
            Assert.AreEqual(home0, actual.HomeIndex[0]);
            Assert.AreEqual(home1, actual.HomeIndex[1]);

            // desired/unavailable must not be null
            foreach (var visit in actual.Visits)
            {
                Assert.IsNotNull(visit.Desired);
                Assert.IsNotNull(visit.Unavailable);
            }
        }
        /// <summary>
        /// creates data.SantaIds
        /// </summary>
        /// <param name="data">routing input data</param>
        /// <param name="maxNumberOfAdditionalSantas"></param>
        private static void CreateSantas(RoutingData data, int maxNumberOfAdditionalSantas)
        {
            var santaIds = new List<int>();
            for (int i = 0; i < data.Input.Santas.Length; i++)
            {
                // real santa
                santaIds.Add(data.Input.Santas[i].Id);
            }
            for (int i = 0; i < maxNumberOfAdditionalSantas; i++)
            {
                // new, artificial santa
                santaIds.Add(santaIds.Max() + 1);
            }

            // duplicate for each day
            var santaIdsPerDay = new List<int>();
            foreach (var _ in data.Input.Days)
            {
                santaIdsPerDay.AddRange(santaIds);
            }

            data.SantaIds = santaIdsPerDay.ToArray();
        }
        public void TestGetRealDesiredLength()
        {
            var data = new RoutingData(TestDataset1.Create());

            var durationDay1 = TestDataset1.EndDay1 - TestDataset1.StartDay1;
            var durationDay2 = TestDataset1.EndDay2 - TestDataset1.StartDay2;
            var tests        = new List <(int expected, (int from, int to) desired)>
            {
                (0, (TestDataset1.StartDay1, TestDataset1.StartDay1)),
                (durationDay1, (TestDataset1.StartDay1, TestDataset1.EndDay1)),
                (durationDay1, (TestDataset1.StartDay1, TestDataset1.EndDay1 + 100)),
                (durationDay1 - 100, (TestDataset1.StartDay1, TestDataset1.EndDay1 - 100)),
                (durationDay1, (TestDataset1.StartDay1 - 100, TestDataset1.EndDay1)),
                (durationDay1 - 100, (TestDataset1.StartDay1 + 100, TestDataset1.EndDay1)),
                (Math.Max(durationDay1, durationDay2), (TestDataset1.StartDay1, TestDataset1.EndDay2)),
                (100, (TestDataset1.StartDay2 + 100, TestDataset1.StartDay2 + 200)),
            };


            foreach (var(expected, desired) in tests)
            {
                Assert.AreEqual(expected, Routing.Algorithm.Utility.GetRealDesiredLength(data, desired));
            }
        }