Advertisement
Guest User

sidziwki

a guest
Mar 23rd, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 16.41 KB | None | 0 0
  1. import com.sun.org.apache.xpath.internal.SourceTree;
  2. import msrcpsp.evaluation.BaseEvaluator;
  3. import msrcpsp.evaluation.DurationEvaluator;
  4. import msrcpsp.io.MSRCPSPIO;
  5. import msrcpsp.scheduling.*;
  6. import msrcpsp.scheduling.greedy.Greedy;
  7. import msrcpsp.validation.AssignmentValidator;
  8. import msrcpsp.validation.BaseValidator;
  9. import msrcpsp.validation.CompleteValidator;
  10.  
  11. import java.io.BufferedWriter;
  12. import java.io.FileWriter;
  13. import java.io.IOException;
  14. import java.io.PrintWriter;
  15. import java.util.*;
  16. import java.util.logging.Level;
  17. import java.util.logging.Logger;
  18.  
  19. /**
  20.  * Runner class to help with understanding of the library.
  21.  */
  22. public class Runner {
  23.  
  24.   private static final Logger LOGGER = Logger.getLogger( Runner.class.getName() );
  25.   private static final String definitionFile = "assets/def_small/100_10_26_15.def";
  26.   private static final String writeFile = "assets/solutions_small/100_10_26_15.sol";
  27.     //params for Genetic Algorithm
  28.   private static final int pop_size = 100;
  29.     private static final int generation_max = 100;
  30.     private static final double crossover_probability = 0;
  31.     private static final double mutation_probability = 0.05;
  32.     private static final int challengers = 3;
  33.     public static final int number_of_runs = 1;
  34.  
  35.     private static final Random random = new Random(System.currentTimeMillis());
  36.  
  37.     //these arrays must have lenght of generation_max, these arrayse serve for statistical averaging
  38.     private static final int[] avg_max = new int[generation_max];
  39.     private static final int[] avg_avg = new int[generation_max];
  40.     private static final int[] avg_min = new int[generation_max];
  41.  
  42.  
  43.   public static void main(String[] args) {
  44.  
  45.  
  46.  
  47.     //int pop_size = 100;
  48.  
  49.  
  50.  
  51.     //our population
  52.  
  53.  
  54.     // read definition file into Schedule object
  55.     MSRCPSPIO reader = new MSRCPSPIO();
  56.  
  57.     Schedule schedule_orig = reader.readDefinition(definitionFile);
  58.     if (null == schedule_orig) {
  59.       LOGGER.log(Level.WARNING, "Could not read the Definition " + definitionFile);
  60.     }
  61.  
  62.     //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
  63.  
  64.     Schedule schedule_greedy = new Schedule(schedule_orig);
  65.     Greedy greedy_comp = new Greedy(schedule_greedy.getSuccesors());
  66.     greedy_comp.buildAssignments(schedule_greedy);
  67.     greedy_comp.buildTimestamps(schedule_greedy);
  68.     BaseEvaluator greedy_eval = new DurationEvaluator(schedule_greedy);
  69.     BaseIndividual greedy_ind = new BaseIndividual(schedule_greedy,greedy_eval);
  70.     greedy_ind.setDuration();
  71.  
  72.     //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
  73.  
  74.     for (int run = 0; run < number_of_runs; run++) {
  75.  
  76.         List<BaseIntIndividual> pop = new ArrayList<BaseIntIndividual>();
  77.         //copying original schedule (or rather set of Tasks ans Resources) for this run
  78.         Schedule schedule = new Schedule(schedule_orig);
  79.  
  80.  
  81.         // get array of upper bounds of each task assignment, that does
  82.         // violate skill constraint
  83.         int[] upperBounds = schedule.getUpperBounds(schedule.getTasks().length);
  84.         // create an evaluator
  85.         //BaseEvaluator evaluator = new DurationEvaluator(schedule);
  86.         //table of tasks
  87.  
  88.         Task[] tasks = schedule.getTasks();
  89.         //Resource[] resources = schedule.getResources();
  90.  
  91.  
  92.         // create greedy algorithm to set timestamps
  93.         Greedy greedy = new Greedy(schedule.getSuccesors());
  94.  
  95.  
  96.         // create validators
  97.         BaseValidator validator = new CompleteValidator();
  98.         BaseValidator assign_validator = new AssignmentValidator();
  99.         //System.out.println(validator.validate(schedule));
  100.         //System.out.println(validator.getErrorMessages());
  101.  
  102.         //generation of start population
  103.         for (int i = 0; i < pop_size; i++)
  104.  
  105.         {
  106.             //prepare genotype table (chromosomes)
  107.             int[] genes = new int[tasks.length];
  108.             //clones schedule for new individual
  109.             Schedule s_copy = new Schedule(schedule);
  110.             Task[] tasks_copy = s_copy.getTasks();
  111.  
  112.             // create schedule randomly, while keeping constraints
  113.             //Random random = new Random(System.currentTimeMillis());
  114.             List<Resource> capableResources;
  115.             for (int j = 0; j < tasks.length; ++j) {
  116.                 // get resources capable of performing given task
  117.                 capableResources = s_copy.getCapableResources(tasks_copy[j]);
  118.                 // assign the task to random capable resource
  119.                 s_copy.assign(tasks_copy[j], capableResources.get((int) (random.nextDouble() * upperBounds[j])));
  120.                 //sets gene responsible for that task
  121.                 genes[j] = tasks_copy[j].getResourceId();
  122.                 System.out.println("Osobnik: " + i + ", gen: " + j + ", pracownik:" + genes[j]);
  123.             }
  124.  
  125.             //runs greedy for timestamps
  126.             Greedy greedy2 = new Greedy(s_copy.getSuccesors());
  127.             greedy2.buildTimestamps(s_copy);
  128.             System.out.println(validator.validate(s_copy));
  129.             System.out.println(validator.getErrorMessages());
  130.             BaseEvaluator evaluator = new DurationEvaluator(s_copy);
  131.             //creates an individual, based on time-stamped schedule and genotype
  132.             BaseIntIndividual new_random_ind = new BaseIntIndividual(s_copy, genes, evaluator);
  133.             //evaluates duration
  134.             new_random_ind.setDuration();
  135.             System.out.println(new_random_ind.getDuration());
  136.             //add new individual into a start population
  137.             pop.add(new_random_ind);
  138.  
  139.  
  140.         }
  141.  
  142.         System.out.println("Rozmiar populacji pokolenia poczatkowego: " + pop.size());
  143.         //here, minimal, maximal nad avg values for current population is found and written in list
  144.         List<Integer> values = Runner.valuesSearch(pop);
  145.         System.out.println("Najkrotszy: " + values.get(0) + ", najdluzszy: " + values.get(1) + " Srednio: " + values.get(2));
  146.  
  147.         /*
  148.         * MAIN LOOP
  149.         * here, population including staring one will be touched by selection trough the tournament, crossed over and mutate
  150.         * as long as final generation will come to live
  151.         * */
  152.  
  153.  
  154.         int generations = 0;
  155.  
  156.         while (generations < generation_max) {
  157.             pop = Runner.selectAndCross(pop);
  158.             pop = Runner.mutate(pop);
  159.  
  160.             // this code below serves as assignment based on chromosomes (genotype table, delivered by BasIntIndividual)
  161.             int numberOfTasks = tasks.length;
  162.  
  163.             for (BaseIntIndividual p : pop) {
  164.  
  165.  
  166.                 for (int i = 0; i < numberOfTasks; i++) {
  167.                     int gene = p.getGenes()[i];
  168.                     //System.out.println("Gen:"+ i +", wartosc:" + gene);
  169.                     Resource res = p.getSchedule().getResource(gene);
  170.                     p.getSchedule().assign(p.getSchedule().getTasks()[i], res);
  171.  
  172.                 }
  173.  
  174.                 //end of assingment, print info if assigment are not correct
  175.  
  176.                 System.out.println(assign_validator.validate(p.getSchedule()));
  177.                 System.out.println(assign_validator.getErrorMessages());
  178.                 //avaluation of individuals in new generation
  179.                 Greedy greedy3 = new Greedy(p.getSchedule().getSuccesors());
  180.                 greedy3.buildTimestamps(p.getSchedule());
  181.                 p.setDuration();
  182.                 //System.out.println(p.getDuration());
  183.  
  184.             }
  185.  
  186.             //gets min, max and avg for this generation and puts onto arrays
  187.  
  188.             List<Integer> values2 = Runner.valuesSearch(pop);
  189.             avg_min[generations]+= values2.get(0);
  190.             avg_max[generations]+= values2.get(1);
  191.             avg_avg[generations]+= values2.get(2);
  192.             generations++;
  193.  
  194.             System.out.println("Pokolenie:" + generations);
  195.             System.out.println("Najkrotszy: " + values2.get(0) + ", najdluzszy: " + values2.get(1) + " Srednio: " + values2.get(2));
  196.  
  197.         }
  198.  
  199.  
  200.  
  201.     }
  202.  
  203.     try {
  204.  
  205.         //if FIINALLY genethic algorithm will rach max number of generation, saving mean values of each generation into CSV file
  206.  
  207.         System.out.println("podaj nazwe");
  208.  
  209.         String title;
  210.         Scanner odczyt = new Scanner(System.in); //obiekt do odebrania danych od użytkownika
  211.  
  212.         title = odczyt.nextLine();
  213.         title = title + ".csv";
  214.  
  215.         FileWriter writer = new FileWriter(title, false);
  216.         BufferedWriter bufferedWriter = new BufferedWriter(writer);
  217.  
  218.         bufferedWriter.write("Populacja:"+pop_size+";Pokolenia:"+generation_max+";Pr.krzyzowania:"+crossover_probability+";Pr.mutacji:"+mutation_probability+";Rozmiar turnieju:"+challengers);
  219.         bufferedWriter.newLine();
  220.         bufferedWriter.write("Rozwiazanie zachłanne:"+ greedy_ind.getDuration());
  221.         bufferedWriter.newLine();
  222.         bufferedWriter.write("MIN;AVG;MAX");
  223.         bufferedWriter.newLine();
  224.  
  225.         for (int i = 0; i < generation_max; i++) {
  226.             avg_max[i] /= number_of_runs;
  227.             avg_min[i] /= number_of_runs;
  228.             avg_avg[i] /= number_of_runs;
  229.  
  230.             bufferedWriter.write(avg_min[i]+";"+avg_avg[i]+";"+avg_max[i]);
  231.             bufferedWriter.newLine();
  232.  
  233.  
  234.         }
  235.  
  236.  
  237.  
  238.         bufferedWriter.close();
  239.  
  240.  
  241.     } catch(IOException e){
  242.         System.out.println("Blad zapisu");
  243.     }
  244.  
  245.   }
  246. //function returns List of MIN, MAX, AVG
  247.   public static List<Integer> valuesSearch(List <? extends BaseIndividual> population)
  248.   {
  249.     int min = population.get(0).getDuration();
  250.     int max = min;
  251.     int sum = 0;
  252.     int avg = 0;
  253.  
  254.     for (BaseIndividual ind: population
  255.          ) {
  256.           int duration = ind.getDuration();
  257.         if(ind.getDuration() > max) max = duration;
  258.         if(ind.getDuration() < min) min = duration;
  259.         sum += duration;
  260.  
  261.     }
  262.  
  263.     avg = sum/pop_size;
  264.  
  265.     List<Integer> values = new ArrayList<Integer>();
  266.     values.add(min);
  267.     values.add(max);
  268.     values.add(avg);
  269.  
  270.     return values;
  271.   }
  272.  
  273.   // here selection and sometimes crossover happens
  274.  
  275.   public static List<BaseIntIndividual> selectAndCross(List<BaseIntIndividual> old_pop){
  276.  
  277.       //create new population
  278.  
  279.       List<BaseIntIndividual> new_pop = new ArrayList<BaseIntIndividual>();
  280.       //Set<Integer> selected = new HashSet<Integer>();
  281.       //Random chance = new Random(System.currentTimeMillis());
  282.       //int numberOfTasks = old_pop.get(0).getGenes().length;
  283.  
  284.       //new_pop.size() - checks for size of new generation
  285.  
  286.       while(new_pop.size() < pop_size)
  287.       {
  288.           //tournament ensues - one BaseIntIndividual shall be returned
  289.           BaseIntIndividual new_ind = Runner.tournament(old_pop);
  290.  
  291.  
  292.  
  293.           //check the chance for crossover
  294.  
  295.           if(new_pop.size()< pop_size-1 && random.nextDouble() < crossover_probability)
  296.           {
  297.               System.out.println("Krzyzowanie");
  298.               //find mating partner for crossover process, but with out genetic twins
  299.               BaseIntIndividual mating_partner = Runner.tournament(old_pop);
  300.               boolean isTheSame = true;
  301.               int numberOfTasks = mating_partner.getGenes().length;
  302.               int patience = pop_size; //for cases if it cannot find correct result for too much time
  303.  
  304.               while(isTheSame)
  305.               {
  306.                   for(int i = 0; i<numberOfTasks && isTheSame;i++)
  307.                   {
  308.                       isTheSame = (mating_partner.getGenes()[i] == new_ind.getGenes()[i]);
  309.  
  310.                   }
  311.                   if (isTheSame)
  312.                       System.out.println("Nowe losowanie");
  313.                   mating_partner = Runner.tournament(old_pop);
  314.                   patience--;
  315.                   if(patience == 0) isTheSame = false; // if patienc is over, will put duplicates into the new generation
  316.  
  317.               }
  318.  
  319.  
  320.  
  321.               Schedule sAB = new Schedule(new_ind.getSchedule());
  322.               Schedule sBA = new Schedule(mating_partner.getSchedule());
  323.  
  324.               int[] AB = new int[numberOfTasks];
  325.               int[] BA = new int[numberOfTasks];
  326.  
  327.               BaseEvaluator evaluator = new DurationEvaluator(sAB);
  328.               BaseEvaluator evaluator2 = new DurationEvaluator(sBA);
  329.  
  330.  
  331.  
  332.               System.out.print("Rodzic 1:");
  333.               for (int i = 0; i< numberOfTasks; i++){
  334.                   System.out.print(new_ind.getGenes()[i]);
  335.               }
  336.  
  337.               System.out.println();
  338.               System.out.print("Rodzic 2:");
  339.               for (int i = 0; i< numberOfTasks; i++){
  340.                   System.out.print(mating_partner.getGenes()[i]);
  341.               }
  342.  
  343.               int divide = random.nextInt(numberOfTasks-2)+1;
  344.  
  345.  
  346.               System.arraycopy(new_ind.getGenes(),0,AB,0,numberOfTasks);
  347.               System.arraycopy(mating_partner.getGenes(),0,BA,0,numberOfTasks);
  348.  
  349.  
  350.  
  351.               System.arraycopy(new_ind.getGenes(),0,BA,0,divide);
  352.               System.arraycopy(mating_partner.getGenes(),0,AB,0,divide);
  353.  
  354.               //stwórz nowe osobniki i wrzuć do nowego pokolenia
  355.               System.out.println();
  356.  
  357.               System.out.print("Dziecko1:");
  358.               for (int i = 0; i< numberOfTasks; i++){
  359.                   System.out.print(AB[i]);
  360.               }
  361.  
  362.               System.out.println();
  363.               System.out.print("Dziecko2:");
  364.               for (int i = 0; i< numberOfTasks; i++){
  365.                   System.out.print(BA[i]);
  366.               }
  367.  
  368.  
  369.  
  370.               BaseIntIndividual offspring1 = new BaseIntIndividual(sAB,AB,evaluator);
  371.               BaseIntIndividual offspring2 = new BaseIntIndividual(sBA,BA,evaluator2);
  372.  
  373.               new_pop.add(offspring1);
  374.               new_pop.add(offspring2);
  375.  
  376.  
  377.  
  378.           }
  379.           else{
  380.  
  381.               //BaseEvaluator evaluator = new DurationEvaluator(new_ind.getSchedule());
  382.               //BaseIntIndividual copy = new BaseIntIndividual(new_ind.getSchedule(), new_ind.getGenes(), evaluator);
  383.               //new_pop.add(copy);
  384.  
  385.               //if(!new_pop.contains(new_ind)){
  386.                   new_pop.add(new_ind);
  387.  
  388.               //}
  389.  
  390.  
  391.  
  392.               //else System.out.println("Duplikat");
  393.  
  394.  
  395.           }
  396.  
  397.           System.out.println("Rozmiar nowej populacji"+new_pop.size());
  398.  
  399.  
  400.  
  401.       }
  402.  
  403.       System.out.println("Populacja pokolenia:"+ new_pop.size());
  404.  
  405.      return new_pop;
  406.   }
  407.  
  408.   //here tournament happens
  409.  
  410.   public static BaseIntIndividual tournament (List <BaseIntIndividual> pop)
  411.   {
  412.       List<BaseIntIndividual> chevaliers = new ArrayList<BaseIntIndividual>();
  413.       Set<Integer> selectedPos = new HashSet<Integer>();
  414.       //Random generator = new Random(System.currentTimeMillis());
  415.       BaseIntIndividual winner = null;
  416.       while(chevaliers.size() != challengers)
  417.       {
  418.           int selection = random.nextInt(pop_size);
  419.           if(!selectedPos.contains(selection)){
  420.  
  421.               BaseIntIndividual challenger = pop.get(selection);
  422.               chevaliers.add(challenger);
  423.               selectedPos.add(selection);
  424.           }
  425.       }
  426.  
  427.       boolean isFound = false;
  428.  
  429.       for (int i = 0; i < challengers && !isFound ; i++){
  430.           isFound = chevaliers.get(i).dominates(chevaliers);
  431.           if (isFound)
  432.           {
  433.               winner = chevaliers.get(i);
  434.           }
  435.  
  436.       }
  437.  
  438.       return winner;
  439.  
  440.  
  441.   }
  442.  
  443.   public static List<BaseIntIndividual> mutate(List <BaseIntIndividual> pop)
  444.   {
  445.  
  446.  
  447.       int numberOfTasks = pop.get(0).getGenes().length;
  448.  
  449.       for (BaseIntIndividual ind: pop) {
  450.           for(int i = 0; i<numberOfTasks; i++){
  451.               //double mutator = random.nextDouble();
  452.               //System.out.println(mutator);
  453.               if(random.nextDouble() < mutation_probability)
  454.               {
  455.                   System.out.println("Mutacja");
  456.                   List<Resource> capable = ind.getSchedule().getCapableResources(ind.getSchedule().getTasks()[i]);
  457.                   int choice = random.nextInt(capable.size());
  458.  
  459.                   int[] genes = ind.getGenes();
  460.                   System.out.print("Pozycja:"+i+"gen:"+genes[i]);
  461.                   genes[i] = capable.get(choice).getId();
  462.                   System.out.println("->"+genes[i]);
  463.                   ind.setGenes(genes);
  464.  
  465.               }
  466.  
  467.           }
  468.  
  469.       }
  470.  
  471.       return pop;
  472.  
  473.   }
  474.  
  475. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement