예제 #1
0
        public void ConvertDataVectorToVectorsTest()
        {
            ProblemInstance problemInstance = new ProblemInstance(new double[] { 1, 2, 2, -1 }, new double[] { 5, 0, 0, 1, 1, 5, 0, 0, 3, 4, -2, -2, 8, 7, -2, 12 });

            HybridQaoa classicalOptimization = new HybridQaoa(2, 3, problemInstance, 1, new Double[] { 1, 2, 3 }, new Double[] { 4, 5, 6 });

            Utils.FreeParamsVector result = Utils.ConvertVectorIntoHalves(new Double[] { 1, 2, 3, 4, 5, 6 });

            Utils.FreeParamsVector dataVectors = new Utils.FreeParamsVector();
            dataVectors.beta  = new double[] { 1, 2, 3 };
            dataVectors.gamma = new double[] { 4, 5, 6 };

            Utils.FreeParamsVector expectedResult = dataVectors;

            CollectionAssert.AreEqual(expectedResult.beta, result.beta, "Hamiltonian beta value not calculated correctly.");
            CollectionAssert.AreEqual(expectedResult.gamma, result.gamma, "Hamiltonian gamma value not calculated correctly.");
        }
예제 #2
0
        public static ProblemInstance GetInstance(IEnumerable <MenuOrder> menuOrders, IEnumerable <Worker> workers)
        {
            ProblemInstance problemInstance = new ProblemInstance();

            problemInstance.n = menuOrders.Count();
            problemInstance.m = workers.Count();

            JobDetails[]     job_details     = new JobDetails[problemInstance.n];
            List <MenuOrder> menuOrders_list = menuOrders.ToList();

            for (int i = 0; i < job_details.Length; i++)
            {
                job_details[i] = new JobDetails(Convert.ToDouble(100 * menuOrders_list[i].JD), Convert.ToDouble(100 * menuOrders_list[i].WD));
            }
            problemInstance.job_details = job_details;

            return(problemInstance);
        }
예제 #3
0
        public void ReadFromJsonTest()
        {
            try
            {
                var sampleFile = @"C:\Users\gille\Documents\Development\Cff_Schedule\tschedule\C# - Optimizer\TrainScheduler\Samples\sample_scenario.json";
                var json       = File.ReadAllText(sampleFile);

                var sampleScenario = new ProblemInstance();
                sampleScenario.FromJson(json);

                Assert.AreEqual(sampleScenario.Hash, -1254734547);
                Assert.AreEqual(sampleScenario.ServiceIntentions.Count, 2);
                Assert.AreEqual(sampleScenario.Resources.Count, 13);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
예제 #4
0
        public ProblemInstance Produce(TrademarkRepository rep)
        {
            var res = new ProblemInstance {
                TrademarkRepository = rep
            };

            foreach (var trademark in rep.AllTrademarks)
            {
                if (res.TrainingSetRatio <= trainingSetRatio)
                {
                    res.TrainingSet.Add(trademark);
                }
                else
                {
                    res.ControlSet.Add(trademark);
                }
            }
            return(res);
        }
        protected override void PerformMove()
        {
            PotvinCustomerRelocationMove move = CustomerRelocationMoveParameter.ActualValue;

            PotvinEncoding newSolution = move.Individual.Clone() as PotvinEncoding;

            Apply(newSolution, move, ProblemInstance);
            newSolution.Repair();
            VRPToursParameter.ActualValue = newSolution;

            //reset move quality
            VRPEvaluation eval = ProblemInstance.Evaluate(newSolution);

            MoveQualityParameter.ActualValue.Value = eval.Quality;

            //update memory
            VariableCollection memory = MemoriesParameter.ActualValue;
            string             key    = AdditionFrequencyMemoryKeyParameter.Value.Value;

            if (memory != null)
            {
                if (!memory.ContainsKey(key))
                {
                    memory.Add(new Variable(key,
                                            new ItemDictionary <PotvinCustomerRelocationMoveAttribute, IntValue>()));
                }
                ItemDictionary <PotvinCustomerRelocationMoveAttribute, IntValue> additionFrequency =
                    memory[key].Value as ItemDictionary <PotvinCustomerRelocationMoveAttribute, IntValue>;

                PotvinCustomerRelocationMoveAttribute attr = new PotvinCustomerRelocationMoveAttribute(0, move.Tour, move.City);
                if (!additionFrequency.ContainsKey(attr))
                {
                    additionFrequency[attr] = new IntValue(0);
                }

                additionFrequency[attr].Value++;
            }
        }
        private bool FindRouteInsertionPlace(
            PotvinEncoding individual,
            Tour tour,
            int city, bool allowInfeasible, out int place)
        {
            place = -1;

            if (tour.Stops.Contains(city))
            {
                return(false);
            }

            if (tour.Stops.Count == 0)
            {
                place = 0;
                return(true);
            }

            double        minDetour        = 0;
            VRPEvaluation eval             = ProblemInstance.EvaluateTour(tour, individual);
            bool          originalFeasible = ProblemInstance.Feasible(eval);

            for (int i = 0; i <= tour.Stops.Count; i++)
            {
                bool   feasible;
                double detour = ProblemInstance.GetInsertionCosts(eval, individual, city, 0, i, out feasible);
                if (feasible || allowInfeasible)
                {
                    if (place < 0 || detour < minDetour)
                    {
                        place     = i;
                        minDetour = detour;
                    }
                }
            }

            return(place >= 0);
        }
예제 #7
0
        public void RunHybridQaoaTest()
        {
            double[] dh = new Double[] { 0, 0 };
            double[] dJ = new Double[] { 0, 1,
                                         0, 0 };

            int numberOfIterations = 50;
            int p = 2;
            int numberOfRandomStartingPoints = 2;

            ProblemInstance simpleMaxCut = new ProblemInstance(dh, dJ);

            HybridQaoa      classicalOptimization = new HybridQaoa(numberOfIterations, p, simpleMaxCut, numberOfRandomStartingPoints);
            OptimalSolution optimalSolution       = classicalOptimization.RunOptimization();

            string optimizationResult1 = "01";
            string optimizationResult2 = "10";

            string result = optimalSolution.optimalVector;

            Console.WriteLine(result);

            Assert.IsTrue(result.Equals(optimizationResult1) || result.Equals(optimizationResult2), "Hybrid QAOA produced incorrect result.");
        }
예제 #8
0
 protected double GetQuality(PrinsEncoding individual)
 {
     return(ProblemInstance.Evaluate(individual).Quality);
 }
예제 #9
0
        public override List <Tour> GetTours()
        {
            List <Tour> result = new List <Tour>();

            int cities = ProblemInstance.Cities.Value;

            //Split permutation into vector P
            int[] P = new int[cities + 1];
            for (int i = 0; i <= cities; i++)
            {
                P[i] = -1;
            }

            double[] V = new double[cities + 1];
            V[0] = 0;
            for (int i = 1; i <= cities; i++)
            {
                V[i] = double.MaxValue;
            }

            for (int i = 1; i <= cities; i++)
            {
                int  j        = i;
                Tour tour     = new Tour();
                bool feasible = true;

                do
                {
                    tour.Stops.Add(this[j - 1] + 1);

                    VRPEvaluation eval =
                        ProblemInstance.EvaluateTour(tour, this);

                    double cost = eval.Quality;
                    feasible = ProblemInstance.Feasible(eval);

                    if (feasible || j == i)
                    {
                        if (V[i - 1] + cost < V[j])
                        {
                            V[j] = V[i - 1] + cost;
                            P[j] = i - 1;
                        }
                        j++;
                    }
                } while (j <= cities && feasible);
            }

            //extract VRP solution from vector P
            int  index  = 0;
            int  index2 = cities;
            Tour trip   = null;

            do
            {
                index = P[index2];
                trip  = new Tour();

                for (int k = index + 1; k <= index2; k++)
                {
                    trip.Stops.Add(this[k - 1] + 1);
                }

                if (trip.Stops.Count > 0)
                {
                    result.Add(trip);
                }

                index2 = index;
            } while (index != 0);

            //if there are too many vehicles - repair
            while (result.Count > ProblemInstance.Vehicles.Value)
            {
                Tour tour = result[result.Count - 1];

                //find predecessor / successor in permutation
                int predecessorIndex = Array.IndexOf(this.array, tour.Stops[0] - 1) - 1;
                if (predecessorIndex >= 0)
                {
                    int predecessor = this[predecessorIndex] + 1;

                    foreach (Tour t in result)
                    {
                        int insertPosition = t.Stops.IndexOf(predecessor) + 1;
                        if (insertPosition != -1)
                        {
                            t.Stops.InsertRange(insertPosition, tour.Stops);
                            break;
                        }
                    }
                }
                else
                {
                    int successorIndex = Array.IndexOf(this.array,
                                                       tour.Stops[tour.Stops.Count - 1] - 1) + 1;
                    int successor = this[successorIndex] + 1;

                    foreach (Tour t in result)
                    {
                        int insertPosition = t.Stops.IndexOf(successor);
                        if (insertPosition != -1)
                        {
                            t.Stops.InsertRange(insertPosition, tour.Stops);
                            break;
                        }
                    }
                }

                result.Remove(tour);
            }

            return(result);
        }
예제 #10
0
        private GVREncoding Crossover(IRandom random, GVREncoding parent1, GVREncoding parent2)
        {
            GVREncoding child = parent1.Clone() as GVREncoding;

            Tour       tour        = parent2.Tours[random.Next(parent2.Tours.Count)];
            int        breakPoint1 = random.Next(tour.Stops.Count);
            int        length      = random.Next(1, tour.Stops.Count - breakPoint1 + 1);
            List <int> subroute    = tour.Stops.GetRange(breakPoint1, length);

            //remove duplicates
            List <Tour> toBeRemoved = new List <Tour>();

            foreach (Tour route in child.Tours)
            {
                foreach (int city in subroute)
                {
                    route.Stops.Remove(city);
                }

                if (route.Stops.Count == 0)
                {
                    toBeRemoved.Add(route);
                }
            }
            foreach (Tour route in toBeRemoved)
            {
                child.Tours.Remove(route);
            }

            //choose nearest customer
            double minDistance = -1;
            int    customer    = -1;

            for (int i = 1; i <= ProblemInstance.Cities.Value; i++)
            {
                if (!subroute.Contains(i))
                {
                    double distance = ProblemInstance.GetDistance(subroute[0], i, child);

                    if (customer == -1 || distance < minDistance)
                    {
                        customer    = i;
                        minDistance = distance;
                    }
                }
            }

            //insert
            if (customer != -1)
            {
                Tour newTour;
                int  newPosition;
                child.FindCustomer(customer, out newTour, out newPosition);
                newTour.Stops.InsertRange(newPosition + 1, subroute);
            }
            else
            {
                //special case -> only one tour, whole tour has been chosen as subroute
                child = parent1.Clone() as GVREncoding;
            }

            return(child);
        }
예제 #11
0
        public static int ScheduleTrains(ProblemInstance problem, IEnumerable <TrainRun> trainRuns)
        {
            var nbConflicts   = 0;
            var usedResources = new UsedResourceCollection();

            foreach (var trainRun in trainRuns)
            {
                // ----------------------------------------------------
                //Log($"Delay train {trainRun.ServiceIntentionId} start ? ", Utils.Logging.LogEventArgs.MessageType.Info, false);
                var delay             = TimeSpan.Zero;
                var initialRunSection = trainRun.TrainRunSections[0];
                var initialSection    = problem.TryGetRouteSection(initialRunSection.Key);
                foreach (var resId in initialSection.ResourceIds)
                {
                    var resource = problem.TryGetResource(resId);
                    if (resource != null)
                    {
                        foreach (var usage in usedResources.UsageByOtherThan(resId, trainRun.ServiceIntentionId))
                        {
                            if (Math.Intersect(initialRunSection.EntryTime, initialRunSection.ExitTime + resource.ReleaseTime, usage.Item3, usage.Item4))
                            {
                                delay = Math.Max(delay, usage.Item4 - initialRunSection.EntryTime);
                            }
                        }
                    }
                }

                // Postpone train departure
                if (delay > TimeSpan.Zero)
                {
                    ++nbConflicts;
                    //Log($"Yes. Delay is {delay}");
                    initialRunSection.EntryTime += delay;
                    trainRun.ApplyDelay(delay);
                }

                //Log($"Check other sections for delays ... ");
                for (int k = 1; k < trainRun.TrainRunSections.Count; ++k)
                {
                    var runSection = trainRun.TrainRunSections[k];
                    var section    = problem.TryGetRouteSection(runSection.Key);

                    // Check resource occupation for next section
                    delay = TimeSpan.Zero;

                    foreach (var resId in section.ResourceIds)
                    {
                        var resource = problem.TryGetResource(resId);
                        if (resource != null)
                        {
                            foreach (var usage in usedResources.UsageByOtherThan(resId, trainRun.ServiceIntentionId))
                            {
                                if (Math.Intersect(runSection.EntryTime, runSection.ExitTime + resource.ReleaseTime, usage.Item3, usage.Item4))
                                {
                                    delay = Math.Max(delay, usage.Item4 - runSection.EntryTime);
                                }
                            }
                        }
                    }

                    if (delay > TimeSpan.Zero)
                    {
                        ++nbConflicts;
                        //Log($"Delay exit of train {trainRun.ServiceIntentionId}, from section {k-1} by {delay}");
                        trainRun.ApplyDelay(delay, k - 1);
                    }
                }

                // ----------------------------------------------------
                //Log($"Add current train resource occupation ... ");
                foreach (var runSection in trainRun.TrainRunSections)
                {
                    var section = problem.TryGetRouteSection(runSection.Key);

                    foreach (var resId in section.ResourceIds)
                    {
                        var resource = problem.TryGetResource(resId);
                        if (resource != null)
                        {
                            usedResources.Add(resId, trainRun.ServiceIntentionId, runSection.SequenceNumber,
                                              runSection.EntryTime, runSection.ExitTime + resource.ReleaseTime);
                        }
                    }
                }
            }

            return(nbConflicts);
        }
예제 #12
0
        public static void ScheduleTrains(ProblemInstance problem, IEnumerable <TrainRun> trainRuns, UsedResourceCollection usedResources)
        {
            foreach (var trainRun in trainRuns)
            {
                // Schedule train accordingly
                for (int k = 0; k < trainRun.TrainRunSections.Count; ++k)
                {
                    var thisRunSection = trainRun.TrainRunSections[k];
                    var nextRunSection = (k < trainRun.TrainRunSections.Count - 1)
                  ? trainRun.TrainRunSections[k + 1]
                  : null;

                    var thisSection = problem.TryGetRouteSection(thisRunSection.Key);
                    var nextSection = problem.TryGetRouteSection(nextRunSection?.Key);

                    // ------------------------------------------------
                    // Is there a min entry/exit time
                    var thisRequirement = trainRun.Train.GetRequirement(thisSection.SectionMarker);
                    var nextRequirement = trainRun.Train.GetRequirement(nextSection?.SectionMarker);

                    // ------------------------------------------------
                    // Start time is always last exit time unless this is the first section
                    if (k > 0)
                    {
                        thisRunSection.EntryTime = trainRun.TrainRunSections[k - 1].ExitTime;
                    }
                    else
                    {
                        thisRunSection.EntryTime = Math.Max(thisRunSection.EntryTime, thisRequirement.minEntryTime);

                        // Check resource occupation
                        if (nextRunSection != null)
                        {
                            foreach (var resId in thisSection.ResourceIds)
                            {
                                foreach (var usage in usedResources.UsageByOtherThan(resId, trainRun.ServiceIntentionId))
                                {
                                    thisRunSection.EntryTime = Math.Max(thisRunSection.EntryTime, usage.Item4);
                                }
                            }
                        }
                    }

                    // ------------------------------------------------
                    // Set exit time, taking into acount resource occupation of next section
                    thisRunSection.ExitTime = Math.Max(thisRequirement.minExitTime,
                                                       thisRunSection.EntryTime + thisSection.MinimumRunningTime +
                                                       thisRequirement.minStoppingTime);

                    // Consider minEntryTime for next section
                    thisRunSection.ExitTime = Math.Max(thisRunSection.ExitTime, nextRequirement.minEntryTime);

                    // Check resource occupation
                    if (nextRunSection != null)
                    {
                        foreach (var resId in nextSection.ResourceIds)
                        {
                            foreach (var usage in usedResources.UsageByOtherThan(resId, trainRun.ServiceIntentionId))
                            {
                                thisRunSection.ExitTime = Math.Max(thisRunSection.ExitTime, usage.Item4);
                            }
                        }
                    }

                    // ------------------------------------------------
                    // Add current resource occupation
                    foreach (var resId in thisSection.ResourceIds)
                    {
                        var resource = problem.TryGetResource(resId);
                        if (resource != null)
                        {
                            usedResources.Add(resId, trainRun.ServiceIntentionId, thisRunSection.SequenceNumber,
                                              thisRunSection.EntryTime, thisRunSection.ExitTime + resource.ReleaseTime);
                        }
                    }
                }
            }
        }
예제 #13
0
        public override List <Tour> GetTours()
        {
            List <Tour> result = new List <Tour>();

            Tour newTour = new Tour();

            for (int i = 0; i < this.Length; i++)
            {
                int city = this[i] + 1;
                newTour.Stops.Add(city);
                if (!ProblemInstance.TourFeasible(newTour, this))
                {
                    newTour.Stops.Remove(city);
                    if (newTour.Stops.Count > 0)
                    {
                        result.Add(newTour);
                    }

                    newTour = new Tour();
                    newTour.Stops.Add(city);
                }
            }

            if (newTour.Stops.Count > 0)
            {
                result.Add(newTour);
            }

            //if there are too many vehicles - repair
            while (result.Count > ProblemInstance.Vehicles.Value)
            {
                Tour tour = result[result.Count - 1];

                //find predecessor / successor in permutation
                int predecessorIndex = Array.IndexOf(this.array, tour.Stops[0] - 1) - 1;
                if (predecessorIndex >= 0)
                {
                    int predecessor = this[predecessorIndex] + 1;

                    foreach (Tour t in result)
                    {
                        int insertPosition = t.Stops.IndexOf(predecessor) + 1;
                        if (insertPosition != -1)
                        {
                            t.Stops.InsertRange(insertPosition, tour.Stops);
                            break;
                        }
                    }
                }
                else
                {
                    int successorIndex = Array.IndexOf(this.array,
                                                       tour.Stops[tour.Stops.Count - 1] - 1) + 1;
                    int successor = this[successorIndex] + 1;

                    foreach (Tour t in result)
                    {
                        int insertPosition = t.Stops.IndexOf(successor);
                        if (insertPosition != -1)
                        {
                            t.Stops.InsertRange(insertPosition, tour.Stops);
                            break;
                        }
                    }
                }

                result.Remove(tour);
            }

            return(result);
        }
예제 #14
0
        protected override ZhuEncoding Crossover(IRandom random, ZhuEncoding parent1, ZhuEncoding parent2)
        {
            List <int> p1 = new List <int>(parent1);
            List <int> p2 = new List <int>(parent2);

            ZhuEncoding child = parent2.Clone() as ZhuEncoding;

            if (parent1.Length != parent2.Length)
            {
                return(child);
            }

            int breakPoint  = random.Next(child.Length);
            int i           = breakPoint;
            int predecessor = breakPoint - 1;

            if (predecessor < 0)
            {
                predecessor = predecessor + child.Length;
            }

            int parent1Index = i;
            int parent2Index = i;

            while (i != predecessor)
            {
                if (i == breakPoint)
                {
                    child[i] = p1[parent1Index];

                    p1.Remove(child[i]);
                    if (parent1Index >= p1.Count)
                    {
                        parent1Index = 0;
                    }

                    p2.Remove(child[i]);
                    if (parent2Index >= p2.Count)
                    {
                        parent2Index = 0;
                    }
                }

                if (ProblemInstance.GetDistance(
                        child[i] + 1, p1[parent1Index] + 1, child)
                    <
                    ProblemInstance.GetDistance(
                        child[i] + 1, p2[parent2Index] + 1, child))
                {
                    child[(i + 1) % child.Length] = p1[parent1Index];
                }
                else
                {
                    child[(i + 1) % child.Length] = p2[parent2Index];
                }

                p1.Remove(child[(i + 1) % child.Length]);
                if (parent1Index >= p1.Count)
                {
                    parent1Index = 0;
                }

                p2.Remove(child[(i + 1) % child.Length]);
                if (parent2Index >= p2.Count)
                {
                    parent2Index = 0;
                }

                i = (i + 1) % child.Length;
            }

            return(child);
        }
예제 #15
0
    public static List <ProblemInstance> LoadInstanceDataFromFile(string dataFilePath)
    {
        List <ProblemInstance> instances   = new List <ProblemInstance>();
        List <string>          problemSets = new List <string>();

        bool         firstLine = true;
        string       line;
        StreamReader file = new StreamReader(dataFilePath);

        while ((line = file.ReadLine()) != null)
        {
            if (firstLine)
            {
                // Header
                firstLine = false;
                continue;
            }

            //ProblemSet;ProblemName;ProblemFile;SolutionFile;Type;Size;Tightness;Optimal;BKS;CpuSolveTime
            //A;A-n32-k5;A-n32-k5.vrp;A-n32-k5.opt;U;32;0.82;784;784;5.33
            //0 1        2            3            4 5  6    7   8   9
            var    parts          = line.Trim().Split(';');
            string problemfolder  = CVRBLIBFOLDER + '\\' + parts[0];
            double typeMultiplier = parts[4] == "U" ?
                                    1.0 :                             // uniform = hard
                                    ((parts[4] == "C") ? 0.5 : 0.75); // clustered = easy, other other.
            double optval      = Double.Parse(parts[7], CultureInfo.InvariantCulture);
            var    readProblem = new ProblemInstance()
            {
                ProblemSet   = parts[0],
                ProblemName  = parts[1],
                ProblemFile  = problemfolder + '\\' + parts[2],
                SolutionFile = problemfolder + '\\' + parts[3],

                Size         = Int32.Parse(parts[5]),
                BKS          = Double.Parse(parts[8], CultureInfo.InvariantCulture),
                Tightness    = Double.Parse(parts[6], CultureInfo.InvariantCulture),
                CpuSolveTime = Double.Parse(parts[9], CultureInfo.InvariantCulture),

                // TODO: load these from another file
                Locked          = true,
                Stars           = 0,
                personalBestSol = null,
                personalBest_k  = null,
            };

            if (!problemSets.Contains(readProblem.ProblemSet))
            {
                readProblem.Locked = false;
                problemSets.Add(readProblem.ProblemSet);
            }


            readProblem.Difficulty =
                0.33 * readProblem.Size / 200 +
                0.33 * Math.Sqrt(readProblem.Tightness) * typeMultiplier +
                0.33 * Math.Log10(readProblem.CpuSolveTime) / MAX_LOG_T_VAL;

            readProblem.BKSisOptimal = readProblem.BKS == optval;
            instances.Add(readProblem);
        }
        return(instances);
    }