Esempio n. 1
0
        static void Solve(List <List <int> > machines, List <List <int> > processingTimes, List <List <int> > jobIds, GPXPoint bucketInfo, int cycleTime)
        {
            Console.WriteLine("\n---- Job shop Scheduling Program ----");
            JobShop jobShop = new JobShop(machines, processingTimes, jobIds, bucketInfo, cycleTime);

            jobShop.RunJobShopScheduling("Jobshop");
        }
Esempio n. 2
0
    public static void Main(String[] args)
    {
        Console.WriteLine("\n---- Job shop Scheduling Program ----");
        JobShop jobShop = new JobShop();

        jobShop.RunJobShopScheduling("Jobshop");
    }
Esempio n. 3
0
        private async Task <Job> PostOrderToJob(OrderModel model, string adminUserId = null)
        {
            UserModel userModel      = new UserModel(await accountManager.FindByIdAsync(model.UserId));
            UserModel adminUserModel = null;

            Vendor vendor = default(Vendor);

            if (!string.IsNullOrWhiteSpace(model.VendorId))
            {
                vendor = await vendorService.Get(model.VendorId);
            }

            if (!string.IsNullOrWhiteSpace(adminUserId))
            {
                adminUserModel = new UserModel(await accountManager.FindByIdAsync(adminUserId));
            }

            JobShop    jobShop = new JobShop();
            JobBuilder builder;

            switch (model.Type)
            {
            case OrderTypes.ClassifiedDelivery:
            {
                ClassifiedDeliveryOrder classifiedDeliveryOrderModel = model as ClassifiedDeliveryOrder;
                if (!string.IsNullOrWhiteSpace(classifiedDeliveryOrderModel.BuyerInfo?.UserRef))
                {
                    var user = await accountManager.FindByIdAsync(classifiedDeliveryOrderModel.BuyerInfo.UserRef);

                    classifiedDeliveryOrderModel.BuyerInfo.PhoneNumber = user.PhoneNumber;
                    classifiedDeliveryOrderModel.BuyerInfo.Address     = user.Profile.Address;
                    classifiedDeliveryOrderModel.BuyerInfo.Name        = GetNameFromProfile(user);
                }
                if (!string.IsNullOrWhiteSpace(classifiedDeliveryOrderModel.SellerInfo?.UserRef))
                {
                    var user = await accountManager.FindByIdAsync(classifiedDeliveryOrderModel.SellerInfo.UserRef);

                    classifiedDeliveryOrderModel.SellerInfo.PhoneNumber = user.PhoneNumber;
                    classifiedDeliveryOrderModel.SellerInfo.Address     = user.Profile.Address;
                    classifiedDeliveryOrderModel.SellerInfo.Name        = GetNameFromProfile(user);
                }
                builder = GetDeliveryJobBuilder(userModel, adminUserModel, classifiedDeliveryOrderModel, vendor);
                break;
            }

            case OrderTypes.Delivery:
            {
                DeliveryOrder deliveryOrderModel = model as DeliveryOrder;
                builder = GetDeliveryJobBuilder(userModel, adminUserModel, deliveryOrderModel, vendor);
                break;
            }

            default:
                throw new InvalidOperationException("Invalid/Not supported Order Type Provided");
            }
            var result = await ConstructAndRegister(jobShop, builder);

            this.jobSearchIndexService.OnNext(result);
            return(result);
        }
Esempio n. 4
0
        private async Task <Job> ConstructAndRegister(JobShop jobShop, JobBuilder builder)
        {
            var createdJob = jobShop.Construct(builder);
            var result     = await manager.RegisterJob(createdJob);

            return(result);
        }
Esempio n. 5
0
        private static JobShop GenerateJobShop()
        {
            var generator = new JobShopGenerator();

            JobShop jobShop = generator.Generate(Global.Config.OperationCounts, Global.Config.MachinesCount);

            return(jobShop);
        }
Esempio n. 6
0
        /// <summary>
        /// Creates instance of <see cref="JobShopGeneticAlgorithm"/> from parameters.
        /// </summary>
        /// <param name="jobShop">Input.</param>
        /// <param name="iterationsCount">How many times will the GA be run repeatedly.</param>
        /// <param name="logger">Logger.</param>
        /// <param name="adaptive">True, if the algorithm should be adaptive.</param>
        /// <exception cref="ArgumentException"></exception>
        public JobShopGeneticAlgorithm(JobShop jobShop, int iterationsCount, ILogger logger, bool adaptive = true)
        {
            if (iterationsCount < 1)
            {
                throw new ArgumentException();
            }

            this.jobShop         = jobShop;
            this.iterationsCount = iterationsCount;
            this.logger          = logger;
            this.adaptive        = adaptive;
        }
Esempio n. 7
0
        private ScheduleChromosome(JobShop jobShop, bool generateNew) : base(jobShop.MachinesCount)
        {
            this.JobShop = jobShop;

            if (generateNew)
            {
                // initialize genes
                for (int i = 0; i < jobShop.MachinesCount; i++)
                {
                    var machineChromosome = new MachineChromosome(jobShop.MachineOperations[i]
                                                                  .AsShuffledEnumerable()
                                                                  .ToArray());
                    ReplaceGene(i, new Gene(machineChromosome));
                }
            }
        }
Esempio n. 8
0
        public void SetUp()
        {
            jobShop    = new JobShopLoader().Load("TestExamples/test1.in", false);
            chromosome = new ScheduleChromosome(jobShop);

            var machineChromosome1 = new MachineChromosome(new int[]
            {
                4, 5, 0, 2
            }.Select(x => jobShop.Operations[x]).ToArray());

            chromosome.ReplaceGene(0, new Gene(machineChromosome1));

            var machineChromosome2 = new MachineChromosome(new int[]
            {
                1, 3
            }.Select(x => jobShop.Operations[x]).ToArray());

            chromosome.ReplaceGene(1, new Gene(machineChromosome2));

            graphHandler = new GraphHandler();
        }
Esempio n. 9
0
        private async Task<Job> PostOrderToJob(OrderModel model, string adminUserId = null)
        {
            UserModel userModel = new UserModel(await accountManager.FindByIdAsync(model.UserId));
            UserModel adminUserModel = null;

            Vendor vendor = default(Vendor);
            if (!string.IsNullOrWhiteSpace(model.VendorId))
            {
                vendor = await vendorService.Get(model.VendorId);
            }

            if (!string.IsNullOrWhiteSpace(adminUserId))
            {
                adminUserModel = new UserModel(await accountManager.FindByIdAsync(adminUserId));
            }

            JobShop jobShop = new JobShop();
            JobBuilder builder;

            switch (model.Type)
            {
                case OrderTypes.Ride:
                    {
                        RideOrder rideOrderModel = model as RideOrder;
                        Validator.ValidateObject(rideOrderModel, new ValidationContext(rideOrderModel), true);
                        builder = adminUserModel == null ?
                            new RideJobBuilder(rideOrderModel, userModel, hridService)
                            : new RideJobBuilder(rideOrderModel, userModel, adminUserModel, hridService);
                        break;
                    }
                case OrderTypes.ClassifiedDelivery:
                    {
                        ClassifiedDeliveryOrder classifiedDeliveryOrderModel = model as ClassifiedDeliveryOrder;
                        if (!string.IsNullOrWhiteSpace(classifiedDeliveryOrderModel.BuyerInfo?.UserRef))
                        {
                            var user = await accountManager.FindByIdAsync(classifiedDeliveryOrderModel.BuyerInfo.UserRef);
                            classifiedDeliveryOrderModel.BuyerInfo.PhoneNumber = user.PhoneNumber;
                            classifiedDeliveryOrderModel.BuyerInfo.Address = user.Profile.Address;
                            classifiedDeliveryOrderModel.BuyerInfo.Name = GetNameFromProfile(user);
                        }
                        if (!string.IsNullOrWhiteSpace(classifiedDeliveryOrderModel.SellerInfo?.UserRef))
                        {
                            var user = await accountManager.FindByIdAsync(classifiedDeliveryOrderModel.SellerInfo.UserRef);
                            classifiedDeliveryOrderModel.SellerInfo.PhoneNumber = user.PhoneNumber;
                            classifiedDeliveryOrderModel.SellerInfo.Address = user.Profile.Address;
                            classifiedDeliveryOrderModel.SellerInfo.Name = GetNameFromProfile(user);
                        }
                        builder = GetDeliveryJobBuilder(userModel, adminUserModel, classifiedDeliveryOrderModel, vendor);
                        break;
                    }
                case OrderTypes.Delivery:
                    {
                        DeliveryOrder deliveryOrderModel = model as DeliveryOrder;
                        builder = GetDeliveryJobBuilder(userModel, adminUserModel, deliveryOrderModel, vendor);
                        break;
                    }
                default:
                    throw new InvalidOperationException("Invalid/Not supported Order Type Provided");
            }
            return await ConstructAndRegister(jobShop, builder);
        }
Esempio n. 10
0
 private async Task<Job> ConstructAndRegister(JobShop jobShop, JobBuilder builder)
 {
     var createdJob = jobShop.Construct(builder);
     return await manager.RegisterJob(createdJob);
 }
Esempio n. 11
0
    public void RunJobShopScheduling(String solverType)
    {
        Solver solver = new Solver(solverType);

        if (solver == null)
        {
            Console.WriteLine("JobShop failed to create a solver " + solverType);
            return;
        }

        // All tasks
        Dictionary <string, IntervalVar> allTasks = new Dictionary <string, IntervalVar>();

        // Creates jobs
        for (int i = 0; i < allJobs.Count; i++)
        {
            for (int j = 0; j < machines.ElementAt(i).Count; j++)
            {
                IntervalVar oneTask = solver.MakeFixedDurationIntervalVar(0,
                                                                          horizon,
                                                                          processingTimes.ElementAt(i).ElementAt(j),
                                                                          false,
                                                                          "Job_" + i + "_" + j);
                //Console.WriteLine("Job_" + i + "_" + j);
                allTasks.Add("Job_" + i + "_" + j, oneTask);
            }
        }

        // Create sequence variables and add disjuctive constraints
        List <SequenceVar> allSequences = new List <SequenceVar>();

        foreach (var machine in allMachines)
        {
            List <IntervalVar> machinesJobs = new List <IntervalVar>();
            for (int i = 0; i < allJobs.Count; i++)
            {
                for (int k = 0; k < machines.ElementAt(i).Count; k++)
                {
                    if (machines.ElementAt(i).ElementAt(k) == machine)
                    {
                        machinesJobs.Add(allTasks["Job_" + i + "_" + k]);
                    }
                }
            }

            DisjunctiveConstraint disj = solver.MakeDisjunctiveConstraint(machinesJobs.ToArray(),
                                                                          "machine " + machine);
            allSequences.Add(disj.SequenceVar());
            solver.Add(disj);
        }

        // Add conjunctive constraints
        foreach (var job in allJobs)
        {
            for (int j = 0; j < machines.ElementAt(job).Count - 1; j++)
            {
                solver.Add(allTasks["Job_" + job + "_" + (j + 1)].StartsAfterEnd(allTasks["Job_" + job + "_" + j]));
            }
        }

        // Set the objective
        IntVar[] allEnds = new IntVar[jobsCount];
        for (int i = 0; i < allJobs.Count; i++)
        {
            allEnds[i] = allTasks["Job_" + i + "_" + (machines.ElementAt(i).Count - 1)].EndExpr().Var();
        }

        // Objective: minimize the makespan (maximum end times of all tasks)
        // of the problem.
        IntVar      objectiveVar     = solver.MakeMax(allEnds).Var();
        OptimizeVar objectiveMonitor = solver.MakeMinimize(objectiveVar, 1);

        // Create search phases
        DecisionBuilder sequencePhase = solver.MakePhase(allSequences.ToArray(), Solver.SEQUENCE_DEFAULT);
        DecisionBuilder varsPhase     = solver.MakePhase(objectiveVar, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MIN_VALUE);

        // The main decision builder (ranks all tasks, then fixes the
        // objectiveVariable).
        DecisionBuilder mainPhase = solver.Compose(sequencePhase, varsPhase);

        SolutionCollector collector = solver.MakeLastSolutionCollector();

        collector.Add(allSequences.ToArray());
        collector.Add(objectiveVar);

        foreach (var i in allMachines)
        {
            SequenceVar sequence      = allSequences.ElementAt(i);
            long        sequenceCount = sequence.Size();
            for (int j = 0; j < sequenceCount; j++)
            {
                IntervalVar t = sequence.Interval(j);
                collector.Add(t.StartExpr().Var());
                collector.Add(t.EndExpr().Var());
            }
        }

        // Search.
        bool solutionFound = solver.Solve(mainPhase, null, objectiveMonitor, null, collector);

        if (solutionFound)
        {
            //The index of the solution from the collector
            const int  SOLUTION_INDEX = 0;
            Assignment solution       = collector.Solution(SOLUTION_INDEX);

            string solLine      = "";
            string solLineTasks = "";
            Console.WriteLine("Time Intervals for Tasks\n");

            List <List <TimeSpan> > tuplesSolution = new List <List <TimeSpan> >();

            for (int m = 0; m < this.machinesCount; m++)
            {
                //Console.WriteLine("MachineCount: " + this.machinesCount);
                solLine      = "Machine " + m + " :";
                solLineTasks = "Machine " + m + ": ";

                SequenceVar seq            = allSequences.ElementAt(m);
                int[]       storedSequence = collector.ForwardSequence(SOLUTION_INDEX, seq);

                foreach (int taskIndex in storedSequence)
                {
                    //Console.WriteLine("taskIndex: " + taskIndex);
                    IntervalVar task = seq.Interval(taskIndex);
                    solLineTasks += task.Name() + " ";
                    //Console.WriteLine("Len: " + storedSequence.Length);
                }

                // First GreenTime
                //TimeSpan timeToAdd = tuplesSolution.First().Last();
                TimeSpan timeEndBucket   = this.bucketInfo.EndBucket;
                TimeSpan timeStartBucket = this.bucketInfo.StartBucket;


                int  solutionSize = tuplesSolution.Count;
                bool isEnd        = false;

                List <int> list_id = jobIds.ElementAt(m);
                // Adding GreenTime to Solution
                while (timeStartBucket.CompareTo(timeEndBucket) < 0)
                {
                    foreach (int taskIndex in storedSequence)
                    {
                        IntervalVar task = seq.Interval(taskIndex);

                        var startValue = TimeSpan.FromSeconds(collector.Value(0, task.StartExpr().Var()));
                        var endValue   = TimeSpan.FromSeconds(collector.Value(0, task.EndExpr().Var()));

                        TimeSpan greenTime = endValue.Subtract(startValue);
                        TimeSpan timeEnd;

                        timeEnd = timeStartBucket.Add(greenTime);


                        List <TimeSpan> tuple = new List <TimeSpan>();
                        tuple.Add(timeStartBucket);
                        if (timeEndBucket.CompareTo(timeEnd) < 0)
                        {
                            timeEnd = timeEndBucket;
                            isEnd   = true;
                        }

                        tuple.Add(timeEnd);
                        tuplesSolution.Add(tuple);
                        if (taskIndex + 1 < list_id.Count() && list_id.ElementAt(taskIndex) == list_id.ElementAt(taskIndex + 1))
                        {
                            timeStartBucket = timeStartBucket.Add(TimeSpan.FromSeconds(this.cycleTime));
                        }
                        else
                        {
                            timeStartBucket = timeEnd;
                        }
                        if (isEnd)
                        {
                            break;
                        }
                    }
                }

                //
                // Saving the Solution to a XML file
                //
                JobShop.save(m, tuplesSolution);

                //solLine += "\n";
                //solLineTasks += "\n";

                //Console.WriteLine(solLineTasks);
                //Console.WriteLine(solLine);
            }
        }
        else
        {
            Console.WriteLine("No solution found!");
        }
    }
Esempio n. 12
0
 public static void save(int machine, List <List <TimeSpan> > tuplesSolution)
 {
     JobShop.createNewXML(machine, tuplesSolution);
 }
Esempio n. 13
0
 public ScheduleChromosome(JobShop jobShop) : this(jobShop, true)
 {
 }
Esempio n. 14
0
        private static void Main(string[] args)
        {
            ParseCmdArguments(args);

            string inputPath       = Global.Config.InputFilePath;
            string inputName       = Path.GetFileName(inputPath);
            int    iterationsCount = Global.Config.IterationsCount;

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Information()
                         .WriteTo.Console()
                         .WriteTo.File($"{inputName}.log")
                         .CreateLogger();

            Log.Information("CONFIG PARAMETERS");
            Log.Information(Global.Config.ToString());

            JobShop jobShop = LoadJobShop(inputPath);
            //JobShop jobShop = GenerateJobShop();

            var plottingUtils = new PlottingHelper();

            var gaAdaptive = new JobShopGeneticAlgorithm(jobShop, iterationsCount, logger: Log.Logger, adaptive: true)
            {
                PlotModel = plottingUtils.CreatePlotModel()
            };

            gaAdaptive.Run();
            var adaptiveSeries = plottingUtils.AverageY(gaAdaptive.PlotModel.Series.OfType <LineSeries>());

            adaptiveSeries.Title = "Adaptive";
            using (var sw = new StreamWriter($"{inputName}.out"))
            {
                sw.WriteLine("Adaptive");
                sw.WriteLine();

                sw.WriteLine(gaAdaptive.BestSchedule.GetStringRepresentation());
                sw.WriteLine($"Schedule length: {gaAdaptive.BestSchedule.ScheduleLength}");

                sw.WriteLine();
            }

            var gaNonAdaptive = new JobShopGeneticAlgorithm(jobShop, iterationsCount, logger: Log.Logger, adaptive: false)
            {
                PlotModel = plottingUtils.CreatePlotModel()
            };

            gaNonAdaptive.Run();
            var nonAdaptiveSeries = plottingUtils.AverageY(gaNonAdaptive.PlotModel.Series.OfType <LineSeries>());

            nonAdaptiveSeries.Title = "Basic";

            var plotModel = plottingUtils.CreatePlotModel();

            plotModel.Title = inputName;
            plotModel.Series.Add(adaptiveSeries);
            plotModel.Series.Add(nonAdaptiveSeries);

            plottingUtils.ExportPlotModelToSvg(inputName, plotModel);

            using (var sw = new StreamWriter($"{inputName}.out", append: true))
            {
                sw.WriteLine("Non-adaptive");
                sw.WriteLine();

                sw.WriteLine(gaNonAdaptive.BestSchedule.GetStringRepresentation());
                sw.WriteLine($"Schedule length: {gaNonAdaptive.BestSchedule.ScheduleLength}");

                sw.WriteLine();
            }
        }