Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import com.sun.org.apache.xpath.internal.SourceTree;
- import msrcpsp.evaluation.BaseEvaluator;
- import msrcpsp.evaluation.DurationEvaluator;
- import msrcpsp.io.MSRCPSPIO;
- import msrcpsp.scheduling.*;
- import msrcpsp.scheduling.greedy.Greedy;
- import msrcpsp.validation.AssignmentValidator;
- import msrcpsp.validation.BaseValidator;
- import msrcpsp.validation.CompleteValidator;
- import java.io.BufferedWriter;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.*;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- /**
- * Runner class to help with understanding of the library.
- */
- public class Runner {
- private static final Logger LOGGER = Logger.getLogger( Runner.class.getName() );
- private static final String definitionFile = "assets/def_small/100_10_26_15.def";
- private static final String writeFile = "assets/solutions_small/100_10_26_15.sol";
- //params for Genetic Algorithm
- private static final int pop_size = 100;
- private static final int generation_max = 100;
- private static final double crossover_probability = 0;
- private static final double mutation_probability = 0.05;
- private static final int challengers = 3;
- public static final int number_of_runs = 1;
- private static final Random random = new Random(System.currentTimeMillis());
- //these arrays must have lenght of generation_max, these arrayse serve for statistical averaging
- private static final int[] avg_max = new int[generation_max];
- private static final int[] avg_avg = new int[generation_max];
- private static final int[] avg_min = new int[generation_max];
- public static void main(String[] args) {
- //int pop_size = 100;
- //our population
- // read definition file into Schedule object
- MSRCPSPIO reader = new MSRCPSPIO();
- Schedule schedule_orig = reader.readDefinition(definitionFile);
- if (null == schedule_orig) {
- LOGGER.log(Level.WARNING, "Could not read the Definition " + definitionFile);
- }
- //here, a copy of conducted schedule is made, this copy will be used to evaluate efficiency of greedy algorithm for whole probelm, not just <task, start time> subproblem
- Schedule schedule_greedy = new Schedule(schedule_orig);
- Greedy greedy_comp = new Greedy(schedule_greedy.getSuccesors());
- greedy_comp.buildAssignments(schedule_greedy);
- greedy_comp.buildTimestamps(schedule_greedy);
- BaseEvaluator greedy_eval = new DurationEvaluator(schedule_greedy);
- BaseIndividual greedy_ind = new BaseIndividual(schedule_greedy,greedy_eval);
- greedy_ind.setDuration();
- //here is loop for runs - which are repetitions of GA on the same set of Tasks and Resources, from wich min, max and avg values of each run will be averaged
- for (int run = 0; run < number_of_runs; run++) {
- List<BaseIntIndividual> pop = new ArrayList<BaseIntIndividual>();
- //copying original schedule (or rather set of Tasks ans Resources) for this run
- Schedule schedule = new Schedule(schedule_orig);
- // get array of upper bounds of each task assignment, that does
- // violate skill constraint
- int[] upperBounds = schedule.getUpperBounds(schedule.getTasks().length);
- // create an evaluator
- //BaseEvaluator evaluator = new DurationEvaluator(schedule);
- //table of tasks
- Task[] tasks = schedule.getTasks();
- //Resource[] resources = schedule.getResources();
- // create greedy algorithm to set timestamps
- Greedy greedy = new Greedy(schedule.getSuccesors());
- // create validators
- BaseValidator validator = new CompleteValidator();
- BaseValidator assign_validator = new AssignmentValidator();
- //System.out.println(validator.validate(schedule));
- //System.out.println(validator.getErrorMessages());
- //generation of start population
- for (int i = 0; i < pop_size; i++)
- {
- //prepare genotype table (chromosomes)
- int[] genes = new int[tasks.length];
- //clones schedule for new individual
- Schedule s_copy = new Schedule(schedule);
- Task[] tasks_copy = s_copy.getTasks();
- // create schedule randomly, while keeping constraints
- //Random random = new Random(System.currentTimeMillis());
- List<Resource> capableResources;
- for (int j = 0; j < tasks.length; ++j) {
- // get resources capable of performing given task
- capableResources = s_copy.getCapableResources(tasks_copy[j]);
- // assign the task to random capable resource
- s_copy.assign(tasks_copy[j], capableResources.get((int) (random.nextDouble() * upperBounds[j])));
- //sets gene responsible for that task
- genes[j] = tasks_copy[j].getResourceId();
- System.out.println("Osobnik: " + i + ", gen: " + j + ", pracownik:" + genes[j]);
- }
- //runs greedy for timestamps
- Greedy greedy2 = new Greedy(s_copy.getSuccesors());
- greedy2.buildTimestamps(s_copy);
- System.out.println(validator.validate(s_copy));
- System.out.println(validator.getErrorMessages());
- BaseEvaluator evaluator = new DurationEvaluator(s_copy);
- //creates an individual, based on time-stamped schedule and genotype
- BaseIntIndividual new_random_ind = new BaseIntIndividual(s_copy, genes, evaluator);
- //evaluates duration
- new_random_ind.setDuration();
- System.out.println(new_random_ind.getDuration());
- //add new individual into a start population
- pop.add(new_random_ind);
- }
- System.out.println("Rozmiar populacji pokolenia poczatkowego: " + pop.size());
- //here, minimal, maximal nad avg values for current population is found and written in list
- List<Integer> values = Runner.valuesSearch(pop);
- System.out.println("Najkrotszy: " + values.get(0) + ", najdluzszy: " + values.get(1) + " Srednio: " + values.get(2));
- /*
- * MAIN LOOP
- * here, population including staring one will be touched by selection trough the tournament, crossed over and mutate
- * as long as final generation will come to live
- * */
- int generations = 0;
- while (generations < generation_max) {
- pop = Runner.selectAndCross(pop);
- pop = Runner.mutate(pop);
- // this code below serves as assignment based on chromosomes (genotype table, delivered by BasIntIndividual)
- int numberOfTasks = tasks.length;
- for (BaseIntIndividual p : pop) {
- for (int i = 0; i < numberOfTasks; i++) {
- int gene = p.getGenes()[i];
- //System.out.println("Gen:"+ i +", wartosc:" + gene);
- Resource res = p.getSchedule().getResource(gene);
- p.getSchedule().assign(p.getSchedule().getTasks()[i], res);
- }
- //end of assingment, print info if assigment are not correct
- System.out.println(assign_validator.validate(p.getSchedule()));
- System.out.println(assign_validator.getErrorMessages());
- //avaluation of individuals in new generation
- Greedy greedy3 = new Greedy(p.getSchedule().getSuccesors());
- greedy3.buildTimestamps(p.getSchedule());
- p.setDuration();
- //System.out.println(p.getDuration());
- }
- //gets min, max and avg for this generation and puts onto arrays
- List<Integer> values2 = Runner.valuesSearch(pop);
- avg_min[generations]+= values2.get(0);
- avg_max[generations]+= values2.get(1);
- avg_avg[generations]+= values2.get(2);
- generations++;
- System.out.println("Pokolenie:" + generations);
- System.out.println("Najkrotszy: " + values2.get(0) + ", najdluzszy: " + values2.get(1) + " Srednio: " + values2.get(2));
- }
- }
- try {
- //if FIINALLY genethic algorithm will rach max number of generation, saving mean values of each generation into CSV file
- System.out.println("podaj nazwe");
- String title;
- Scanner odczyt = new Scanner(System.in); //obiekt do odebrania danych od użytkownika
- title = odczyt.nextLine();
- title = title + ".csv";
- FileWriter writer = new FileWriter(title, false);
- BufferedWriter bufferedWriter = new BufferedWriter(writer);
- bufferedWriter.write("Populacja:"+pop_size+";Pokolenia:"+generation_max+";Pr.krzyzowania:"+crossover_probability+";Pr.mutacji:"+mutation_probability+";Rozmiar turnieju:"+challengers);
- bufferedWriter.newLine();
- bufferedWriter.write("Rozwiazanie zachłanne:"+ greedy_ind.getDuration());
- bufferedWriter.newLine();
- bufferedWriter.write("MIN;AVG;MAX");
- bufferedWriter.newLine();
- for (int i = 0; i < generation_max; i++) {
- avg_max[i] /= number_of_runs;
- avg_min[i] /= number_of_runs;
- avg_avg[i] /= number_of_runs;
- bufferedWriter.write(avg_min[i]+";"+avg_avg[i]+";"+avg_max[i]);
- bufferedWriter.newLine();
- }
- bufferedWriter.close();
- } catch(IOException e){
- System.out.println("Blad zapisu");
- }
- }
- //function returns List of MIN, MAX, AVG
- public static List<Integer> valuesSearch(List <? extends BaseIndividual> population)
- {
- int min = population.get(0).getDuration();
- int max = min;
- int sum = 0;
- int avg = 0;
- for (BaseIndividual ind: population
- ) {
- int duration = ind.getDuration();
- if(ind.getDuration() > max) max = duration;
- if(ind.getDuration() < min) min = duration;
- sum += duration;
- }
- avg = sum/pop_size;
- List<Integer> values = new ArrayList<Integer>();
- values.add(min);
- values.add(max);
- values.add(avg);
- return values;
- }
- // here selection and sometimes crossover happens
- public static List<BaseIntIndividual> selectAndCross(List<BaseIntIndividual> old_pop){
- //create new population
- List<BaseIntIndividual> new_pop = new ArrayList<BaseIntIndividual>();
- //Set<Integer> selected = new HashSet<Integer>();
- //Random chance = new Random(System.currentTimeMillis());
- //int numberOfTasks = old_pop.get(0).getGenes().length;
- //new_pop.size() - checks for size of new generation
- while(new_pop.size() < pop_size)
- {
- //tournament ensues - one BaseIntIndividual shall be returned
- BaseIntIndividual new_ind = Runner.tournament(old_pop);
- //check the chance for crossover
- if(new_pop.size()< pop_size-1 && random.nextDouble() < crossover_probability)
- {
- System.out.println("Krzyzowanie");
- //find mating partner for crossover process, but with out genetic twins
- BaseIntIndividual mating_partner = Runner.tournament(old_pop);
- boolean isTheSame = true;
- int numberOfTasks = mating_partner.getGenes().length;
- int patience = pop_size; //for cases if it cannot find correct result for too much time
- while(isTheSame)
- {
- for(int i = 0; i<numberOfTasks && isTheSame;i++)
- {
- isTheSame = (mating_partner.getGenes()[i] == new_ind.getGenes()[i]);
- }
- if (isTheSame)
- System.out.println("Nowe losowanie");
- mating_partner = Runner.tournament(old_pop);
- patience--;
- if(patience == 0) isTheSame = false; // if patienc is over, will put duplicates into the new generation
- }
- Schedule sAB = new Schedule(new_ind.getSchedule());
- Schedule sBA = new Schedule(mating_partner.getSchedule());
- int[] AB = new int[numberOfTasks];
- int[] BA = new int[numberOfTasks];
- BaseEvaluator evaluator = new DurationEvaluator(sAB);
- BaseEvaluator evaluator2 = new DurationEvaluator(sBA);
- System.out.print("Rodzic 1:");
- for (int i = 0; i< numberOfTasks; i++){
- System.out.print(new_ind.getGenes()[i]);
- }
- System.out.println();
- System.out.print("Rodzic 2:");
- for (int i = 0; i< numberOfTasks; i++){
- System.out.print(mating_partner.getGenes()[i]);
- }
- int divide = random.nextInt(numberOfTasks-2)+1;
- System.arraycopy(new_ind.getGenes(),0,AB,0,numberOfTasks);
- System.arraycopy(mating_partner.getGenes(),0,BA,0,numberOfTasks);
- System.arraycopy(new_ind.getGenes(),0,BA,0,divide);
- System.arraycopy(mating_partner.getGenes(),0,AB,0,divide);
- //stwórz nowe osobniki i wrzuć do nowego pokolenia
- System.out.println();
- System.out.print("Dziecko1:");
- for (int i = 0; i< numberOfTasks; i++){
- System.out.print(AB[i]);
- }
- System.out.println();
- System.out.print("Dziecko2:");
- for (int i = 0; i< numberOfTasks; i++){
- System.out.print(BA[i]);
- }
- BaseIntIndividual offspring1 = new BaseIntIndividual(sAB,AB,evaluator);
- BaseIntIndividual offspring2 = new BaseIntIndividual(sBA,BA,evaluator2);
- new_pop.add(offspring1);
- new_pop.add(offspring2);
- }
- else{
- //BaseEvaluator evaluator = new DurationEvaluator(new_ind.getSchedule());
- //BaseIntIndividual copy = new BaseIntIndividual(new_ind.getSchedule(), new_ind.getGenes(), evaluator);
- //new_pop.add(copy);
- //if(!new_pop.contains(new_ind)){
- new_pop.add(new_ind);
- //}
- //else System.out.println("Duplikat");
- }
- System.out.println("Rozmiar nowej populacji"+new_pop.size());
- }
- System.out.println("Populacja pokolenia:"+ new_pop.size());
- return new_pop;
- }
- //here tournament happens
- public static BaseIntIndividual tournament (List <BaseIntIndividual> pop)
- {
- List<BaseIntIndividual> chevaliers = new ArrayList<BaseIntIndividual>();
- Set<Integer> selectedPos = new HashSet<Integer>();
- //Random generator = new Random(System.currentTimeMillis());
- BaseIntIndividual winner = null;
- while(chevaliers.size() != challengers)
- {
- int selection = random.nextInt(pop_size);
- if(!selectedPos.contains(selection)){
- BaseIntIndividual challenger = pop.get(selection);
- chevaliers.add(challenger);
- selectedPos.add(selection);
- }
- }
- boolean isFound = false;
- for (int i = 0; i < challengers && !isFound ; i++){
- isFound = chevaliers.get(i).dominates(chevaliers);
- if (isFound)
- {
- winner = chevaliers.get(i);
- }
- }
- return winner;
- }
- public static List<BaseIntIndividual> mutate(List <BaseIntIndividual> pop)
- {
- int numberOfTasks = pop.get(0).getGenes().length;
- for (BaseIntIndividual ind: pop) {
- for(int i = 0; i<numberOfTasks; i++){
- //double mutator = random.nextDouble();
- //System.out.println(mutator);
- if(random.nextDouble() < mutation_probability)
- {
- System.out.println("Mutacja");
- List<Resource> capable = ind.getSchedule().getCapableResources(ind.getSchedule().getTasks()[i]);
- int choice = random.nextInt(capable.size());
- int[] genes = ind.getGenes();
- System.out.print("Pozycja:"+i+"gen:"+genes[i]);
- genes[i] = capable.get(choice).getId();
- System.out.println("->"+genes[i]);
- ind.setGenes(genes);
- }
- }
- }
- return pop;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement