repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/CoEvolve.java | package lu.uni.svv.PriorityAssignment;
import java.io.FileNotFoundException;
import java.lang.reflect.Constructor;
import java.util.*;
import java.util.logging.Level;
import lu.uni.svv.PriorityAssignment.priority.search.PriorityNSGAII;
import lu.uni.svv.PriorityAssignment.priority.search.PriorityRandom;
import lu.uni.svv.PriorityAssignment.utils.Monitor;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.operator.impl.selection.BinaryTournamentSelection;
import org.uma.jmetal.util.AlgorithmRunner;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.comparator.ObjectiveComparator;
import org.uma.jmetal.util.comparator.ObjectiveComparator.Ordering;
import org.uma.jmetal.util.comparator.RankingAndCrowdingDistanceComparator;
import lu.uni.svv.PriorityAssignment.arrivals.*;
import lu.uni.svv.PriorityAssignment.priority.*;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
public class CoEvolve {
// exchange variables
Map<String, Object> best = null;
public CoEvolve(){
}
public void run(TaskDescriptor[] input, int maxCycle, int simulationTime, Integer[] priorityEngineer, List<Arrivals[]> testArrivals) throws Exception {
Monitor.init();
JMetalLogger.logger.info("Start co-evolution");
// Execute iterative approach (1 cycle == phase1 + phase2)
int cycle = 0;
//Step 0. Generate initial populations
List<ArrivalsSolution> A = null; // populationA will be generated in a SSGA
PriorityProblem problemP = null;
List<PrioritySolution> P = null;
problemP = new PriorityProblem(input, simulationTime, Settings.SCHEDULER);
P = createInitialPriorities(Settings.P2_POPULATION, priorityEngineer, problemP);
GAWriter internalWriter = null;
if(Settings.PRINT_INTERNAL_FITNESS) {
internalWriter = new GAWriter("_arrivalsInternal/arrivals.list", Level.FINE, null);
internalWriter.info("Cycle\tIndex\tArrivalJSON");
}
do{
cycle++;
// Step1. [Phase 1] Find a set of worst case arrival times
List<Integer[]> priorities = PrioritySolution.toArrays(P);
ArrivalProblem problemA = new ArrivalProblem(input, priorities, simulationTime, Settings.SCHEDULER);
A = this.searchArrivals(problemA, cycle, A);
if(Settings.PRINT_INTERNAL_FITNESS) saveArrivals(internalWriter, A, cycle);
// Step2. [Phase 2] find the best pareto front of priority assignment
List<Arrivals[]> arrivals = ArrivalsSolution.toArrays(A);
PrioritySolutionEvaluator evaluator = new PrioritySolutionEvaluator(arrivals, testArrivals);
P = this.searchPriorities(problemP, evaluator, cycle, P); // update bestSolutions inside
// test
// for (int x=0; x<P.size(); x++)
// System.out.println("Priorities"+(x+1)+": " + P.get(x).getVariablesString());
}while(cycle < maxCycle);
if(Settings.PRINT_INTERNAL_FITNESS) internalWriter.close();
Monitor.finish();
saveResults();
JMetalLogger.logger.info("Finished all search process.");
}
/**
*
* @param _problem
* @param _cycle
* @return
*/
private List<ArrivalsSolution> searchArrivals(ArrivalProblem _problem, int _cycle, List<ArrivalsSolution> _initial)
{
String runMsg = (Settings.RUN_NUM==0)?"": "[Run"+ Settings.RUN_NUM + "] ";
JMetalLogger.logger.info(runMsg+ "Search worst-case arrival times (Phase1) cycle "+_cycle);
// Define operators
CrossoverOperator<ArrivalsSolution> crossoverOperator;
MutationOperator<ArrivalsSolution> mutationOperator;
SelectionOperator<List<ArrivalsSolution>, ArrivalsSolution> selectionOperator;
Comparator<ArrivalsSolution> comparator;
// Generate operators
List<Integer> possibleTasks = TaskDescriptor.getVaryingTasks(_problem.Tasks);
crossoverOperator = new OnePointCrossover(possibleTasks, Settings.P1_CROSSOVER_PROB);
mutationOperator = new RandomTLMutation(possibleTasks, _problem, Settings.P1_MUTATION_PROB);
selectionOperator = new BinaryTournamentSelection<>();
comparator = new ObjectiveComparator<>(0, Ordering.DESCENDING);
AbstractArrivalGA algorithm = null;
try {
// Find algorithm class
String packageName = this.getClass().getPackage().getName();
Class algorithmClass = Class.forName(packageName + ".arrivals.search." + Settings.P1_ALGORITHM);
// make algorithm instance
Constructor constructor = algorithmClass.getConstructors()[0];
Object[] parameters = {_cycle, _initial, _problem,
Settings.P1_ITERATION, Settings.P1_POPULATION,
crossoverOperator, mutationOperator, selectionOperator, comparator};
algorithm = (AbstractArrivalGA)constructor.newInstance(parameters);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
// execute algorithm in thread
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm).execute();
// Get result and print
// saveArrivals(algorithm.getPopulation(), _cycle);
// logging some information
System.gc();
return algorithm.getPopulation();
}
/**
*
* @param _problem
* @param _evaluator
* @param _cycle
* @return
* @throws JMetalException
* @throws FileNotFoundException
*/
public List<PrioritySolution> searchPriorities(PriorityProblem _problem, PrioritySolutionEvaluator _evaluator, int _cycle, List<PrioritySolution> _initial) throws JMetalException, FileNotFoundException {
String runMsg = (Settings.RUN_NUM==0)?"": "[Run"+ Settings.RUN_NUM + "] ";
JMetalLogger.logger.info(runMsg+ "Search Optimal Priority (Phase2) cycle "+_cycle);
// define operators
CrossoverOperator<PrioritySolution> crossover;
MutationOperator<PrioritySolution> mutation;
SelectionOperator<List<PrioritySolution>, PrioritySolution> selection;
crossover = new PMXCrossover(Settings.P2_CROSSOVER_PROB);
mutation = new SwapMutation(Settings.P2_MUTATION_PROB);
selection = new BinaryTournamentSelection<>(new RankingAndCrowdingDistanceComparator<>());
// Define algorithm
AbstractPrioritySearch algorithm = null;
if (Settings.P2_SIMPLE_SEARCH){
algorithm = new PriorityRandom(
_cycle, _initial, best, _problem,
Settings.P2_ITERATIONS, Settings.P2_POPULATION, Settings.P2_POPULATION, Settings.P2_POPULATION,
crossover, mutation, selection, _evaluator);
}
else{
algorithm = new PriorityNSGAII(
_cycle, _initial, best, _problem,
Settings.P2_ITERATIONS, Settings.P2_POPULATION, Settings.P2_POPULATION, Settings.P2_POPULATION,
crossover, mutation, selection, _evaluator);
}
// execute algorithm in thread
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm).execute();
// print results
// List<PrioritySolution> population = algorithm.getResult();
// savePriorities(population, _cycle);
System.gc();
best = algorithm.getBest();
return algorithm.getPopulation();
}
/**
* Create initial priority assignments
* @param maxPopulation
* @param priorityEngineer
* @param problem
* @return
*/
public List<PrioritySolution> createInitialPriorities(int maxPopulation, Integer[] priorityEngineer, PriorityProblem problem) {
List<PrioritySolution> population = new ArrayList<>(maxPopulation);
PrioritySolution individual;
for (int i = 0; i < maxPopulation; i++) {
if (i==0 && priorityEngineer!=null){
individual = new PrioritySolution(problem, priorityEngineer);
}
else {
individual = new PrioritySolution(problem);
}
population.add(individual);
}
return population;
}
/**
* Print out to file for arrival times
* @param _solutions
* @param _cycle
*/
private void saveArrivals(GAWriter writer, List<ArrivalsSolution> _solutions, int _cycle)
{
// if (_cycle!=Settings.CYCLE_NUM) return ;
JMetalLogger.logger.info("Saving arrival times in cycle "+(_cycle)+"...");
for(int idx=0; idx<_solutions.size(); idx++) {
String line = _solutions.get(idx).getVariablesStringInline();
writer.write(String.format("%d\t%d\t", _cycle, idx));
writer.write(line);
writer.write("\n");
}
JMetalLogger.logger.info("Saving population...Done");
}
/**
* Print out to file for arrival times
* @param _solutions
*/
private void saveTestArrivals(ArrivalProblem problem, List<ArrivalsSolution> _solutions) throws Exception {
JMetalLogger.logger.info("Saving samples...");
SampleGenerator gen = new SampleGenerator(problem);
gen.initWriter();
for(int idx=0; idx<_solutions.size(); idx++) {
gen.appendLine(_solutions.get(idx), idx);
}
gen.closeWriter();
JMetalLogger.logger.info("Saved arrival times for test data");
}
/**
* Print out to file for priorities
* @param _population
* @param _cycle
*/
private void savePriorities(List<PrioritySolution> _population, int _cycle)
{
JMetalLogger.logger.info("Saving priority assignments in cycle "+(_cycle)+"...");
// print results
for (int idx=0; idx < _population.size(); idx++) {
_population.get(idx).store(String.format("_priorities/priorities_cycle%2d_%02d.json", _cycle, idx));
}
JMetalLogger.logger.info("Saving population...Done");
}
/**
* Print out all results (best pareto, last population, time information, memory information..)
*/
private void saveResults()
{
List<PrioritySolution> pareto = (List<PrioritySolution>)best.get("Pareto");
if (pareto.size()==0) return;
double dist = (Double)best.get("Distance");
int iter = (Integer)this.best.get("Iteration");
int cycle = (Integer)best.get("Cycle");
JMetalLogger.logger.info("Saving best pareto priority assignments...");
// print results
GAWriter writer = new GAWriter("_best_pareto.list", Level.FINE, null);
writer.info("Index\tPriorityJSON");
for (int idx=0; idx < pareto.size(); idx++) {
writer.write(String.format("%d\t", idx));
writer.write(pareto.get(idx).getVariablesString());
writer.write("\n");
}
writer.close();
// print population results
List<PrioritySolution> population = (List<PrioritySolution>)best.get("Population");
JMetalLogger.logger.info("Saving population of priority assignments...");
writer = new GAWriter("_last_population.list", Level.FINE, null);
writer.info("Index\tPriorityJSON");
for (int idx=0; idx < population.size(); idx++) {
writer.write(String.format("%d\t", idx));
writer.write(population.get(idx).getVariablesString());
writer.write("\n");
}
writer = new GAWriter(String.format("_result.txt"), Level.FINE, null);
writer.info("Cycle: "+ cycle);
writer.info("bestDistance: "+ dist);
writer.info("bestIteration: "+ iter);
long all = Monitor.getTime();
long evP1 = Monitor.getTime("evaluateP1");
long evP2 = Monitor.getTime("evaluateP2");
long evP2Ex = Monitor.getTime("external");
long searchTime = all-evP1-evP2-evP2Ex;
writer.info(String.format("TotalExecutionTime( s): %.3f",all/1000.0));
writer.info(String.format("SearchTime(s): %.3f",(searchTime)/1000.0));
writer.info(String.format("EvaluationTimeP1(s): %.3f",evP1/1000.0));
writer.info(String.format("EvaluationTimeP2(s): %.3f",evP2/1000.0));
writer.info(String.format("EvaluationTimeEx(s): %.3f",evP2Ex/1000.0));
writer.info(String.format("InitHeap: %.1fM (%.1fG)", Monitor.heapInit/Monitor.MB, Monitor.heapInit/Monitor.GB));
writer.info(String.format("usedHeap: %.1fM (%.1fG)", Monitor.heapUsed/Monitor.MB, Monitor.heapUsed/Monitor.GB));
writer.info(String.format("commitHeap: %.1fM (%.1fG)", Monitor.heapCommit/Monitor.MB, Monitor.heapCommit/Monitor.GB));
writer.info(String.format("MaxHeap: %.1fM (%.1fG)", Monitor.heapMax/Monitor.MB, Monitor.heapMax/Monitor.GB));
writer.info(String.format("MaxNonHeap: %.1fM (%.1fG)", Monitor.nonheapUsed/Monitor.MB, Monitor.nonheapUsed/Monitor.GB));
writer.close();
JMetalLogger.logger.info("Saving population...Done");
}
}
| 11,963 | 36.271028 | 204 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/NSGA.java | package lu.uni.svv.PriorityAssignment;
import lu.uni.svv.PriorityAssignment.arrivals.Arrivals;
import lu.uni.svv.PriorityAssignment.arrivals.ArrivalsSolution;
import lu.uni.svv.PriorityAssignment.priority.*;
import lu.uni.svv.PriorityAssignment.priority.search.PriorityNSGAII;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.utils.FileManager;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Monitor;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.operator.impl.selection.BinaryTournamentSelection;
import org.uma.jmetal.util.AlgorithmRunner;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.comparator.RankingAndCrowdingDistanceComparator;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
public class NSGA {
/**
* Main code to start co-evolution
* - initialize parameters
* - initialize global objects
* @param args
* @throws Exception
*/
public static void main( String[] args ) throws Exception {
// Environment Settings
Initializer.initLogger();
Settings.update(args);
// load input
TaskDescriptor[] input = TaskDescriptor.loadFromCSV(Settings.INPUT_FILE, Settings.TIME_MAX, Settings.TIME_QUANTA);
// update dynamic settings
Initializer.updateSettings(input);
// convert settings' time unit
Initializer.convertTimeUnit(Settings.TIME_QUANTA);
// make simulation time
int simulationTime = (int) Settings.TIME_MAX;
if (Settings.ADDITIONAL_SIMULATION_TIME != 0) {
simulationTime += Settings.ADDITIONAL_SIMULATION_TIME;
}
// create engineer's priority assignment
Integer[] prioritiy = null;
if (!Settings.RANDOM_PRIORITY) {
prioritiy = getPrioritiesFromInput(input);
}
List<Arrivals[]> testArrivals = FileManager.LoadTestArrivals(Settings.TEST_PATH, input, simulationTime, Settings.NUM_TEST);
// save input and settings
GAWriter.init(null, true);
printInput(TaskDescriptor.toString(input, Settings.TIME_QUANTA));
// initialze static objects
ArrivalsSolution.initUUID();
PrioritySolution.initUUID();
AbstractPrioritySearch.init();
// Run Co-Evolution
NSGA system = new NSGA();
List<PrioritySolution> best = system.run(input, simulationTime, prioritiy, testArrivals);
}
/**
* printing input and setting to the result folder to distinguish real
* @param inputs
*/
private static void printInput(String inputs){
String settingStr = Settings.getString();
System.out.print(settingStr);
// print current settings
GAWriter writer = new GAWriter("settings.txt", Level.FINE, null);
writer.info(settingStr);
writer.close();
// print original input
writer = new GAWriter("input.csv", Level.INFO, null);
writer.info(inputs);
writer.close();
}
public List<PrioritySolution> run(TaskDescriptor[] input, int simulationTime, Integer[] priorityEngineer, List<Arrivals[]> arrivals) throws Exception, JMetalException, FileNotFoundException{
Monitor.init();
JMetalLogger.logger.info("Start only NAGA-II appraoch");
// generate initial objects
PriorityProblem problem = new PriorityProblem(input, simulationTime, Settings.SCHEDULER);
List<PrioritySolution> P = this.createInitialPriorities(Settings.P2_POPULATION, priorityEngineer, problem);
PrioritySolutionEvaluator evaluator = new PrioritySolutionEvaluator(arrivals, null);
String runMsg = (Settings.RUN_NUM==0)?"": "[Run"+ Settings.RUN_NUM + "] ";
JMetalLogger.logger.info(runMsg+ "Search Optimal Priority");
// define operators
CrossoverOperator<PrioritySolution> crossover;
MutationOperator<PrioritySolution> mutation;
SelectionOperator<List<PrioritySolution>, PrioritySolution> selection;
crossover = new PMXCrossover(Settings.P2_CROSSOVER_PROB);
mutation = new SwapMutation(Settings.P2_MUTATION_PROB);
selection = new BinaryTournamentSelection<>(new RankingAndCrowdingDistanceComparator<>());
// Define algorithm
PriorityNSGAII algorithm = new PriorityNSGAII(
0, // Priority NSGA-II does not evaluate with external fitness
P, null, problem,
Settings.P2_ITERATIONS, Settings.P2_POPULATION, Settings.P2_POPULATION, Settings.P2_POPULATION,
crossover, mutation, selection, evaluator);
// execute algorithm in thread
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm).execute();
Monitor.finish();
System.gc();
// return with result
List<PrioritySolution> pop = algorithm.getPopulation();
List<PrioritySolution> best = algorithm.getResult();
saveResults(pop, best);
JMetalLogger.logger.info("Finished NSGA search process.");
return null;
}
/**
* Generate initial priorities from input
* This function converts engineer's priority values from task input into priority level (0 to number of tasks - 1),
* it assumes that the higher value of priority is the higher priority level
* @param input
* @return
*/
public static Integer[] getPrioritiesFromInput(TaskDescriptor[] input) {
Integer[] priorities = new Integer[input.length];
int[] assigned = new int[input.length];
Arrays.fill(assigned, 0);
// assign priority level (from highest to lowest)
for(int priority=input.length-1; priority>=0;priority--) {
int maxTaskIdx = 0;
int maxPriority = -1;
for (int x = 0; x < input.length; x++) {
if (assigned[x]==1) continue;
if (input[x].Priority > maxPriority) {
maxTaskIdx = x;
maxPriority = input[x].Priority;
}
}
priorities[maxTaskIdx] = priority;
assigned[maxTaskIdx]=1;
}
return priorities;
}
/**
* Create initial priority assignments
* @param maxPopulation
* @param priorityEngineer
* @param problem
* @return
*/
public List<PrioritySolution> createInitialPriorities(int maxPopulation, Integer[] priorityEngineer, PriorityProblem problem) {
List<PrioritySolution> population = new ArrayList<>(maxPopulation);
PrioritySolution individual;
for (int i = 0; i < maxPopulation; i++) {
if (i==0 && priorityEngineer!=null){
individual = new PrioritySolution(problem, priorityEngineer);
}
else {
individual = new PrioritySolution(problem);
}
population.add(individual);
}
return population;
}
/**
* Print out all results (best pareto, last population, time information, memory information..)
*/
private void saveResults(List<PrioritySolution> population, List<PrioritySolution> pareto)
{
JMetalLogger.logger.info("Saving best pareto priority assignments...");
// print pareto results
if (pareto.size()!=0) {
GAWriter writer = new GAWriter("_best_pareto.list", Level.FINE, null);
writer.info("Index\tPriorityJSON");
for (int idx = 0; idx < pareto.size(); idx++) {
writer.write(String.format("%d\t", idx));
writer.write(pareto.get(idx).getVariablesString());
writer.write("\n");
}
writer.close();
}
// print population results
if (population.size()!=0) {
JMetalLogger.logger.info("Saving population of priority assignments...");
GAWriter writer = new GAWriter("_last_population.list", Level.FINE, null);
writer.info("Index\tPriorityJSON");
for (int idx = 0; idx < population.size(); idx++) {
writer.write(String.format("%d\t", idx));
writer.write(population.get(idx).getVariablesString());
writer.write("\n");
}
writer.close();
}
GAWriter writer = new GAWriter(String.format("_result.txt"), Level.FINE, null);
long all = Monitor.getTime();
long evP1 = Monitor.getTime("evaluateP1");
long evP2 = Monitor.getTime("evaluateP2");
long evP2Ex = Monitor.getTime("external");
long searchTime = all-evP1-evP2-evP2Ex;
writer.info(String.format("TotalExecutionTime( s): %.3f",all/1000.0));
writer.info(String.format("SearchTime(s): %.3f",(searchTime)/1000.0));
writer.info(String.format("EvaluationTimeP1(s): %.3f",evP1/1000.0));
writer.info(String.format("EvaluationTimeP2(s): %.3f",evP2/1000.0));
writer.info(String.format("EvaluationTimeEx(s): %.3f",evP2Ex/1000.0));
writer.info(String.format("InitHeap: %.1fM (%.1fG)", Monitor.heapInit/Monitor.MB, Monitor.heapInit/Monitor.GB));
writer.info(String.format("usedHeap: %.1fM (%.1fG)", Monitor.heapUsed/Monitor.MB, Monitor.heapUsed/Monitor.GB));
writer.info(String.format("commitHeap: %.1fM (%.1fG)", Monitor.heapCommit/Monitor.MB, Monitor.heapCommit/Monitor.GB));
writer.info(String.format("MaxHeap: %.1fM (%.1fG)", Monitor.heapMax/Monitor.MB, Monitor.heapMax/Monitor.GB));
writer.info(String.format("MaxNonHeap: %.1fM (%.1fG)", Monitor.nonheapUsed/Monitor.MB, Monitor.nonheapUsed/Monitor.GB));
writer.close();
JMetalLogger.logger.info("Saving population...Done");
}
}
| 10,104 | 39.582329 | 194 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/CoEvolveStarter.java | package lu.uni.svv.PriorityAssignment;
import lu.uni.svv.PriorityAssignment.arrivals.Arrivals;
import lu.uni.svv.PriorityAssignment.arrivals.ArrivalsSolution;
import lu.uni.svv.PriorityAssignment.arrivals.SampleGenerator;
import lu.uni.svv.PriorityAssignment.arrivals.WorstGenerator;
import lu.uni.svv.PriorityAssignment.priority.AbstractPrioritySearch;
import lu.uni.svv.PriorityAssignment.priority.PrioritySolution;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.utils.FileManager;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.uma.jmetal.util.JMetalLogger;
import java.util.*;
import java.util.logging.Level;
public class CoEvolveStarter {
/**
* Main code to start co-evolution
* - initialize parameters
* - initialize global objects
* @param args
* @throws Exception
*/
public static void main( String[] args ) throws Exception {
// Environment Settings
Initializer.initLogger();
Settings.update(args);
// load input
TaskDescriptor[] input = TaskDescriptor.loadFromCSV(Settings.INPUT_FILE, Settings.TIME_MAX, Settings.TIME_QUANTA);
// update dynamic settings
Initializer.updateSettings(input);
// convert settings' time unit
Initializer.convertTimeUnit(Settings.TIME_QUANTA);
// make simulation time
int simulationTime = (int) Settings.TIME_MAX;
if (Settings.ADDITIONAL_SIMULATION_TIME != 0) {
simulationTime += Settings.ADDITIONAL_SIMULATION_TIME;
}
// create engineer's priority assignment
Integer[] prioritiy = null;
if (!Settings.RANDOM_PRIORITY) {
prioritiy = getPrioritiesFromInput(input);
}
JMetalLogger.logger.info("Initialized program");
// test mode check
boolean testGenerationMode = stringIn(Settings.TEST_GENERATION, new String[]{"Random","Adaptive","AdaptiveFull","Heuristic", "Limit", "Worst"}); //"Initial"
if (testGenerationMode){
GAWriter.init(null, true);
printInput(TaskDescriptor.toString(input, Settings.TIME_QUANTA), null);
}
// work for test data
List<Arrivals[]> testArrivals = null;
testArrivals = generateTestData(input, simulationTime, prioritiy);
if (testArrivals == null) {
// Quit all process
return;
}
if (Settings.RUN_CNT==0) {
run(input, simulationTime, prioritiy, testArrivals);
}
else {
for (int runID = 0; runID < Settings.RUN_CNT; runID++) {
Settings.RUN_NUM = Settings.RUN_START + runID;
run(input, simulationTime, prioritiy, testArrivals);
}
}
}
public static boolean stringIn(String str, String[] items){
for (String item : items) {
if (str.compareTo(item)==0) return true;
}
return false;
}
public static void run(TaskDescriptor[] input, int simulationTime, Integer[] prioritiy, List<Arrivals[]> testArrivals) throws Exception {
GAWriter.init(null, true);
printInput(TaskDescriptor.toString(input, Settings.TIME_QUANTA), null);
// initialze static objects
ArrivalsSolution.initUUID();
PrioritySolution.initUUID();
AbstractPrioritySearch.init();
// Run Co-Evolution (run function will generate result files)
CoEvolve system = new CoEvolve();
system.run(input, Settings.CYCLE_NUM, simulationTime, prioritiy, testArrivals);
}
public static List<Arrivals[]> generateTestData(TaskDescriptor[] input, int simulationTime, Integer[] priorityEngineer) throws Exception{
List<Arrivals[]> testArrivals=null;
SampleGenerator generator = new SampleGenerator(input, simulationTime);
if (Settings.TEST_GENERATION.compareTo("Random")==0) {
generator.generateRandom(Settings.NUM_TEST, false, false, false);
return null;
}
else if (Settings.TEST_GENERATION.compareTo("Adaptive")==0) {
generator.generateAdaptive(Settings.NUM_TEST, 100, true);
return null;
}
else if (Settings.TEST_GENERATION.compareTo("AdaptiveFull")==0) {
generator.generateAdaptive(Settings.NUM_TEST, 100, false);
return null;
}
else if (Settings.TEST_GENERATION.compareTo("Worst")==0) {
WorstGenerator worst = new WorstGenerator(input, simulationTime, priorityEngineer);
worst.generate(Settings.NUM_TEST);
return null;
}
else if (Settings.TEST_GENERATION.length()==0){
// normal execution
testArrivals = FileManager.LoadTestArrivals(Settings.TEST_PATH, input, simulationTime, Settings.NUM_TEST);
}
else{
throw new Exception("There is no options for " + Settings.TEST_GENERATION);
}
return testArrivals;
}
/**
* printing input and setting to the result folder to distinguish real
* @param inputs
* @param changed
*/
private static void printInput(String inputs, String changed){
String settingStr = Settings.getString();
System.out.print(settingStr);
// print current settings
GAWriter writer = new GAWriter("settings.txt", Level.FINE, null);
writer.info(settingStr);
writer.close();
// print original input
writer = new GAWriter("input.csv", Level.INFO, null);
writer.info(inputs);
writer.close();
// print changed inputs
if (changed != null) {
writer = new GAWriter("changed.txt", Level.INFO, null);
writer.print(changed);
writer.close();
}
}
/**
* Generate initial priorities from input
* This function converts engineer's priority values from task input into priority level (0 to number of tasks - 1),
* it assumes that the higher value of priority is the higher priority level
* @param input
* @return
*/
public static Integer[] getPrioritiesFromInput(TaskDescriptor[] input) {
Integer[] priorities = new Integer[input.length];
int[] assigned = new int[input.length];
Arrays.fill(assigned, 0);
// assign priority level (from highest to lowest)
for(int priority=input.length-1; priority>=0;priority--) {
int maxTaskIdx = 0;
int maxPriority = -1;
for (int x = 0; x < input.length; x++) {
if (assigned[x]==1) continue;
if (input[x].Priority > maxPriority) {
maxTaskIdx = x;
maxPriority = input[x].Priority;
}
}
priorities[maxTaskIdx] = priority;
assigned[maxTaskIdx]=1;
}
return priorities;
}
}
| 6,115 | 31.359788 | 158 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/FitnessEvaluator.java | package lu.uni.svv.PriorityAssignment;
import lu.uni.svv.PriorityAssignment.arrivals.Arrivals;
import lu.uni.svv.PriorityAssignment.priority.PriorityProblem;
import lu.uni.svv.PriorityAssignment.priority.PrioritySolution;
import lu.uni.svv.PriorityAssignment.priority.PrioritySolutionEvaluator;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.utils.FileManager;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.uma.jmetal.util.solutionattribute.impl.CrowdingDistance;
import org.uma.jmetal.util.solutionattribute.impl.DominanceRanking;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
public class FitnessEvaluator {
/**
* This class evaluates experiment results with a set of sequences of task arrivals (a test set)
* - The test set can be one used for external fitness or separately generated sequences
* - The path of test set can be below two ways
* - One test set: specify the path with Settings.TEST_PATH and Settings.TEST_CNT=0
* - Multiple test set: specify the path with Settings.TEST_PATH and Settings.TEST_CNT>0
* - the second case, each name of sub-folder for one test set should be "Set%02d"
* @param args
* @throws Exception
*/
public static void main( String[] args ) throws Exception {
// Environment Settings
Initializer.initLogger();
Settings.update(args);
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// Output path setting
GAWriter.init(".", false);
String inputFile = String.format("%s/input.csv", Settings.BASE_PATH);
TaskDescriptor[] input = TaskDescriptor.loadFromCSV(inputFile, Settings.TIME_MAX, Settings.TIME_QUANTA);
int simulationTime = calculateSimulationTime(input);
PriorityProblem problem = new PriorityProblem(input, simulationTime, Settings.SCHEDULER);
run(Settings.BASE_PATH, problem, Settings.TEST_PATH, 0, Settings.OUTPUT_PATH);
}
public static int calculateSimulationTime(TaskDescriptor[] input) throws Exception{
// Set SIMULATION_TIME
int simulationTime = Initializer.calculateSimulationTime(input);
if (simulationTime<0) {
System.out.println("Cannot calculate simulation time");
throw new Exception("Cannot calculate simulation time");
}
Settings.TIME_MAX = simulationTime;
Settings.ADDITIONAL_SIMULATION_TIME = (int)(Settings.ADDITIONAL_SIMULATION_TIME * (1/Settings.TIME_QUANTA));
Settings.MAX_OVER_DEADLINE = (int)(Settings.MAX_OVER_DEADLINE * (1/Settings.TIME_QUANTA));
// make simulation time
simulationTime = (int) Settings.TIME_MAX;
if (Settings.ADDITIONAL_SIMULATION_TIME != 0) {
simulationTime += Settings.ADDITIONAL_SIMULATION_TIME;
}
return simulationTime;
}
public static void run(String _basePath, PriorityProblem _problem, String _testPath, int _testSetCnt, String _outputName) throws Exception {
String solutionFile = String.format("%s/_best_pareto.list", _basePath);
List<PrioritySolution> solutions = loadSolutions(solutionFile, _problem);
// create output file
if (_outputName== null || _outputName.length()==0){
File path = new File(_testPath);
_outputName = path.getName();
}
String output = String.format("%s/_external/fitness_%s.csv", _basePath, _outputName);
String title = "TestID,SolutionIndex,SolutionID,Schedulability,Satisfaction,DeadlineMiss,Rank,CrowdDistance"; //
GAWriter writer = new GAWriter(output, Level.FINE, null);
writer.info(title);
//Re-evaluation
System.out.print(String.format("[%s] Working with %s", _basePath, _testPath));
if (_testSetCnt==0){
System.out.print("...");
String testFile = String.format("%s/test.list", _testPath);
reEvaluate(1, writer, testFile, _problem, solutions);
}
else {
for (int setID = 1; setID <= _testSetCnt; setID++) {
System.out.print(".");
String testFile = String.format("%s/Set%02d/test.list", _testPath, setID);
reEvaluate(setID, writer, testFile, _problem, solutions);
}
}
writer.close();
System.out.println("..Done");
}
public static void reEvaluate(int _setID, GAWriter _writer, String _testPath,
PriorityProblem _problem, List<PrioritySolution> _solutions) throws Exception {
List<Arrivals[]> testArrivals = FileManager.LoadTestArrivals(_testPath, _problem.Tasks, _problem.SimulationTime, 0);
// evaluate with a new test arrivals
PrioritySolutionEvaluator evaluator = new PrioritySolutionEvaluator(testArrivals, null);
evaluator.evaluate(_solutions, _problem);
for(int idx=0; idx<_solutions.size(); idx++) {
_writer.info(getSolutionInfoLine(_setID, idx, _solutions.get(idx)));
}
}
public static List<PrioritySolution> loadSolutions(String _solutionFile, PriorityProblem _problem) throws Exception{
BufferedReader br = new BufferedReader(new FileReader(_solutionFile));
br.readLine(); // throw file header
// load solutions
List<PrioritySolution> solutions = new ArrayList<>();
while(true){
String line = br.readLine();
if (line==null) break;
String[] columns = line.split("\t");
int solID = Integer.parseInt(columns[0]);
PrioritySolution solution = new PrioritySolution(_problem, columns[1]);
solution.ID = solID;
solutions.add(solution);
}
br.close();
return solutions;
}
public static String getSolutionInfoLine(int _testID, int _idx, PrioritySolution _solution) {
int rank = 0;
if (_solution.hasAttribute(DominanceRanking.class))
rank = (Integer)_solution.getAttribute(DominanceRanking.class);
double cDistance = 0.0;
if (_solution.hasAttribute(CrowdingDistance.class))
cDistance = (Double)_solution.getAttribute(CrowdingDistance.class);
StringBuilder line = new StringBuilder();
line.append(_testID);
line.append(",");
line.append(_idx);
line.append(",");
line.append(_solution.ID);
line.append(",");
line.append(-_solution.getObjective(0));
line.append(",");
line.append(-_solution.getObjective(1));
line.append(",");
line.append((int)_solution.getAttribute("DeadlineMiss"));
line.append(",");
line.append(rank);
line.append(",");
line.append(cDistance);
return line.toString();
}
}
| 7,128 | 40.690058 | 144 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/tools/ReverseSolutions.java | package lu.uni.svv.PriorityAssignment.tools;
import lu.uni.svv.PriorityAssignment.Initializer;
import lu.uni.svv.PriorityAssignment.priority.PriorityProblem;
import lu.uni.svv.PriorityAssignment.priority.PrioritySolution;
import lu.uni.svv.PriorityAssignment.utils.FileManager;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.apache.commons.io.FileUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
public class ReverseSolutions {
public static void main(String[] args) throws Exception {
// Environment Settings
Initializer.initLogger();
Settings.update(args);
GAWriter.init("", false);
// load test file names
for(int runID=1; runID<= Settings.RUN_CNT; runID++) {
String path = String.format("%s/Run%02d", Settings.BASE_PATH, runID);
reverseSolutions(String.format("%s/_best_pareto.list", path));
reverseSolutions(String.format("%s/_last_population.list", path));
}
}
public static void reverseSolutions(String _filename) throws Exception {
System.out.print("Reverse solutions in " + _filename);
List<Integer[]> solutions = loadSolutions(_filename);
// make reverse
List<Integer[]> reversed = new ArrayList<>();
for(int i=0; i<solutions.size(); i++){
Integer[] temp = reverse(solutions.get(i));
reversed.add(temp);
}
// load arrivals from file and save it
GAWriter writer = new GAWriter(_filename, Level.FINE, null);
writer.write("Index\tPriorityJSON\n");
for(int idx=0; idx<reversed.size(); idx++) {
String json = convertToJSON(reversed.get(idx));
writer.write(String.format("%d\t%s\n", idx, json));
}
writer.close();
System.out.println("..Done");
}
public static List<Integer[]> loadSolutions(String _solutionFile) throws Exception{
BufferedReader br = new BufferedReader(new FileReader(_solutionFile));
br.readLine(); // throw file header
// load solutions
List<Integer[]> solutions = new ArrayList<>();
while(true){
String line = br.readLine();
if (line==null) break;
String[] columns = line.split("\t");
int solID = Integer.parseInt(columns[0]);
String listStr = columns[1].trim();
listStr = listStr.substring(1,listStr.length()-2);
String[] list = listStr.split(",");
Integer[] priorities = new Integer[list.length];
for(int i=0; i<list.length; i++){
priorities[i] = Integer.parseInt(list[i].trim());
}
solutions.add(priorities);
}
br.close();
return solutions;
}
public static Integer[] reverse(Integer[] priorities){
// find max value
int maxLv = 0;
for(int i=0; i<priorities.length; i++){
if (priorities[i]>maxLv) maxLv = priorities[i];
}
// make reverse
Integer[] reverse = new Integer[priorities.length];
for(int i=0; i<priorities.length; i++){
reverse[i] = maxLv - priorities[i];
}
return reverse;
}
public static String convertToJSON(Integer[] priorities){
StringBuilder sb = new StringBuilder();
sb.append("[ ");
sb.append(priorities[0]);
for(int i=1; i<priorities.length; i++){
sb.append(", ");
sb.append(priorities[i]);
}
sb.append(" ]");
return sb.toString();
}
}
| 3,818 | 32.79646 | 87 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/tools/MergeSolutions.java | package lu.uni.svv.PriorityAssignment.tools;
import javafx.scene.layout.Priority;
import lu.uni.svv.PriorityAssignment.Initializer;
import lu.uni.svv.PriorityAssignment.arrivals.ArrivalProblem;
import lu.uni.svv.PriorityAssignment.arrivals.ArrivalsSolution;
import lu.uni.svv.PriorityAssignment.priority.PrioritySolution;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.utils.FileManager;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.apache.commons.io.FileUtils;
import java.io.*;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
public class MergeSolutions {
public static void main(String[] args) throws Exception {
// Environment Settings
Initializer.initLogger();
Settings.update(args);
GAWriter.init("", false);
// load test file names
for(int runID=1; runID<= Settings.RUN_CNT; runID++) {
String path = String.format("%s/Run%02d", Settings.BASE_PATH, runID);
mergePareto(path);
mergePopulation(path);
mergeResult(path);
FileUtils.deleteDirectory(new File(String.format("%s/_pareto", path)));
FileUtils.deleteDirectory(new File(String.format("%s/_population", path)));
}
}
public static void mergePareto(String _path) throws IOException {
System.out.print(_path+" Merge population...");
String folder = String.format("%s/_pareto", _path);
List<String> fileList = FileManager.listFilesUsingDirectoryStream(folder);
if (fileList.size()==0) {
System.out.println("Not found the files");
return;
}
Collections.sort(fileList);
// load arrivals from file and save it
String output = String.format("%s/_best_pareto.list", _path);
GAWriter writer = new GAWriter(output, Level.FINE, "Index\tPriorityJSON");
for(int idx=0; idx<fileList.size(); idx++) {
String name = fileList.get(idx);
if (!name.startsWith("priorities")) continue;
int actualIndex = Integer.parseInt(name.substring(11, name.length()-5));
// read file
String fullname = folder + "/" +name;
BufferedReader br = new BufferedReader(new FileReader(fullname));
String text = br.readLine();
br.close();
// write to file
writer.write(String.format("%d\t", actualIndex));
writer.write(text);
writer.write("\n");
}
writer.close();
System.out.println("..Done");
}
public static void mergePopulation(String _path) throws IOException {
System.out.print(_path+" Merge population...");
String folder = String.format("%s/_population", _path);
List<String> fileList = FileManager.listFilesUsingDirectoryStream(folder);
if (fileList.size()==0) {
System.out.println("Not found the files");
return;
}
Collections.sort(fileList);
// load arrivals from file and save it
String output = String.format("%s/_last_population.list", _path);
GAWriter writer = new GAWriter(output, Level.FINE, "Index\tPriorityJSON");
for(int idx=0; idx<fileList.size(); idx++) {
String name = fileList.get(idx);
if (!name.startsWith("last")) continue;
int actualIndex = Integer.parseInt(name.substring(5, name.length()-5));
// read file
String fullname = folder + "/" +name;
BufferedReader br = new BufferedReader(new FileReader(fullname));
String text = br.readLine();
br.close();
// write to file
writer.write(String.format("%d\t", actualIndex));
writer.write(text);
writer.write("\n");
}
writer.close();
System.out.println("..Done");
}
public static void mergeResult(String _path) throws IOException {
System.out.print(_path+" Result file move..");
String folder = String.format("%s/_pareto", _path);
List<String> fileList = FileManager.listFilesUsingDirectoryStream(folder);
if (fileList.size()==0) {
System.out.println("Not found the files");
return;
}
// load arrivals from file and save it
String output = String.format("%s/_result.txt", _path);
GAWriter writer = new GAWriter(output, Level.FINE, null);
for(int idx=0; idx<fileList.size(); idx++) {
String name = fileList.get(idx);
if (!name.startsWith("result_cycle")) continue;
// read file
String fullname = folder + "/" +name;
BufferedReader br = new BufferedReader(new FileReader(fullname));
while(true) {
String text = br.readLine();
if (text==null) break;
writer.write(text);
writer.write("\n");
}
br.close();
}
writer.close();
System.out.println("..Done");
}
}
| 5,205 | 36.185714 | 87 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/scheduler/OldRTScheduler.java | package lu.uni.svv.PriorityAssignment.scheduler;
import java.util.*;
import lu.uni.svv.PriorityAssignment.task.Task;
import lu.uni.svv.PriorityAssignment.arrivals.Arrivals;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.utils.Settings;
/**
* Scheduling Policy
* - We use Fixed Priority to schedule tasks.
* - The two task has same priority, first arrived execution in the ready queue has higher priority to use CPU.
* - In the other words, the execution that is arrived lately couldn't preempt the other executions already arrived in the ready queue.
*
* Deadline misses detection
* - We count the number of deadline misses while the scheduling(by SIMULATION_TIME)
* - And, if the ready queue has tasks after being done scheduling(after SIMULATION_TIME),
* we will execute this scheduler by finishQuing all tasks in the ready queue.
* @author jaekwon.lee
*
*/
public class OldRTScheduler extends RTScheduler {
/* For Scheduling */
private Schedule[][] schedules2=null; // for saving schedule results
// For Single Scheduler single core
private Task curTask;
private Task prevTask;
private int subStartTime = 0; // for checking preemption start time
public OldRTScheduler(TaskDescriptor[] _tasks, int _simulationTime) {
super(_tasks, _simulationTime);
}
/**
* properties to get result of scheduling
* @return
*/
public Schedule[][] getResult(){
return schedules2;
}
/////////////////////////////////////////////////////////////////
// Scheduling
/////////////////////////////////////////////////////////////////
/**
* Execute the RateMonotonic Algorithm
*/
public void run(Arrivals[] _arrivals, Integer[] priorities) {
initilizeEvaluationTools();
initialize(_arrivals);
try {
// Running Scheduler
timeLapsed = 0;
while(timeLapsed <= this.SIMULATION_TIME){
// append a new task which is matched with this time
appendNewTask(_arrivals, priorities);
//Execute Once!
executeOneUnit();
timeLapsed++;
}
//Check cycle complete or not (It was before ExecuteOneUnit() originally)
if (Settings.EXTEND_SCHEDULER && readyQueue.size() > 0) {
if (RTScheduler.DETAIL)
{
printer.println("\nEnd of expected time quanta");
printer.println("Here are extra execution because of ramaining tasks in queue");
printer.println("------------------------------------------");
}
// System.out.println(String.format("Exetended, still we have %d executions", readyQueue.size()));
while(readyQueue.size() > 0) {
executeOneUnit();
timeLapsed++;
}
// System.out.println(String.format("Ended %.1fms", time*0.1));
}
} catch (Exception e) {
printer.println("Some error occurred. Program will now terminate: " + e);
e.printStackTrace();
}
// schedules value updated inside function among functions used this function
return ;
}
/**
* Ready queue for the Scheduler
* This uses fixed priority for adding new task
*
*/
public Comparator<Task> queueComparator = new Comparator<Task>(){
@Override
public int compare(Task t1, Task t2) {
if (t1.Priority > t2.Priority)
return 1;
else if (t1.Priority < t2.Priority)
return -1;
else{
if (t1.ExecutionID < t2.ExecutionID)
return -1;
else if (t1.ExecutionID > t2.ExecutionID)
return 1;
return 0;
}
}
};
/**
* initialize scheduler
*/
protected void initialize(Arrivals[] _arrivals){
timeLapsed = 0;
curTask = null;
prevTask = null;
readyQueue = new PriorityQueue<Task>(60000, queueComparator);
// initialize index tables for accessing execution index at each time (all index starts from 0)
this.executionIndex= new int[_arrivals.length];
Arrays.fill(executionIndex, 0);
// Initialize result schedules
schedules2 = new Schedule[_arrivals.length][];
for (int x=0; x<_arrivals.length; x++) {
schedules2[x] = new Schedule[_arrivals[x].size()];
}
}
/**
* append a new task execution into readyQueue
* @param _variables
*/
private void appendNewTask(Arrivals[] _variables, Integer[] _priorities){
//compare arrivalTime and add a new execution into ReadyQueue for each task
for (int tIDX=0; tIDX<_variables.length; tIDX++)
{
// Check whether there is more executions
if (_variables[tIDX].size() <= executionIndex[tIDX]) continue;
if (timeLapsed != _variables[tIDX].get(executionIndex[tIDX])) continue;
// Add Tasks
TaskDescriptor task = this.Tasks[tIDX];
int priority = task.Priority;
if (_priorities != null){
priority = _priorities[tIDX];
}
Task t = new Task(task.ID, executionIndex[tIDX],
task.WCET,
timeLapsed, // arrival time
timeLapsed + task.Deadline, // deadline
priority,
task.Severity);
readyQueue.add(t);
executionIndex[tIDX]++;
}
}
/**
*
* @return 0: Nothing to do
* 1: Everything went normally
* 2: Deadline Missed!
* 3: Process completely executed without missing the deadline
* @throws Exception
*/
protected int executeOneUnit() throws Exception {
// init current task
prevTask = curTask;
curTask = null;
// If it has tasks to be executed
if (!readyQueue.isEmpty()) {
// Get one task from Queue
curTask = readyQueue.peek();
if (curTask.RemainTime <= 0)
throw new Exception(); //Somehow remaining time became negative, or is 0 from first
// process preemption
if ((prevTask != null) && (prevTask != curTask)){
if (prevTask.RemainTime != 0){
logExecutions(prevTask, subStartTime, timeLapsed);
}
subStartTime = timeLapsed;
}
// Set StartedTime
if (curTask.RemainTime == curTask.ExecutionTime) {
curTask.StartedTime = timeLapsed;
subStartTime = timeLapsed;
}
// Execute
curTask.RemainTime--;
}
// CPU time increased!
// timeLapsed++; // Process out of thie function, we assume that timeLapsed is increased after this line
if (curTask != null) {
// Check task finished and deadline misses
if (curTask.RemainTime == 0) {
readyQueue.poll(); // Task finished, poll the Task out.
// Set finished time of the task ended
curTask.FinishedTime = (timeLapsed+1);
logExecutions(curTask, subStartTime, (timeLapsed+1));
}
}
if (RTScheduler.DETAIL) { printState(); }
// End of this function
return 0;
}
/**
* logging execution result into "schedules"
* @param _task
* @param _start
* @param _end
*/
private void logExecutions(Task _task, int _start, int _end){
int tID = _task.ID-1;
int exID = _task.ExecutionID;
if (schedules2[tID][exID] == null) {
schedules2[tID][exID] =
new Schedule(_task.ArrivedTime,
_task.Deadline,
_start,
_end);
}
else{
schedules2[tID][exID].add(_start, _end);
}
}
/**
* Utility to show the scheduler execution status
*/
private void printState(){
// check state
boolean preemption = false;
long missedTime = 0;
// process preemption
if ((prevTask != null) && (prevTask != curTask)){
if (prevTask.RemainTime != 0) {
preemption = true;
}
}
// calculate deadline miss
if (curTask!=null) missedTime = (timeLapsed+1) - curTask.Deadline;
// Represent working status ========================
String prefix = " ";
String postfix = " ";
// Notification for a Task execution started.
if ((curTask != null) &&
((curTask.RemainTime + 1 == curTask.ExecutionTime) || (curTask != prevTask))) {
if (preemption) prefix = "*";
else prefix = "+";
}
//showing deadline miss time
if (missedTime>0) postfix ="x";
//After running if remaining time becomes zero, i.e. process is completely executed
if ((curTask != null) && (curTask.RemainTime == 0)) {
if (missedTime<0)
postfix = "/"; // Finished Normal.
else
postfix = "!"; //finished after Deadline.
}
if ( (timeLapsed%LINEFEED) == 0 )
printer.format("\nCPU[%010d]: ", timeLapsed);
printer.format("%s%02d%s ", prefix, (curTask == null ? 0 : curTask.ID), postfix);
if (curTask!=null && RTScheduler.PROOF) {
int type = (postfix.compareTo(" ")!=0 && postfix.compareTo("x")!=0)? 4: (prefix.compareTo(" ")!=0)?2:3;
timelines.get(curTask.ID -1)[timeLapsed] = type;
}
}
@Override
protected void finalize() throws Throwable{
for (int x = 0; x < schedules2.length; x++) {
for (int y = 0; y < schedules2[x].length; y++) {
schedules2[x][y] = null;
}
}
schedules2 = null;
}
} | 8,648 | 26.810289 | 138 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/scheduler/Schedule.java | package lu.uni.svv.PriorityAssignment.scheduler;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
public class Schedule {
int arrivalTime;
int deadline;
int finishedTime;
int executedTime;
int activatedNum;
ArrayList<Integer> startTime;
ArrayList<Integer> endTime;
ArrayList<Integer> CPUs;
public Schedule(int arrival, int deadline, int start, int end){
this(arrival, deadline, start, end, 0);
}
public Schedule(int arrival, int deadline){
this.arrivalTime = arrival;
this.deadline = deadline;
this.finishedTime = 0;
this.executedTime = 0;
this.activatedNum = 0;
startTime = new ArrayList<>(5);
endTime = new ArrayList<>(5);
CPUs = new ArrayList<>(5);
}
public Schedule(int arrival, int deadline, int start, int end, int cpu){
this.arrivalTime = arrival;
this.deadline = deadline;
if (cpu>=0) {
this.finishedTime = end;
this.executedTime = end - start;
}
else
this.finishedTime = 0;
this.activatedNum = 1;
startTime = new ArrayList<>(5);
endTime = new ArrayList<>(5);
CPUs = new ArrayList<>(5);
startTime.add(start);
endTime.add(end);
CPUs.add(cpu);
}
/**
* For loading schedule
* @param arrival
* @param deadline
* @param finished
* @param executed
* @param activated
* @param starts
* @param ends
* @param cpus
*/
public Schedule(int arrival, int deadline, int finished, int executed, int activated, ArrayList<Integer> starts, ArrayList<Integer> ends, ArrayList<Integer> cpus){
this.arrivalTime = arrival;
this.deadline = deadline;
this.finishedTime = finished;
this.executedTime = executed;
this.activatedNum = activated;
startTime = starts;
endTime = ends;
CPUs = cpus;
}
public void add(int start, int end){
add(start, end, 0);
}
public void add(int start, int end, int cpu){
this.activatedNum++;
startTime.add(start);
endTime.add(end);
CPUs.add(cpu);
if (cpu>=0) {
this.executedTime += end - start;
this.finishedTime = end;
}
}
@Override
protected void finalize() throws Throwable {
startTime.clear();
endTime.clear();
startTime = null;
endTime = null;
super.finalize();
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(arrivalTime);
sb.append(", ");
sb.append(deadline);
sb.append(", ");
sb.append(finishedTime);
sb.append(", ");
sb.append(executedTime);
sb.append(", ");
sb.append(activatedNum);
sb.append(", [");
for( int x=0; x<activatedNum; x++){
sb.append("[");
sb.append(startTime.get(x));
sb.append(",");
sb.append(endTime.get(x));
sb.append(",");
sb.append(CPUs.get(x));
sb.append("]");
if (x+1!=activatedNum) sb.append(", ");
}
sb.append("] ]");
return sb.toString();
}
////////////////////////////////////////////////////////////////
// Static functions
////////////////////////////////////////////////////////////////
public static void printSchedules(String _filename, Schedule[][] _schedules){
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int tID=0; tID<_schedules.length; tID++){
sb.append("\t[");
for (int x=0; x<_schedules[tID].length; x++) {
sb.append("\t\t");
sb.append(_schedules[tID][x].toString());
if (x+1==_schedules[tID].length){
sb.append("\n");
}
else{
sb.append(",\n");
}
}
if (tID+1 == _schedules.length)
sb.append("\t]");
else
sb.append("\t],");
}
sb.append("]");
GAWriter writer = new GAWriter(_filename, Level.INFO, "", null);
writer.write(sb.toString());
writer.close();
}
public static Schedule[][] loadSchedules(String _filename){
// Parse Json
Schedule[][] schedules = null;
FileReader reader = null;
try {
reader = new FileReader(_filename);
JSONParser parser = new JSONParser();
JSONArray json = (JSONArray) parser.parse(reader);
schedules = new Schedule[json.size()][];
for (int t = 0; t < json.size(); t++) {
JSONArray execs = (JSONArray) json.get(t);
schedules[t] = new Schedule[execs.size()];
for (int x=0; x<execs.size(); x++) {
JSONArray items = (JSONArray) execs.get(x);
// prepare variables
int activatedNum = ((Long)items.get(4)).intValue();
ArrayList<Integer> starts = new ArrayList<>();
ArrayList<Integer> ends = new ArrayList<>();
ArrayList<Integer> cpus = new ArrayList<>();
// load activates
JSONArray activates = (JSONArray) items.get(5);
for (int a=0; a<activatedNum; a++) {
JSONArray values = (JSONArray)activates.get(a);
starts.add(((Long)values.get(0)).intValue());
ends.add(((Long)values.get(1)).intValue());
int cpu = (values.size()>2) ? ((Long)values.get(2)).intValue() : 0;
cpus.add(cpu);
}
// create new schedule object
schedules[t][x] = new Schedule(((Long)items.get(0)).intValue(),
((Long)items.get(1)).intValue(),
((Long)items.get(2)).intValue(),
((Long)items.get(3)).intValue(), activatedNum, starts, ends, cpus);
}
}
}
catch (IOException | ParseException e){
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return schedules;
}
}
| 5,515 | 24.302752 | 164 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/scheduler/ScheduleVerify.java | package lu.uni.svv.PriorityAssignment.scheduler;
import lu.uni.svv.PriorityAssignment.arrivals.Arrivals;
import lu.uni.svv.PriorityAssignment.task.Task;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.task.TaskState;
import lu.uni.svv.PriorityAssignment.utils.RandomGenerator;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import java.awt.color.ICC_Profile;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
/**
* Scheduling Policy
* - We use Fixed Priority to schedule tasks.
* - The two task has same priority, first arrived execution in the ready queue has higher priority to use CPU.
* - In the other words, the execution that is arrived lately couldn't preempt the other executions already arrived in the ready queue.
*
* Deadline misses detection
* - We count the number of deadline misses while the scheduling(by SIMULATION_TIME)
* - And, if the ready queue has tasks after being done scheduling(after SIMULATION_TIME),
* we will execute this scheduler by finishQuing all tasks in the ready queue.
* @author jaekwon.lee
*
*/
public class ScheduleVerify{
protected Schedule[][] schedules;
protected TaskDescriptor[] Tasks;
protected int MaxTime;
protected Integer[] priorities;
protected int[][] timelines;
protected Arrivals[] arrivals;
public ScheduleVerify(Schedule[][] _schedules, TaskDescriptor[] _tasks, Integer[] _priorities)
{
this(_schedules, _tasks, _priorities, null);
}
public ScheduleVerify(Schedule[][] _schedules, TaskDescriptor[] _tasks, Integer[] _priorities, Arrivals[] _arrivals)
{
schedules = _schedules;
Tasks = _tasks;
MaxTime = getMaximumExecutionTime();
priorities = _priorities;
arrivals = _arrivals;
generateTimelines();
}
protected int getMaximumExecutionTime(){
int max = 0;
for(int x=0; x<schedules.length; x++){
int idx = schedules[x].length-1;
int val = schedules[x][idx].finishedTime;
if(max<val) max = val;
}
return max;
}
/**
* generate timelines (-2: ready state, 0: Idle, N: Running (cpu number) )
*/
protected void generateTimelines(){
// generate timelines
timelines = new int[schedules.length][];
for (int x=0; x<schedules.length; x++){
timelines[x] = new int[MaxTime];
}
// set ready state of task
for (int x=0; x<schedules.length; x++) {
for (int i = 0; i < schedules[x].length; i++) {
Schedule schedule = schedules[x][i];
for (int t = schedule.arrivalTime; t < schedule.finishedTime; t++) {
timelines[x][t] = -2;
}
}
}
// set activated time of a task execution
for (int x=0; x<schedules.length; x++) {
for (int i = 0; i < schedules[x].length; i++) {
Schedule schedule = schedules[x][i];
for(int a=0; a<schedule.activatedNum; a++){
int start = schedule.startTime.get(a);
int end = schedule.endTime.get(a);
int CPU = schedule.CPUs.get(a);
for(int t=start; t<end; t++) {
timelines[x][t] = (CPU==-1)? CPU: CPU+1;
}
}
}
}
}
/////////////////////////////////////////////////////////////////
// Verification 6 steps
/////////////////////////////////////////////////////////////////
/**
* initialize scheduler
*/
public boolean verify(){
try {
verifyArrivalTime();
verifyStartTime();
verifyExecutionTime();
verifyBlocking();
verifyCPUExecution();
// verifyTriggers();
}
catch(AssertionError | Exception e){
System.out.println(e.getMessage());
}
return true;
}
/**
* Task arrivals verification
* @return
*/
public boolean verifyArrivalTime() {
if (arrivals==null) return true;
// to except for triggered tasks.
boolean[] exceptions = TaskDescriptor.getArrivalExceptionTasks(Tasks);
for(int tIDX=0; tIDX<schedules.length; tIDX++){
if(exceptions[tIDX+1]) continue;
if (schedules[tIDX].length!=arrivals[tIDX].size()){
throw new AssertionError("Error to verify the number of executions on task " + (tIDX+1));
}
for(int e=0; e< schedules[tIDX].length; e++){
if (schedules[tIDX][e].arrivalTime != arrivals[tIDX].get(e)){
throw new AssertionError("Error to verify arrival time on " + (e+1) + " execution of task " + (tIDX+1));
}
}
}
return true;
}
/**
* Tasks which are higher priority than running tasks should be the blocked or running state
* When a task is in the ready state, only higher priority tasks then the task should be running.
* [Deprecated]
* @return
*/
public boolean verifyStartTime2() {
for (int x = 0; x < timelines.length; x++) {
ArrayList<Integer> list = getHigherPriorityTaskIdxs(Tasks[x].ID - 1);
if (list.size() == 0) {
for (int t = 0; t < timelines[x].length; t++) {
if (timelines[x][t] == -2) return false;
}
} else {
for (int t = 0; t < timelines[x].length; t++) {
if (timelines[x][t] <= 0) continue;
for (int taskIdx : list) {
if (timelines[taskIdx][t] == -2) return false; // if the higher priority tasks is ready state
}
}
}
}
return true;
}
/**
* When a task is in the ready state, only higher priority tasks then the task should be running.
* @return
*/
public boolean verifyStartTime() throws Exception{
// timeline
ArrayList<Integer> list = new ArrayList<>();
for (int t = 0; t < MaxTime; t++) {
list.clear();
int maxPriority = Integer.MAX_VALUE;
for (int x = 0; x < timelines.length; x++) {
if(timelines[x][t] == -2){
if (priorities[x]<maxPriority) maxPriority = priorities[x];
}
else if(timelines[x][t]>0){
list.add(priorities[x]);
}
}
if (maxPriority == Integer.MAX_VALUE) continue;
for(int priority:list) {
if (priority > maxPriority)
throw new AssertionError("Error to verify start time at "+t+" time.");
}
}
return true;
}
protected ArrayList<Integer> getHigherPriorityTaskIdxs(int taskIdx){
ArrayList<Integer> list = new ArrayList<>();
int priorityT = priorities[taskIdx];
for (int x=0; x<priorities.length; x++){
if (priorities[x]<priorityT) list.add(x);
}
return list;
}
/**
* All task executions have the same execution time of their WCET
* @return
*/
public boolean verifyExecutionTime(){
for (int x=0; x<schedules.length; x++) {
for (int i = 0; i < schedules[x].length; i++) {
if (Tasks[x].WCET != schedules[x][i].executedTime)
throw new AssertionError("Error to verify execution time");
}
}
return true;
}
/**
* Tasks are depends each other should not be executed at the same time unit
*
* @return
*/
public boolean verifyBlocking(){
// find max number of resources;
int maxResource = TaskDescriptor.getMaxNumResources(Tasks);
// build resource relationship matrix by task index
// Resource 1 => B, C
// Resource 2 => A, D
HashSet<Integer>[] resources = new HashSet[maxResource];
for (int tIDX=0; tIDX<Tasks.length; tIDX++) {
for (int d=0; d<Tasks[tIDX].Dependencies.length; d++){
int rIDX = Tasks[tIDX].Dependencies[d]-1;
if (resources[rIDX]==null)
resources[rIDX] = new HashSet<>();
resources[rIDX].add(tIDX);
}
}
// check tasks that have dependency are executed at the same time unit
for(int rIDX=0; rIDX<resources.length; rIDX++){
if (resources[rIDX].size()==0) continue;
for (int t=0; t<MaxTime; t++) {
int cnt = 0;
for (Integer tIDX : resources[rIDX]) {
if (timelines[tIDX][t] > 0) cnt +=1;
}
if (cnt>1) throw new AssertionError("Error to verify exclusive access to resources");
}
}
return true;
}
/**
* Task executions at one time unit should be less than the number of CPUs
* When a CPU is idle, no tasks are ready (some tasks can be blocked state)
* @return
*/
public boolean verifyCPUExecution(){
for (int t=0; t<MaxTime; t++) {
int cntRunning = 0;
int cntReady = 0;
for (int x=0; x<timelines.length; x++){
if (timelines[x][t] > 0) cntRunning +=1;
if (timelines[x][t] == -2) cntReady +=1;
}
if (cntRunning>Settings.N_CPUS) throw new AssertionError("Error to verify the number of CPU are executing");
if (cntRunning==0 && cntReady>0) throw new AssertionError("Error to verify the CPU idle state");
}
return true;
}
public boolean verifyTriggers(){
for (int x=0; x<schedules.length; x++) {
for (int i = 0; i < schedules[x].length; i++) {
if (Tasks[x].WCET == schedules[x][i].executedTime)
throw new AssertionError("Error to verify triggers");
}
}
return true;
}
} | 8,621 | 28.128378 | 138 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/scheduler/CountMap.java | package lu.uni.svv.PriorityAssignment.scheduler;
import java.util.HashMap;
public class CountMap extends HashMap<Integer, Integer> {
}
| 138 | 16.375 | 57 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/scheduler/RTScheduler.java | package lu.uni.svv.PriorityAssignment.scheduler;
import java.io.PrintStream;
import java.util.*;
import lu.uni.svv.PriorityAssignment.task.Task;
import lu.uni.svv.PriorityAssignment.arrivals.Arrivals;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.task.TaskState;
import lu.uni.svv.PriorityAssignment.task.TaskType;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
/**
* Scheduling Policy
* - We use Fixed Priority to schedule tasks.
* - The two task has same priority, first arrived execution in the ready queue has higher priority to use CPU.
* - In the other words, the execution that is arrived lately couldn't preempt the other executions already arrived in the ready queue.
*
* Deadline misses detection
* - We count the number of deadline misses while the scheduling(by SIMULATION_TIME)
* - And, if the ready queue has tasks after being done scheduling(after SIMULATION_TIME),
* we will execute this scheduler by finishQuing all tasks in the ready queue.
* @author jaekwon.lee
*
*/
public class RTScheduler {
/* Common Scheduling Variables */
protected int SIMULATION_TIME;
protected TaskDescriptor[] Tasks;
protected PriorityQueue<Task> readyQueue;
protected int[] executionIndex = null;
protected ArrayList<Schedule>[] schedules=null; // for saving schedule results
protected int timeLapsed; // current CPU time quanta
protected Integer[] priorities; // priorities
// For Single Scheduler single core
private Task curTask;
private Task prevTask;
private int subStartTime = 0; // for checking preemption start time
/* For Debugging */
public static boolean DETAIL = false; // Show detail information (for debugging)
public static boolean PROOF = false; // Show proof of execution (for debugging)
protected long LINEFEED = 50; // This value uses for showing CPU execution detail, This value gives line feed every LINEFEED time quanta
protected PrintStream printer = null; // print object to show progress during the scheduling.
protected List<int[]> timelines = null; // Timelines for each task
protected List<Task> executedTasks = null; // Save all executions' details
public RTScheduler(TaskDescriptor[] _tasks, int _simulationTime) {
this.Tasks = _tasks;
this.SIMULATION_TIME = _simulationTime;
printer = System.out;
}
/*
* setter
*/
public void setPrinter(PrintStream _stream) {
printer = _stream;
}
/**
* properties to get result of scheduling
* @return
*/
public Schedule[][] getResult(){
Schedule[][] result = new Schedule[schedules.length][];
for (int x=0; x<schedules.length; x++){
result[x] = new Schedule[schedules[x].size()];
schedules[x].toArray(result[x]);
}
return result;
}
/////////////////////////////////////////////////////////////////
// Scheduling
/////////////////////////////////////////////////////////////////
/**
* Execute the RateMonotonic Algorithm
*/
public void run(Arrivals[] _arrivals, Integer[] _priorities) {
initilizeEvaluationTools();
initialize(_arrivals);
priorities = _priorities;
try {
// Running Scheduler
timeLapsed = 0;
while(timeLapsed <= this.SIMULATION_TIME){
// append a new task which is matched with this time
appendNewTask(_arrivals);
//Execute Once!
executeOneUnit();
timeLapsed++;
}
//Check cycle complete or not (It was before ExecuteOneUnit() originally)
if (Settings.EXTEND_SCHEDULER && readyQueue.size() > 0) {
if (RTScheduler.DETAIL)
{
printer.println("\nEnd of expected time quanta");
printer.println("Here are extra execution because of ramaining tasks in queue");
printer.println("------------------------------------------");
}
// System.out.println(String.format("Exetended, still we have %d executions", readyQueue.size()));
while(readyQueue.size() > 0) {
executeOneUnit();
timeLapsed++;
}
// System.out.println(String.format("Ended %.1fms", time*0.1));
}
} catch (Exception e) {
printer.println("Some error occurred. Program will now terminate: " + e);
e.printStackTrace();
}
// schedules value updated inside function among functions used this function
return ;
}
/**
* Ready queue for the Scheduler
* This uses fixed priority for adding new task
*
*/
public Comparator<Task> queueComparator = new Comparator<Task>(){
@Override
public int compare(Task t1, Task t2) {
if (t1.Priority != t2.Priority)
return t2.Priority - t1.Priority; // the higher number is the higher priority
else {
if (t1.ID != t2.ID)
return t1.ID - t2.ID; // the lower number of task order is the the higher priority
else {
if (t1.ExecutionID != t2.ExecutionID)
return t1.ExecutionID - t2.ExecutionID; // the lower number of execution ID is the the higher priority
else
return 0;
}
}
}
};
/**
* initialize scheduler
*/
protected void initialize(Arrivals[] _arrivals){
timeLapsed = 0;
curTask = null;
prevTask = null;
readyQueue = new PriorityQueue<Task>(60000, queueComparator);
// initialize index tables for accessing execution index at each time (all index starts from 0)
this.executionIndex= new int[_arrivals.length];
Arrays.fill(executionIndex, 0);
// Initialize result schedules
schedules = new ArrayList[_arrivals.length]; // (ArrayList<Schedule>[])
for (int x=0; x<_arrivals.length; x++) {
schedules[x] = new ArrayList<>();
}
}
/**
* append a new task execution into readyQueue
* @param _variables
*/
protected void appendNewTask(Arrivals[] _variables){
//compare arrivalTime and add a new execution into ReadyQueue for each task
for (int tIDX=0; tIDX<_variables.length; tIDX++)
{
// Check whether there is more executions
if (_variables[tIDX].size() <= executionIndex[tIDX]) continue;
if (timeLapsed != _variables[tIDX].get(executionIndex[tIDX])) continue;
if (Tasks[tIDX].WCET==0 && Tasks[tIDX].MaxWCET==0) continue;
// Add Tasks
addReadyQueue(tIDX, timeLapsed);
}
}
protected boolean addReadyQueue(int taskIdx, int _currentTime){
TaskDescriptor taskDesc = this.Tasks[taskIdx];
int priority = taskDesc.Priority;
if (priorities != null){
priority = priorities[taskIdx];
}
Task t = new Task(taskDesc.ID, executionIndex[taskIdx],
taskDesc.WCET,
_currentTime, // arrival time
_currentTime + taskDesc.Deadline, // deadline
priority,
taskDesc.Severity);
t.updateTaskState(TaskState.Ready, _currentTime);
newSchedule(t);
readyQueue.add(t);
executionIndex[taskIdx]++;
return true;
}
/**
*
* @return 0: Nothing to do
* 1: Everything went normally
* 2: Deadline Missed!
* 3: Process completely executed without missing the deadline
* @throws Exception
*/
protected int executeOneUnit() throws Exception {
// init current task
prevTask = curTask;
curTask = null;
// If it has tasks to be executed
if (!readyQueue.isEmpty()) {
// Get one task from Queue
curTask = readyQueue.peek();
if (curTask.RemainTime <= 0)
throw new Exception(); //Somehow remaining time became negative, or is 0 from first
// process preemption
if ((prevTask != null) && (prevTask != curTask)){
if (prevTask.RemainTime != 0){
addSchedule(prevTask, subStartTime, timeLapsed, 0);
}
subStartTime = timeLapsed;
}
// Set StartedTime
if (curTask.RemainTime == curTask.ExecutionTime) {
curTask.StartedTime = timeLapsed;
subStartTime = timeLapsed;
}
// Execute
curTask.RemainTime--;
}
// CPU time increased!
// timeLapsed++; // Process out of thie function, we assume that timeLapsed is increased after this line
if (curTask != null) {
// Check task finished and deadline misses
if (curTask.RemainTime == 0) {
readyQueue.poll(); // Task finished, poll the Task out.
// Set finished time of the task ended
curTask.FinishedTime = (timeLapsed+1);
addSchedule(curTask, subStartTime, (timeLapsed+1),0);
}
}
return 0;
}
/**
* add execution result into "schedules"
* @param _task
* @param _start
* @param _end
*/
protected void addSchedule(Task _task, int _start, int _end, int _cid){
int tID = _task.ID-1;
int exID = _task.ExecutionID;
if (schedules[tID].size()-1 < exID) {
Schedule s = new Schedule(_task.ArrivedTime, _task.Deadline, _start, _end, _cid);
schedules[tID].add(s);
}
else{
schedules[tID].get(exID).add(_start, _end, _cid);
}
}
protected void newSchedule(Task _task){
int tID = _task.ID-1;
int exID = _task.ExecutionID;
schedules[tID].add(new Schedule(_task.ArrivedTime, _task.Deadline));
}
/////////////////////////////////////////////////////////////////
// Utilities
/////////////////////////////////////////////////////////////////
/**
* calculating Task Utilization
* @return
*/
public double calculateUtilization() {
double result = 0;
for (TaskDescriptor task:this.Tasks)
{
if (task.Type == TaskType.Periodic)
result += (task.WCET / (double)task.Period);
else
result += (task.WCET / (double)task.MinIA);
}
return result;
}
/**
* check input data's feasibility
* @return
*/
public boolean checkFeasibility() {
double feasible = muSigma(this.Tasks.length);
if (feasible >= calculateUtilization())
return true;
return false;
}
/**
* Greatest Common Divisor for two int values
* @param _result
* @param _periodArray
* @return
*/
public static long gcd(long _result, long _periodArray) {
while (_periodArray > 0) {
long temp = _periodArray;
_periodArray = _result % _periodArray; // % is remainder
_result = temp;
}
return _result;
}
/**
* Least Common Multiple for two int numbers
* @param _result
* @param _periodArray
* @return
*/
public static long lcm(long _result, long _periodArray) {
return _result * (_periodArray / RTScheduler.gcd(_result, _periodArray));
}
/**
* Least Common Multiple for int arrays
*
* @param _periodArray
* @return
*/
public static long lcm(long[] _periodArray) {
long result = _periodArray[0];
for (int i = 1; i < _periodArray.length; i++) {
result = RTScheduler.lcm(result, _periodArray[i]);
if (result<0){
result = -1;
break;
}
}
return result;
}
/**
* calculate feasible values
* @param _n
* @return
*/
public double muSigma(int _n) {
return ((double) _n) * ((Math.pow((double) 2, ((1 / ((double) _n)))) - (double) 1));
}
/////////////////////////////////////////////////////////////////
// Evaluation functions
/////////////////////////////////////////////////////////////////
public void initilizeEvaluationTools()
{
if (RTScheduler.DETAIL == false) return;
if (RTScheduler.PROOF == true) {
timelines = new ArrayList<int[]>();
for (TaskDescriptor task : this.Tasks)
timelines.add(new int[(int) this.SIMULATION_TIME*2]);
}
executedTasks = new ArrayList<Task>();
}
class SortbyPriority implements Comparator<TaskDescriptor>
{
@Override
public int compare(TaskDescriptor o1, TaskDescriptor o2) {
return (int)(o1.Priority - o2.Priority);
}
}
protected boolean isHigherTasksActive(Task t) {
// find higher priority tasks
List<Integer> IDXs = this.getHigherPriorityTasks(t);
// find active states for all IDXs
for(int idx:IDXs) {
if (timelines.get(idx)[(int)(t.ArrivedTime)] != 0)
return true;
}
return false;
}
protected boolean isLowerTasksActive(Task t) {
// find lower priority tasks
List<Integer> IDXs = this.getLowerPriorityTasks(t);
//find lower tasks active
for(int idx:IDXs) {
int[] timeline = timelines.get(idx);
for(int x=(int)t.StartedTime; x<t.FinishedTime; x++) {
if (timeline[x]!=0) return true;
}
}
return false;
}
protected List<Integer> getHigherPriorityTasks(Task t)
{
ArrayList<Integer> IDXs = new ArrayList<Integer>();
for(TaskDescriptor item:this.Tasks) {
if (item.Priority < t.Priority)
IDXs.add(item.ID-1);
if (item.Priority == t.Priority && item.ID<t.ID)
IDXs.add(item.ID-1);
}
return IDXs;
}
protected List<Integer> getLowerPriorityTasks(Task t)
{
// find lower priority tasks
ArrayList<Integer> IDXs = new ArrayList<Integer>();
for(TaskDescriptor item:this.Tasks) {
if (item.Priority > t.Priority)
IDXs.add(item.ID-1);
if (item.Priority == t.Priority && item.ID<t.ID)
IDXs.add(item.ID-1);
}
return IDXs;
}
protected int getMinimumInactiveTimeDelta(Task t) {
List<Integer> IDXs = this.getHigherPriorityTasks(t);
int tq = (int)t.ArrivedTime;
for (; tq<this.SIMULATION_TIME; tq++)
{
boolean isActive = false;
for(int idx:IDXs) {
if(timelines.get(idx)[tq] > 1) {
isActive = true;
break;
}
}
if (!isActive)
break;
}
return (int)(tq - t.ArrivedTime);
}
public int getMaximumDelayTime(Task t) {
// find higher priority tasks
List<Integer> IDXs = this.getHigherPriorityTasks(t);
//calculate sum of delay for all higher priority tasks
int delay =0;
for(int tID:IDXs) {
delay += this.Tasks[tID].WCET;
}
// calculate WCET of tasks which the tasks' periods are longer than 'delay'.
int[] multi = new int[this.Tasks.length];
Arrays.fill(multi, 1);
while(true) {
boolean flag = false;
for(int tID:IDXs) {
TaskDescriptor item = this.Tasks[tID];
int period = (int)( (item.Type==TaskType.Periodic) ? item.Period : item.MinIA);
if (delay < period*multi[tID]) break;
delay += item.WCET;
multi[tID]+=1;
flag = true;
}
if (flag == false) break;
}
return delay;
}
public boolean assertScheduler(GAWriter writer) {
if (!RTScheduler.DETAIL || !RTScheduler.PROOF) return true;
for (Task task:executedTasks)
{
String str = String.format("{ID:%d,Arrived:%03d, Started:%03d, Finished:%03d, Deadline:%03d}: ", task.ID, task.ArrivedTime, task.StartedTime, task.FinishedTime, task.Deadline+task.ArrivedTime);
writer.print(str);
try {
//first assert
if (!isHigherTasksActive(task)) {
assert task.StartedTime == task.ArrivedTime: "Failed to assert higher_tasks_non_active";
}
else {
assert task.StartedTime <= (task.ArrivedTime+getMinimumInactiveTimeDelta(task)): "Failed to assert non exceed WCET";
}
//second assert
assert !isLowerTasksActive(task): "Failed to assert lower_tasks_active";
writer.print("Success\n");
}
catch(AssertionError e) {
writer.print(e.getMessage()+"\n");
}//
}// for
return true;
}
public String getTimelinesStr()
{
if (!RTScheduler.DETAIL || !RTScheduler.PROOF) return "";
StringBuilder sb = new StringBuilder();
for(int tID=0; tID<this.Tasks.length; tID++)
{
sb.append(String.format("Task %02d: ", tID+1));
for (int x=0; x<this.SIMULATION_TIME; x++) {
switch(timelines.get(tID)[x]) {
case 0: sb.append("0 "); break; // Not working
case 1: sb.append("A "); break; // Arrived
case 2: sb.append("S "); break; // Started
case 3: sb.append("W "); break; // Working
case 4: sb.append("E "); break; // Ended
}
}
sb.append("\n");
}
return sb.toString();
}
@Override
protected void finalize() throws Throwable{
for (int x = 0; x < schedules.length; x++) {
schedules[x].clear();
schedules[x] = null;
}
schedules = null;
}
/////////////////////////////////////////////////////////////////
// Information functions
/////////////////////////////////////////////////////////////////
//
// public String getMissedDeadlineString() {
// StringBuilder sb = new StringBuilder();
// sb.append("TaskID,ExecutionID,Arrival,Started,Finished,Deadline,Misses(finish-deadline)\n");
//
// for (int tid=1; tid<=this.Tasks.length; tid++) {
// for (Task item:missedDeadlines) {
// if (tid!=item.ID) continue;
// long deadline_tq = (item.ArrivedTime+item.Deadline);
// sb.append(String.format("%d,%d,%d,%d,%d,%d,%d\n",
// item.ID, item.ExecutionID, item.ArrivedTime, item.StartedTime, item.FinishedTime, deadline_tq, item.FinishedTime - deadline_tq));
// }
// }
// return sb.toString();
// }
//
// public String getByproduct() {
// return "";
// }
//
// public Task getMissedDeadlineTask(int idx){
// if (this.missedDeadlines.size()>idx)
// return this.missedDeadlines.get(idx);
// return null;
// }
//
// /**
// * get Deadline Missed items
// * @return
// */
// public String getExecutedTasksString() {
// StringBuilder sb = new StringBuilder();
// sb.append("TaskID,ExecutionID,Arrival,Started,Finished,Deadline,Misses(finish-deadline),Pow\n");
//
// for (int tid=1; tid<=this.Tasks.length; tid++) {
// for (Task item:executedTasks) {
// if (tid!=item.ID) continue;
//
// long deadline_tq = (item.ArrivedTime + item.Deadline);
// int missed = (int)(item.FinishedTime - deadline_tq);
// double fitness_item = evaluateDeadlineMiss(item, missed);
//
// sb.append(String.format("%d,%d,%d,%d,%d,%d,%d,%.32e\n",
// item.ID, item.ExecutionID,item.ArrivedTime, item.StartedTime, item.FinishedTime, deadline_tq, missed, fitness_item));
// }
// }
// return sb.toString();
// }
} | 17,575 | 27.672104 | 196 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/scheduler/SchedulerDrawer.java | package lu.uni.svv.PriorityAssignment.scheduler;
import lu.uni.svv.PriorityAssignment.priority.PriorityProblem;
import lu.uni.svv.PriorityAssignment.priority.PrioritySolution;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.uma.jmetal.util.JMetalLogger;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.logging.ConsoleHandler;
public class SchedulerDrawer {
public static void main( String[] args ) throws Exception {
// Environment Settings
// String PATH = "results/TEST_T";
// String PATH = "results/20200505_Minimum3/Run02";
String PATH = "results/COEVOLEX/DistAnalysis3/";
int SIMULATION_TIME = 80000;
GAWriter.setBasePath(PATH);
System.out.println("-----------Schedule drawer----------------");
int solutionID = 1;
int testNum = 0;
System.out.print("Loading schedules....");
Schedule[][] schedules = Schedule.loadSchedules(PATH + String.format("/_schedules/schedule_%d_num%d.json", solutionID, testNum));
System.out.println("Done");
ScheduleCalculator sc = new ScheduleCalculator(schedules, null);
int[] maxs = sc.getMaximumExecutions();
for (int x=0; x<maxs.length; x++)
System.out.println(String.format("Task%d: %d",x+1, maxs[x]));
System.out.println("\nMinimum:");
int[] mins = sc.getMinimumExecutions();
for (int x=0; x<mins.length; x++)
System.out.println(String.format("Task%d: %d",x+1, mins[x]));
System.out.println("\nCounts:");
CountMap[] counts = sc.getExecutionDistList();
for (int t=0; t<counts.length; t++){
System.out.print("Task"+(t+1)+": {");
Integer[] keys = new Integer[counts[t].size()];
counts[t].keySet().toArray(keys);
Arrays.sort(keys);
for(int x=keys.length-1; x>=0; x--){
int value = counts[t].get(keys[x]);
System.out.print(String.format("%d: %d, ",keys[x], value));
}
System.out.println("}");
}
//TODO:: need to debug (these two lines are added by the class modification)
TaskDescriptor[] input = TaskDescriptor.loadFromCSV(PATH + "input.csv", Settings.TIME_MAX, Settings.TIME_QUANTA);
PriorityProblem problem = new PriorityProblem(input, SIMULATION_TIME, Settings.SCHEDULER);
String filepath = String.format("%s/_priorities/sol%d_num%d.json", PATH, solutionID, testNum);
String json = new String( Files.readAllBytes( Paths.get(filepath) ) );
PrioritySolution solution = new PrioritySolution(problem, json);
String filename = String.format(PATH + "/draws/schedule_%d_num%d.txt", solutionID, testNum);
drawSchedule(schedules, solution.toArray(), SIMULATION_TIME, filename);
}
public static void drawSchedule(Schedule[][] schedules, Integer[] _priorities, int stime, String _filename){
int maxTime = 0;
for (int t=0; t<schedules.length; t++) {
int finishedTime = schedules[t][schedules[t].length-1].finishedTime;
if (maxTime < finishedTime){
maxTime = finishedTime;
}
}
PrintStream writer = null;
if (_filename==null){
writer = System.out;
}
else{
File file = new File(_filename);
if (!file.getParentFile().exists())
{
file.getParentFile().mkdirs();
}
OutputStream os = null;
try {
os = new FileOutputStream(_filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (os==null) return;
writer = new PrintStream(os);
}
int simulationTime = Math.min(stime, maxTime);
writer.println(String.format("Total simulation Time: %d", simulationTime));
ScheduleCalculator calculator = new ScheduleCalculator(schedules, null);
int[] dms = calculator.getDeadlineMissList();
writer.println(String.format("Total simulation Time: %d", simulationTime));
for (int t=0; t<schedules.length; t++) {
StringBuilder sb = new StringBuilder();
sb.append("Task");
sb.append(String.format("%02d", t + 1));
sb.append(" (");
sb.append(String.format("%02d", _priorities[t]));
sb.append(", DM-");
sb.append(String.format("%02d", dms[t]));
sb.append("): ");
int e = 0;
int a = -1;
int start = -1;
int end = -1;
for (int time = 0; time < simulationTime; time++) {
if (time%10==0) sb.append("|");
if (time % 100 == 0) sb.append(String.format("%d|",time));
if (time % 1000 == 0) sb.append("|");
if (time >= end) {
int[] vals = findNextArrival(schedules[t], e, a);
e = vals[0];
a = vals[1];
start = vals[2];
end = vals[3];
}
if (time >= start && time < end) {
if (time>=schedules[t][e].deadline){
sb.append("!");
}
else sb.append("*");
} else {
sb.append(".");
}
}
writer.println(sb.toString());
}
}
public static int[] findNextArrival(Schedule[] schedules, int e, int a){
int[] vals = new int[4];
Arrays.fill(vals, -1);
vals[0] = e;
vals[1] = a;
vals[1]+=1;
if (vals[0]>=schedules.length) return vals;
if (vals[1]>= schedules[e].startTime.size()) {
vals[1]=0;
vals[0]++;
}
if (vals[0]>=schedules.length) return vals;
List<Integer> starts = schedules[vals[0]].startTime;
List<Integer> ends = schedules[vals[0]].endTime;
vals[2] = starts.get(vals[1]);
vals[3] = ends.get(vals[1]);
return vals;
}
}
| 5,342 | 30.245614 | 131 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/scheduler/SQMScheduler.java | package lu.uni.svv.PriorityAssignment.scheduler;
import lu.uni.svv.PriorityAssignment.arrivals.Arrivals;
import lu.uni.svv.PriorityAssignment.task.Task;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.task.TaskState;
import lu.uni.svv.PriorityAssignment.utils.RandomGenerator;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import java.util.ArrayList;
/**
* Scheduling Policy
* - We use Fixed Priority to schedule tasks.
* - The two task has same priority, first arrived execution in the ready queue has higher priority to use CPU.
* - In the other words, the execution that is arrived lately couldn't preempt the other executions already arrived in the ready queue.
*
* Deadline misses detection
* - We count the number of deadline misses while the scheduling(by SIMULATION_TIME)
* - And, if the ready queue has tasks after being done scheduling(after SIMULATION_TIME),
* we will execute this scheduler by finishQuing all tasks in the ready queue.
* @author jaekwon.lee
*
*/
public class SQMScheduler extends RTScheduler{
/* For Scheduling */
protected Task[] CPU;
protected int[] resources; // shared resources
protected ArrayList<Task>[] blockQueue; // shared resources
protected boolean[] exceptions; // for excepting periodic arrival to triggered task
protected ArrayList<Integer> triggerList; // tasks list to make trigger event
protected int[] CIDs;
RandomGenerator randomGen;
public SQMScheduler(TaskDescriptor[] _tasks, int _simulationTime) {
super(_tasks, _simulationTime);
}
/////////////////////////////////////////////////////////////////
// Scheduling
/////////////////////////////////////////////////////////////////
/**
* initialize scheduler
*/
protected void initialize(Arrivals[] _arrivals){
super.initialize(_arrivals);
this.CPU = new Task[Settings.N_CPUS];
for (int i=0; i<Settings.N_CPUS; i++) { this.CPU[i] = null; }
// for randomizing selecting a CPU
randomGen = new RandomGenerator();
CIDs = new int[Settings.N_CPUS];
for (int i = 0; i <CIDs.length; i++) { CIDs[i] = i; }
int maxResources = TaskDescriptor.getMaxNumResources(Tasks);
this.resources = new int[maxResources+1]; // used from index 1;
this.blockQueue = new ArrayList[this.resources.length];
for(int x=0; x<blockQueue.length; x++)
this.blockQueue[x] = new ArrayList<>();
this.triggerList = new ArrayList<>();
this.exceptions = TaskDescriptor.getArrivalExceptionTasks(Tasks);
}
/**
* Execute the RateMonotonic Algorithm
*/
public void run(Arrivals[] _arrivals, Integer[] _priorities) {
initilizeEvaluationTools();
initialize(_arrivals);
priorities = _priorities;
try {
// Running Scheduler
timeLapsed = 0;
while (timeLapsed <= this.SIMULATION_TIME) {
// append a new task which is matched with this time
appendNewTask(_arrivals);
//Execute Once!
executeMultiCore(Settings.N_CPUS);
timeLapsed++;
}
//Check cycle complete or not (It was before ExecuteOneUnit() originally)
if (Settings.EXTEND_SCHEDULER && checkExecution()) {
if (SQMScheduler.DETAIL) {
printer.println("\nEnd of expected time quanta");
printer.println("Here are extra execution because of ramaining tasks in queue");
printer.println("------------------------------------------");
}
// System.out.println(String.format("Exetended, still we have %d executions", readyQueue.size()));
while (checkExecution()) {
executeMultiCore(Settings.N_CPUS);
timeLapsed++;
}
}
} catch (Exception e) {
printer.println("Some error occurred. Program will now terminate: " + e);
e.printStackTrace();
}
if (Settings.VERIFY_SCHEDULE && this.SIMULATION_TIME<100000)
new ScheduleVerify(getResult(), Tasks, priorities, _arrivals).verify();
return;
}
protected boolean checkExecution(){
if (readyQueue.size() > 0) return true;
for (int i=0; i< CPU.length; i++){
if (CPU[i] != null) return true;
}
return false;
}
/**
* append a new task execution into readyQueue
* @param _variables
*/
protected void appendNewTask(Arrivals[] _variables){
//compare arrivalTime and add a new execution into ReadyQueue for each task
for (int tIDX=0; tIDX<_variables.length; tIDX++)
{
if (exceptions[this.Tasks[tIDX].ID]) continue;
// Check whether there is more executions
if (_variables[tIDX].size() <= executionIndex[tIDX]) continue;
if (timeLapsed != _variables[tIDX].get(executionIndex[tIDX])) continue;
// Remove tasks that has 0 execution time
if (Tasks[tIDX].WCET==0 && Tasks[tIDX].MaxWCET==0) continue;
// Add Tasks
addReadyQueue(tIDX, timeLapsed);
}
}
/**
* work with multi core
* We randomly choose the execution order of CPUs
* @param nCPUs
* @return
* @throws Exception
*/
public int executeMultiCore(int nCPUs) throws Exception{
// Mix the order of CPU idx
for (int i = 0; i <nCPUs-1; i++) {
// int j = randomGen.nextInt(0, nCPUs-1);
int j = (int)(Math.random()*nCPUs);
int temp = CIDs[i];
CIDs[i] = CIDs[j];
CIDs[j] = temp;
}
// Execute each core
for (int i = 0; i <nCPUs; i++) {
int ret = executeOneUnit(CIDs[i]);
if (ret!=0){
return ret;
}
}
// Process for the finished task
for (int x = 0; x <nCPUs; x++) {
if (CPU[x]!=null && CPU[x].RemainTime == 0) {
int startTime = CPU[x].updateTaskState(TaskState.Idle, timeLapsed + 1);
addSchedule(CPU[x], startTime, (timeLapsed + 1), x);
releaseResources(CPU[x].ID);
if (Tasks[CPU[x].ID - 1].Triggers.length != 0)
triggerList.add(CPU[x].ID);
CPU[x] = null;
}
}
triggerTasks();
return 0;
}
/**
*
* @return 0: Nothing to do
* 1: Everything went normally
* 2: Deadline Missed!
* 3: Process completely executed without missing the deadline
* @throws Exception
*/
int executeOneUnit(int cid) throws Exception {
// Get one task from Queue
if (CPU[cid] == null) {
// get top priority task and if a resource that is required by the task, block the task
Task top = readyQueue.poll();
while(top!=null) {
int rID = checkResources(top.ID);
if (rID==0) break;
top.updateTaskState(TaskState.Blocked, timeLapsed);
blockQueue[rID].add(top);
top = readyQueue.poll();
}
// Assign CPU to the task
if (top != null){
top.updateTaskState(TaskState.Running, timeLapsed);
CPU[cid] = top;
}
}
else{
// if a CPU is executing a task, we check whether the task will be preempted.
Task top = readyQueue.peek();
// managing preemption (check all cpus the task should be preempted)
while ((top != null) && (needPreempted(cid))) {
// check dependency, if true, move to the blockQueue
int rID = checkResources(top.ID);
if (rID>0){
top.updateTaskState(TaskState.Blocked, timeLapsed);
blockQueue[rID].add(readyQueue.poll());
top = readyQueue.peek();
continue;
}
// change current task state
int startTime = CPU[cid].updateTaskState(TaskState.Preempted, timeLapsed);
addSchedule(CPU[cid], startTime, timeLapsed, cid);
// exchange task (to keep the order of ready queue we poll first)
Task prev = CPU[cid];
CPU[cid] = readyQueue.poll();
readyQueue.add(prev);
// change the new task state
CPU[cid].updateTaskState(TaskState.Running, timeLapsed);
}
}
if (CPU[cid] != null) {
lockResources(CPU[cid].ID);
CPU[cid].RemainTime--;
}
return 0;
}
/**
* look ahead level 2를 유지하고 확인
* @param cid
* @return
*/
protected boolean needPreempted(int cid){
Task[] peeks = new Task[CPU.length];
int pSize = 0;
boolean needPreemption = false; // flag to check preemption requirements
// we need to check for N times which is the same number of CPU
for (int peekCnt=0; peekCnt<CPU.length; peekCnt++){
// The task in the CPU[cid] should be preempted by the task in the ready queue?
Task t = readyQueue.poll();
if (t==null) break;
peeks[pSize++] = t;
// if current task running in this CPU need to be preempted
if (t.Priority > CPU[cid].Priority) {
needPreemption = true;
// Count how many tasks can be executed by other CPUs
int cntAvailable = 0;
for (int y = 0; y < CPU.length; y++) {
if (cid == y) continue;
// find cpus that are not working or lower priority task running than current CPU
if (CPU[y] == null || CPU[y].Priority < CPU[cid].Priority) {
cntAvailable++;
}
}
// Check whether other CPUs can deal with the peeked task
if (pSize<=cntAvailable) {
needPreemption = false;
// to check the next task in the ready queue, we do not break here
continue;
}
}
break;
}
for (int i=0; i<pSize; i++){
readyQueue.add(peeks[i]);
}
return needPreemption;
}
protected int checkResources(int taskID){
int[] deps = Tasks[taskID-1].Dependencies;
if (deps.length>0){
for (int resID:deps ){
int lockedID = resources[resID];
if (lockedID!=0 && lockedID!=taskID) return resID;
}
}
return 0;
}
protected boolean lockResources(int taskID){
int[] deps = Tasks[taskID-1].Dependencies;
if (deps.length>0){
for (int resID : deps){
resources[resID] = taskID;
}
return true;
}
return false;
}
protected boolean releaseResources(int taskID){
int[] dependencies = Tasks[taskID-1].Dependencies;
if (dependencies.length>0){
for (int resID:dependencies){
// release resource
awakeBlockedTasks(resID);
}
return true;
}
return false;
}
protected boolean awakeBlockedTasks(int _resID){
for (int x=0; x<blockQueue[_resID].size(); x++){
Task task = blockQueue[_resID].get(x);
int startTime = task.updateTaskState(TaskState.Ready, timeLapsed+1);
addSchedule(task, startTime, timeLapsed+1, -1);
readyQueue.add(task);
}
blockQueue[_resID].clear();
resources[_resID] = 0;
return true;
}
protected boolean triggerTasks(){
for (int taskID: triggerList) {
int[] triggeredList = Tasks[taskID - 1].Triggers;
for (int x = 0; x < triggeredList.length; x++) {
addReadyQueue(triggeredList[x] - 1, timeLapsed + 1);
}
}
triggerList.clear();
return true;
}
} | 10,408 | 28.075419 | 138 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/scheduler/ScheduleCalculator.java | package lu.uni.svv.PriorityAssignment.scheduler;
import lu.uni.svv.PriorityAssignment.utils.Settings;
public class ScheduleCalculator {
Schedule[][] schedules;
int[] targets;
public ScheduleCalculator(Schedule[][] _schedules, int[] _targets){
schedules = _schedules;
targets = _targets;
}
private boolean inTargets(int taskID){
if (targets==null) return true;
if (targets.length==0) return true;
for (int k=0; k<targets.length; k++){
if (taskID == targets[k]) return true;
}
return false;
}
/**
* fitness function
* return a sum of all distance of e-d margins in all tasks
* @return
*/
public double distanceMargin(boolean reverse){
double result = 0.0;
double direction = 1.0;
if (reverse) direction = -1.0;
// tasks
for (int t=0; t<schedules.length; t++) {
if (!inTargets(t+1)) continue;
// executions
for (int e = 0; e < schedules[t].length; e++) {
Schedule schedule = schedules[t][e];
if (schedule == null) {
System.out.println(String.format("schedule is null on Task%d exec %d in distanceMargin", t, e));
continue;
}
int diff = schedule.finishedTime - schedule.deadline;
if (Settings.MAX_OVER_DEADLINE!=0 && diff > Settings.MAX_OVER_DEADLINE){
diff = Settings.MAX_OVER_DEADLINE;
}
result += direction * Math.pow(Settings.FD_BASE, diff/Settings.FD_EXPONENT);
}
}
if (Double.isInfinite(result))
result = Double.MAX_VALUE;
return result;
}
/**
* print each bin of e-d values for a solution
*/
public void checkBins(){
int size = 100;
int[] cnt = new int[size+1];
int[] cntM = new int[size+1];
// tasks
for (int t=0; t<schedules.length; t++) {
if (!inTargets(t+1)) continue;
// executions
for (int e = 0; e < schedules[t].length; e++) {
Schedule schedule = schedules[t][e];
int diff = schedule.finishedTime - schedule.deadline;
int bin = diff/1000;
if (bin<0){
if (bin<-size) bin = -size;
cntM[-bin] += 1;
}
else{
if (bin>size) bin = size;
cnt[bin] += 1;
}
if (bin==100){
System.out.println("Task" + (t+1));
}
}
}
StringBuilder sb = new StringBuilder(5000);
sb.append("CNT_M:");
for(int i=0; i<=size; i++){
sb.append(cntM[i]);
sb.append(",");
}
sb.append("\n CNT :");
for(int i=0; i<=size; i++){
sb.append(cnt[i]);
sb.append(",");
}
System.out.println(sb.toString());
}
/**
* get a number of deadline miss for all tasks
* @return
*/
public int checkDeadlineMiss(){
int count = 0;
// tasks
for (int t=0; t<schedules.length; t++) {
if (!inTargets(t+1)) continue;
if (schedules[t]==null) continue;
// executions
for (int e = 0; e < schedules[t].length; e++) {
Schedule schedule = schedules[t][e];
if (schedule == null) {
System.out.println(String.format("schedule is null on Task%d exec %d in checkDeadlineMiss", t, e));
continue;
}
int diff = schedule.finishedTime - schedule.deadline;
// Deadline missed
if (diff > 0) {
count += 1;
}
}
}
return count;
}
/**
* get string about information of deadline miss
* It returns a list of taskID, executionID, e-d as String
* @param head
* @return
*/
public String getDeadlineMiss(String head){
StringBuilder sb = new StringBuilder();
int count = 0;
// tasks
for (int t=0; t<schedules.length; t++) {
if (!inTargets(t+1)) continue;
if (schedules[t]==null) continue;
// executions
for (int e = 0; e < schedules[t].length; e++) {
Schedule schedule = schedules[t][e];
int diff = schedule.finishedTime - schedule.deadline;
// Deadline missed
if (diff > 0) {
sb.append(head);
sb.append(t+1);
sb.append(",");
sb.append(e);
sb.append(",");
sb.append(diff);
sb.append("\n");
}
}
}
return sb.toString();
}
/**
* print schedules
*/
public void printSchedule(){
// for each task
for(int t=0; t<schedules.length; t++) {
StringBuilder sb = new StringBuilder();
if (schedules[t]==null) {
sb.append("null");
}
else {
Schedule[] schedule = schedules[t];
sb.append("{ ");
// for each execution
for (int x = 0; x < schedule.length; x++) {
if (x >= 5) {
sb.append("... ");
sb.append(schedule.length - 2);
sb.append(" more");
break;
}
sb.append(x);
sb.append(":[");
sb.append(schedule[x].arrivalTime);
sb.append(", ");
for (int a = 0; a < schedule[x].activatedNum; a++) {
sb.append(schedule[x].startTime.get(a));
sb.append("(");
sb.append(schedule[x].endTime.get(a) - schedule[x].startTime.get(a));
sb.append("), ");
}
sb.append("], ");
}
sb.append(" }");
}
// sb.append("\n");
System.out.println("Task" + t + ": " + sb.toString());
}
}
/**
* maximum e-d each task
* @return list of maximum e-d
*/
public int[] getMaximumExecutions(){
int[] maximumMissed = new int[schedules.length];
// tasks
for (int t=0; t<schedules.length; t++) {
int maxValue = Integer.MIN_VALUE;
if (schedules[t]!=null) {
for (int e = 0; e < schedules[t].length; e++) {
Schedule schedule = schedules[t][e];
int diff = schedule.finishedTime - schedule.deadline;
if (maxValue < diff) {
maxValue = diff;
}
}
}
maximumMissed[t] = maxValue;
}
return maximumMissed;
}
/**
* minimum e-d each task
* @return list of maximum e-d
*/
public int[] getMinimumExecutions(){
int[] minimumMissed = new int[schedules.length];
// tasks
for (int t=0; t<schedules.length; t++) {
int minValue = Integer.MAX_VALUE;
// executions
if (schedules[t]!=null) {
for (int e = 0; e < schedules[t].length; e++) {
Schedule schedule = schedules[t][e];
int diff = schedule.finishedTime - schedule.deadline;
if (minValue > diff) {
minValue = diff;
}
}
}
minimumMissed[t] = minValue;
}
return minimumMissed;
}
/**
* return list of the number of deadline miss for each task
* @return list of the number of deadline miss
*/
public int[] getDeadlineMissList(){
int[] counts = new int[schedules.length];
int count = 0;
// tasks
for (int t=0; t<schedules.length; t++) {
if (!inTargets(t+1)) continue;
if (schedules[t] == null) continue;
// executions
for (int e = 0; e < schedules[t].length; e++) {
Schedule schedule = schedules[t][e];
int diff = schedule.finishedTime - schedule.deadline;
// Deadline missed
if (diff > 0) {
counts[t] += 1;
}
}
}
return counts;
}
/**
* get distribution of E-D for each task
* @return list of deadline miss counts
*/
public CountMap[] getExecutionDistList(){
CountMap[] counts = new CountMap[schedules.length];
// tasks
for (int t=0; t<schedules.length; t++) {
if (!inTargets(t+1)) continue;
if (schedules[t] == null) continue;
counts[t] = new CountMap();
// executions
for (int e = 0; e < schedules[t].length; e++) {
Schedule schedule = schedules[t][e];
int diff = schedule.finishedTime - schedule.deadline;
if (counts[t].containsKey(diff)){
counts[t].put(diff, counts[t].get(diff)+1);
}
else{
counts[t].put(diff, 1);
}
}
}
return counts;
}
}
| 7,392 | 21.539634 | 104 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/arrivals/SolutionPrinter.java | package lu.uni.svv.PriorityAssignment.arrivals;
import java.util.List;
import java.util.logging.Level;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.uma.jmetal.util.JMetalLogger;
public class SolutionPrinter {
private GAWriter wFitness;
private GAWriter wMaximum;
private int cycle;
public SolutionPrinter(int nTask, int cycle){
this.cycle = cycle;
init_fitness();
init_maximum(nTask);
}
public void print(List<ArrivalsSolution> population, int iter){
print_fitness(population, iter);
print_maximum(population, iter);
}
public void close() {
if (wFitness != null)
wFitness.close();
if (wMaximum != null)
wMaximum.close();
}
private void init_fitness(){
// Title
String title = "Cycle,Iteration,Fitness,DeadlineMiss";
wFitness = new GAWriter("_fitness/fitness_phase1.csv", Level.INFO, title, null, true);
}
private void print_fitness(List<ArrivalsSolution> population, int iter){
ArrivalsSolution bestSolution = population.get(0);
double fitness = bestSolution.getObjective(0);
StringBuilder sb = new StringBuilder();
sb.append(cycle);
sb.append(",");
sb.append(iter);
sb.append(",");
sb.append(String.format("%e", fitness));
sb.append(",");
sb.append(bestSolution.getAttribute("DeadlineMiss"));
wFitness.info(sb.toString());
}
private void init_maximum(int nTasks){
// title
StringBuilder sb = new StringBuilder();
sb.append("Cycle,Iteration,");
for(int num=0; num<nTasks; num++){
sb.append(String.format("Task%d",num+1));
if (num+1 < nTasks)
sb.append(",");
}
wMaximum = new GAWriter("_maximums/maximums_phase1.csv", Level.FINE, sb.toString(), null, true);
}
private void print_maximum(List<ArrivalsSolution> population, int iter) {
// get maximums from best individual
int[] maximums = (int[])population.get(0).getAttribute("Maximums");
// generate text
StringBuilder sb = new StringBuilder();
sb.append(cycle);
sb.append(",");
sb.append(iter);
sb.append(",");
int x=0;
for (; x < maximums.length - 1; x++) {
sb.append(maximums[x]);
sb.append(',');
}
sb.append(maximums[x]);
wMaximum.info(sb.toString());
}
public void saveExpendedInfo(ArrivalsSolution _solution)
{
// Save Results -->
// _details/solution/{solutionID}.txt
// _details/Narrivals/{solutionID}.csv
// print out a solution info.
String filename = String.format("/_details/solution/%d.json", _solution.ID);
_solution.store(filename);
// sampleing information
filename = String.format("/_details/Narrivals/%d.csv", _solution.ID);
GAWriter writer = new GAWriter(filename, Level.INFO, null);
writer.info(makeArrivals(_solution));
writer.close();
}
private String makeArrivals(ArrivalsSolution _solution){
StringBuilder sb = new StringBuilder();
sb.append("TaskID,Arrivals\n");
List<Arrivals> arrivalsList = _solution.getVariables();
int tid = 1;
for (Arrivals item : arrivalsList){
sb.append(tid);
sb.append(",");
sb.append(item.size());
sb.append("\n");
tid+=1;
}
return sb.toString();
}
////////////////////////////////////////////////////////////////////////////////
// Print out intermediate results
////////////////////////////////////////////////////////////////////////////////
public void printPopulation(String title, List<ArrivalsSolution> population){
System.out.println(title);
for(ArrivalsSolution individual : population){
System.out.println("\t" + individual.toString());
}
}
}
| 3,582 | 25.540741 | 98 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/arrivals/WorstGenerator.java | package lu.uni.svv.PriorityAssignment.arrivals;
import lu.uni.svv.PriorityAssignment.priority.PriorityProblem;
import lu.uni.svv.PriorityAssignment.priority.PrioritySolution;
import lu.uni.svv.PriorityAssignment.scheduler.RTScheduler;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.task.TaskType;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Monitor;
import lu.uni.svv.PriorityAssignment.utils.RandomGenerator;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.operator.impl.selection.BinaryTournamentSelection;
import org.uma.jmetal.util.AlgorithmRunner;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.comparator.ObjectiveComparator;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Level;
public class WorstGenerator {
public static String TESTFILENAME = "test.list";
public TaskDescriptor[] Tasks;
public ArrivalProblem problem;
private GAWriter writer = null;
public List<Integer[]> priorities;
public WorstGenerator(TaskDescriptor[] input, int simulationTime, Integer[] _priorityEngineer) throws Exception
{
this(input, simulationTime, _priorityEngineer,null);
}
public WorstGenerator(TaskDescriptor[] input, int simulationTime, Integer[] _priorityEngineer, String path) throws Exception
{
// generate population
PriorityProblem problemP = new PriorityProblem(input, simulationTime, Settings.SCHEDULER);
List<PrioritySolution> P = createInitialPriorities(Settings.P2_POPULATION, _priorityEngineer, problemP);
List<Integer[]> priorities = PrioritySolution.toArrays(P);
Tasks = input;
problem = new ArrivalProblem(input, priorities, simulationTime, Settings.SCHEDULER);
if (path!=null) WorstGenerator.TESTFILENAME = path;
}
/**
* Generate sample test set
*/
public List<ArrivalsSolution> generate(int _maxNum) throws Exception {
Monitor.init();
JMetalLogger.logger.info("Creating samples...");
List<ArrivalsSolution> solutions = searchArriavls(_maxNum);
JMetalLogger.logger.info("Creating samples...Done.");
initWriter();
for (int i=0; i<solutions.size(); i++){
appendLine(solutions.get(i), i+1);
}
closeWriter();
Monitor.finish();
return solutions;
}
public List<ArrivalsSolution> searchArriavls(int _maxNum){
// Define operators
CrossoverOperator<ArrivalsSolution> crossoverOperator;
MutationOperator<ArrivalsSolution> mutationOperator;
SelectionOperator<List<ArrivalsSolution>, ArrivalsSolution> selectionOperator;
Comparator<ArrivalsSolution> comparator;
// Generate operators
List<Integer> possibleTasks = TaskDescriptor.getVaryingTasks(problem.Tasks);
crossoverOperator = new OnePointCrossover(possibleTasks, Settings.P1_CROSSOVER_PROB);
mutationOperator = new RandomTLMutation(possibleTasks, problem, Settings.P1_MUTATION_PROB);
selectionOperator = new BinaryTournamentSelection<>();
comparator = new ObjectiveComparator<>(0, ObjectiveComparator.Ordering.DESCENDING);
AbstractArrivalGA algorithm = null;
try {
// Find algorithm class
String packageName = this.getClass().getPackage().getName();
Class algorithmClass = Class.forName(packageName + ".search." + Settings.P1_ALGORITHM);
// make algorithm instance
Constructor constructor = algorithmClass.getConstructors()[0];
Object[] parameters = {0, null, problem,
Settings.P1_ITERATION, _maxNum,
crossoverOperator, mutationOperator, selectionOperator, comparator};
algorithm = (AbstractArrivalGA)constructor.newInstance(parameters);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
// execute algorithm in thread
AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm).execute();
// logging some information
System.gc();
return algorithm.getPopulation();
}
////////////////////////////////////////////////////////////////////////////////
// Initial priorities
////////////////////////////////////////////////////////////////////////////////
/**
* Create initial priority assignments
* @param maxPopulation
* @param priorityEngineer
* @param problem
* @return
*/
public List<PrioritySolution> createInitialPriorities(int maxPopulation, Integer[] priorityEngineer, PriorityProblem problem) {
List<PrioritySolution> population = new ArrayList<>(maxPopulation);
PrioritySolution individual;
for (int i = 0; i < maxPopulation; i++) {
if (i==0 && priorityEngineer!=null){
individual = new PrioritySolution(problem, priorityEngineer);
}
else {
individual = new PrioritySolution(problem);
}
population.add(individual);
}
return population;
}
////////////////////////////////////////////////////////////////////////////////
// Writing utility
////////////////////////////////////////////////////////////////////////////////
/**
* Print out to file for arrival times
*/
public void initWriter()
{
writer = new GAWriter(WorstGenerator.TESTFILENAME, Level.FINE, null);
writer.info("Index\tArrivalJSON");
}
public void appendLine(ArrivalsSolution solution, int idx) {
String line = solution.getVariablesStringInline();
if (idx==-1) idx = (int)solution.ID;
writer.write(String.format("%d\t", idx));
writer.write(line);
writer.write("\n");
}
public void closeWriter(){
writer.close();
}
}
| 5,599 | 33.355828 | 128 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/arrivals/RandomTLMutation.java | package lu.uni.svv.PriorityAssignment.arrivals;
import java.util.List;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.util.JMetalException;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.utils.RandomGenerator;
@SuppressWarnings("serial")
public class RandomTLMutation implements MutationOperator<ArrivalsSolution>
{
//This class changes only Aperiodic or Sporadic tasks that can be changeable
private double mutationProbability;
List<Integer> PossibleTasks = null;
ArrivalProblem problem = null;
RandomGenerator randomGenerator = null;
public long newValue = 0;
public int taskID = 0;
public long position = 0;
/** Constructor */
public RandomTLMutation(List<Integer> _possibleTasks, ArrivalProblem _problem, double _probability) throws JMetalException {
if (_probability < 0) {
throw new JMetalException("Mutation probability is negative: " + _probability) ;
}
if (_probability > 1) {
throw new JMetalException("Mutation probability is over 1.0: " + _probability) ;
}
this.mutationProbability = _probability ;
this.randomGenerator = new RandomGenerator() ;
PossibleTasks = _possibleTasks;
problem = _problem;
}
/* Getters and Setters */
public double getMutationProbability() {
return mutationProbability;
}
public void setMutationProbability(double mutationProbability) {
this.mutationProbability = mutationProbability;
}
/** Execute() method */
@Override
public ArrivalsSolution execute(ArrivalsSolution solution) throws JMetalException {
if (null == solution) {
throw new JMetalException("Executed RandomTLMutation with Null parameter");
}
this.newValue = -1;
this.position = -1;
this.taskID = -1;
for (int t:PossibleTasks)
{
Arrivals variable = solution.getVariableValue(t-1);
for (int a=0; a<variable.size(); a++) {
if (randomGenerator.nextDouble() >= mutationProbability) continue;
doMutation(variable, t-1, a);
}
}
return solution;
}
/** Implements the mutation operation */
private void doMutation(Arrivals arrivals, int _taskIdx, int _position)
{
// execute mutation
long curValue = arrivals.get(_position);
long lastValue = 0;
if ( _position>=1 ) lastValue = arrivals.get(_position-1);
TaskDescriptor T = problem.Tasks[_taskIdx];
// make a new value
// only non-periodic tasks changes because we filtered in early stage
long newValue = lastValue + randomGenerator.nextLong(T.MinIA, T.MaxIA);;
// propagate changed values
long delta = newValue - curValue;
curValue += delta;
arrivals.set(_position, curValue);
// modify nextValues following range constraint
for (int x = _position+1; x< arrivals.size(); x++) {
long nextValue = arrivals.get(x);
if ( (nextValue >= T.MinIA + curValue) && (nextValue <= T.MaxIA + curValue) ) break;
arrivals.set(x, nextValue+delta);
curValue = nextValue+delta;
}
// Maximum Constraint
// if the current value is over Maximum time quanta, remove the value
// otherwise, save the result at the same place
for (int x = arrivals.size()-1; x>=0; x--) {
if (arrivals.get(x) <= problem.SIMULATION_TIME)
break;
arrivals.remove(x);
}
// Maximum Constraint
lastValue = arrivals.get(arrivals.size()-1);
if (lastValue + T.MaxIA < problem.SIMULATION_TIME)
{
arrivals.add(lastValue + randomGenerator.nextLong(T.MinIA, T.MaxIA));
}
return;
}
} | 3,452 | 28.767241 | 125 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/arrivals/SampleGenerator.java | package lu.uni.svv.PriorityAssignment.arrivals;
import lu.uni.svv.PriorityAssignment.scheduler.RTScheduler;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.task.TaskType;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.RandomGenerator;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.uma.jmetal.util.JMetalLogger;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
public class SampleGenerator {
public static String TESTFILENAME = "test.list";
public TaskDescriptor[] Tasks;
public ArrivalProblem problem;
private GAWriter writer = null;
public SampleGenerator(TaskDescriptor[] input, int simulationTime) throws Exception
{
this(input, simulationTime, null);
}
public SampleGenerator(ArrivalProblem problem) throws Exception
{
Tasks = problem.Tasks;
this.problem = problem;
}
public SampleGenerator(TaskDescriptor[] input, int simulationTime, String path) throws Exception
{
Tasks = input;
problem = new ArrivalProblem(input, null, simulationTime, Settings.SCHEDULER);
if (path!=null) SampleGenerator.TESTFILENAME = path;
}
/**
* Generate sample test set
*/
public List<ArrivalsSolution> generateRandom(int maxNum, boolean addMin, boolean addMax, boolean addMiddle) throws Exception {
initWriter();
List<ArrivalsSolution> solutions = new ArrayList<>();
// generate random solutions
JMetalLogger.logger.info("Creating samples...");
int count = 0;
while (count<maxNum) {
count++;
ArrivalsSolution.ARRIVAL_OPTION option = ArrivalsSolution.ARRIVAL_OPTION.RANDOM;
if (addMin && count==1) option = ArrivalsSolution.ARRIVAL_OPTION.MIN;
if (addMax && count==2) option = ArrivalsSolution.ARRIVAL_OPTION.MAX;
if (addMiddle && count==3) option = ArrivalsSolution.ARRIVAL_OPTION.MIDDLE;
// Create solution and save to the file
ArrivalsSolution solution = new ArrivalsSolution(problem, option);
solutions.add(solution);
appendLine(solution, count);
JMetalLogger.logger.info(String.format("Created sample [%d/%d]", count, maxNum));
}
JMetalLogger.logger.info("Creating samples...Done.");
closeWriter();
return solutions;
}
public List<ArrivalsSolution> generateAdaptive(int maxNum, int nCandidate, boolean extremePoints) {
initWriter();
JMetalLogger.logger.info("Creating samples...");
List<ArrivalsSolution> population = new ArrayList<>();
if (extremePoints && maxNum > 2) {
ArrivalsSolution solution = new ArrivalsSolution(problem, ArrivalsSolution.ARRIVAL_OPTION.MIN);
population.add(solution);
appendLine(solution, 1);
JMetalLogger.logger.info(String.format("Created sample [%d/%d] -- minimum arrivals", population.size(), maxNum));
solution = new ArrivalsSolution(problem, ArrivalsSolution.ARRIVAL_OPTION.MAX);
population.add(solution);
appendLine(solution, 2);
JMetalLogger.logger.info(String.format("Created sample [%d/%d] -- maximum arrivals", population.size(), maxNum));
}
// generate remaining solutions
while(population.size()<maxNum){
// create candidates
List<ArrivalsSolution> candidates = new ArrayList<>();
for(int x=0; x<nCandidate; x++){
candidates.add(new ArrivalsSolution(problem, ArrivalsSolution.ARRIVAL_OPTION.TASK));
}
// calculate minimum distance (select maximum)
double dist = 0.0;
int index = -1;
if (population.size()==0){
// if there is no comparable individuals, select randomly
RandomGenerator rand = new RandomGenerator();
index = rand.nextInt(0, candidates.size()-1);
}
else {
for (int x = 0; x < nCandidate; x++) {
double d = this.getMinDistance(candidates.get(x), population);
if (d > dist) {
dist = d;
index = x;
}
}
}
// select maximum distance
ArrivalsSolution solution = candidates.get(index);
population.add(solution);
appendLine(solution, population.size());
JMetalLogger.logger.info(String.format("Created sample [%d/%d]", population.size(), maxNum));
}
JMetalLogger.logger.info("Creating samples...Done.");
closeWriter();
return null;
}
public double getMinDistance(ArrivalsSolution candidate, List<ArrivalsSolution> pop) {
int[] vec1 = candidate.getReprVariables();
double min = Double.MAX_VALUE;
for (ArrivalsSolution s:pop){
double dist = this.euclidean(vec1, s.getReprVariables());
if (dist<min){
min = dist;
}
}
return min;
}
public double euclidean(int[] vec1, int[] vec2) {
double dist = 0;
for (int x=0; x<vec1.length; x++){
int t = vec2[x] - vec1[x];
dist += t*t;
}
dist = Math.sqrt(dist);
return dist;
}
////////////////////////////////////////////////////////////////////////////////
// Writing utility
////////////////////////////////////////////////////////////////////////////////
/**
* Print out to file for arrival times
*/
public void initWriter()
{
writer = new GAWriter(SampleGenerator.TESTFILENAME, Level.FINE, null);
writer.info("Index\tArrivalJSON");
}
public void appendLine(ArrivalsSolution solution, int idx) {
String line = solution.getVariablesStringInline();
if (idx==-1) idx = (int)solution.ID;
writer.write(String.format("%d\t", idx));
writer.write(line);
writer.write("\n");
}
public void closeWriter(){
writer.close();
}
////////////////////////////////////////////////////////////////////////////////
// test function
////////////////////////////////////////////////////////////////////////////////
public double valid(List<ArrivalsSolution> pop) {
double[] dists = new double[pop.size()];
for (int x=0; x<pop.size(); x++){
int[] vec1 = pop.get(x).getReprVariables();
double min = Double.MAX_VALUE;
for (int y=0; y<pop.size(); y++){
if (x==y) continue;
double dist = this.euclidean(vec1, pop.get(y).getReprVariables());
if (dist<min){
min = dist;
}
}
dists[x] = min;
}
double avg = mean(dists);
double std = calculateSD(avg, dists);
System.out.println(String.format("Valid dist = avg: %.2f, std: %.2f", avg, std));
return 0;
}
public double mean(double arrays[]) {
double sum = 0.0;
for(double num : arrays) {
sum += num;
}
return sum/arrays.length;
}
public double calculateSD(double mean, double arrays[]) {
double standardDeviation = 0.0;
for(double num: arrays) {
standardDeviation += Math.pow(num - mean, 2);
}
return Math.sqrt(standardDeviation/arrays.length);
}
public double calculateAvg(ArrivalsSolution solution){
int[] vars = solution.getReprVariables();
int avg =0;
int cnt = 0;
for(int x=0; x<vars.length; x++){
if (Tasks[x].Type == TaskType.Periodic) continue;
avg += vars[x];
cnt ++;
}
avg = avg / cnt;
return avg;
}
/**
* Test code for simple generator
* @param args
* @throws Exception
*/
public static void main(String args[]) throws Exception{
// Environment Settings
Settings.update(args);
GAWriter.init(null, true);
// load input
TaskDescriptor[] input = TaskDescriptor.loadFromCSV(Settings.INPUT_FILE, Settings.TIME_MAX, Settings.TIME_QUANTA);
// Set SIMULATION_TIME
int simulationTime = 0;
if (Settings.TIME_MAX == 0) {
long[] periodArray = new long[input.length];
for(int x=0; x<input.length; x++){
periodArray[x] = input[x].Period;
}
simulationTime = (int) RTScheduler.lcm(periodArray);
if (simulationTime<0) {
System.out.println("Cannot calculate simulation time");
return;
}
}
else{
simulationTime = (int) (Settings.TIME_MAX * (1/Settings.TIME_QUANTA));
if (Settings.EXTEND_SIMULATION_TIME) {
long max_deadline = TaskDescriptor.findMaximumDeadline(input);
simulationTime += max_deadline;
}
}
Settings.TIME_MAX = simulationTime;
// initialze static objects
ArrivalsSolution.initUUID();
SampleGenerator generator = new SampleGenerator(input, simulationTime);
// List<ArrivalsSolution> pop = generator.generateRandom(10, true, true, true);
List<ArrivalsSolution> pop = generator.generateAdaptive(10, 10, false);
for (ArrivalsSolution i:pop){
int[] vars = i.getReprVariables();
StringBuilder sb = new StringBuilder();
sb.append(String.format("%6d : ",i.ID));
sb.append("[");
for (int x=0; x<vars.length; x++){
if (input[x].Type == TaskType.Periodic) continue;
sb.append(String.format("%3d, ",vars[x]));
}
sb.append(String.format("], avg: %.2f", generator.calculateAvg(i)));
System.out.println(sb.toString());
}
generator.valid(pop);
}
}
| 8,625 | 28.440273 | 128 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/arrivals/ArrivalProblem.java | package lu.uni.svv.PriorityAssignment.arrivals;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.logging.Level;
import lu.uni.svv.PriorityAssignment.scheduler.Schedule;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import org.uma.jmetal.problem.impl.AbstractGenericProblem;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.scheduler.RTScheduler;
import lu.uni.svv.PriorityAssignment.scheduler.ScheduleCalculator;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import lu.uni.svv.PriorityAssignment.utils.ListUtil;
import org.uma.jmetal.util.JMetalLogger;
/**
* Class Responsibility
* - Definition of the problem to solve
* - Basic environments (This is included the definition of the problem)
* - An interface to create a solution
* - A method to evaluate a solution
*/
@SuppressWarnings("serial")
public class ArrivalProblem extends AbstractGenericProblem<ArrivalsSolution> {
// Internal Values
public int SIMULATION_TIME; // Total simulation time // to treat all time values as integer
public TaskDescriptor[] Tasks; // Task information
public List<Integer[]> Priorities; // Priority list
private Class schedulerClass; // scheduler will be used to evaluate chromosome
/**
* Constructor
* Load input data and setting environment of experiment
* @param _tasks
* @param _schedulerName
*/
public ArrivalProblem(TaskDescriptor[] _tasks, List<Integer[]> _priorities, int _simulationTime, String _schedulerName) throws NumberFormatException, IOException{
// Set environment of this problem.
this.SIMULATION_TIME = _simulationTime;
this.Tasks = _tasks;
this.Priorities = _priorities;
this.setName("");
this.setNumberOfVariables(this.Tasks.length);
this.setNumberOfObjectives(1); //Single Objective Problem
// Create Scheduler instance
try {
String packageName = this.getClass().getPackage().getName();
packageName = packageName.substring(0, packageName.lastIndexOf("."));
this.schedulerClass = Class.forName(packageName + ".scheduler." + _schedulerName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
}
/**
* set a list of priorities to evaluate a solution
* @param _priorities
*/
public void setPriorities(List<Integer[]> _priorities) {
this.Priorities = _priorities;
}
/**
* create solution interface
* Delegate this responsibility to Solution Class.
*/
@Override
public ArrivalsSolution createSolution() {
return new ArrivalsSolution(this);
}
/**
* evaluate solution interface
*/
@Override
public void evaluate(ArrivalsSolution _solution) {
//Prepare scheduler
RTScheduler scheduler = null;
Constructor constructor = schedulerClass.getConstructors()[0];
Object[] parameters = {this.Tasks, SIMULATION_TIME};
try {
Arrivals[] arrivals = _solution.toArray();
double[] fitnessList = new double[Priorities.size()];
int[] deadlineList = new int[Priorities.size()];
int[][] maximums = new int[Priorities.size()][];
String[] deadlineStrings = new String[Priorities.size()];
for(int x=0; x<this.Priorities.size(); x++){
// run Scheduler
scheduler = (RTScheduler)constructor.newInstance(parameters);
scheduler.run(arrivals, Priorities.get(x));
// make result
ScheduleCalculator calculator = new ScheduleCalculator(scheduler.getResult(), Settings.TARGET_TASKS);
fitnessList[x] = calculator.distanceMargin(false);
deadlineList[x] = calculator.checkDeadlineMiss();
maximums[x] = calculator.getMaximumExecutions();
// if (Priorities.size()>1) {
// JMetalLogger.logger.info(String.format("\t\tScheduling test has done [%d/%d]", x + 1, Priorities.size()));
// }
if (deadlineList[x]>0){
String header = String.format("%d,",x);
deadlineStrings[x] = calculator.getDeadlineMiss(header);
}
// for debug
if (Settings.PRINT_DETAILS) {
storeForDebug(_solution, scheduler.getResult(), _solution.ID, x);
}
}
// save fitness information
int idx = selectedFitnessValue(fitnessList);
_solution.setObjective(0, mergeFitnessValues(fitnessList));
_solution.setAttribute("DeadlineMiss", mergeDeadlineMiss(deadlineList));
_solution.setAttribute("FitnessIndex", idx);
_solution.setAttribute("Maximums", maximums[idx]);
_solution.setAttribute("DMString", deadlineStrings[idx]);
_solution.setAttribute("FitnessList", fitnessList);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
System.exit(1);
}
}
/**
* calculate fitness value among multiple fitness values
* @param list
* @return
*/
private double mergeFitnessValues(double[] list){
double fitness = 0.0;
if (Settings.P1_GROUP_FITNESS.compareTo("maximum")==0)
fitness = list[ListUtil.maximumIdx(list)];
else if (Settings.P1_GROUP_FITNESS.compareTo("minimum")==0)
fitness = list[ListUtil.minimumIdx(list)];
else // average
fitness = ListUtil.average(list);
return fitness;
}
/**
* check how many deadline miss are occurred among multiple fitness values
* @param deadlineList
* @return
*/
public int mergeDeadlineMiss(int[] deadlineList){
int sumDM = 0;
for (int x=0; x<deadlineList.length; x++){
sumDM += deadlineList[x];
}
return sumDM;
}
/**
* select index calculated fitness value among multiple fitness values
* @param list
* @return
*/
private int selectedFitnessValue(double[] list){
int idx = 0;
if (Settings.P1_GROUP_FITNESS.compareTo("maximum")==0)
idx = ListUtil.maximumIdx(list);
else if (Settings.P1_GROUP_FITNESS.compareTo("minimum")==0)
idx = ListUtil.minimumIdx(list);
else // average
idx = ListUtil.averageIdx(list);
return idx;
}
/**
* print function for debugging
* @param solution
* @param schedules
* @param sID
* @param pID
*/
public void storeForDebug(ArrivalsSolution solution, Schedule[][] schedules, long sID, int pID){
String filename = String.format("_arrivals1/sol%d_prio%d.json", sID, pID);
solution.store(filename);
filename = String.format("_schedules1/sol%d_prio%d.json", sID, pID);
Schedule.printSchedules(filename, schedules);
// convert priority
Integer[] prios = Priorities.get(pID);
StringBuilder sb = new StringBuilder();
sb.append("[ ");
for (int x=0; x < prios.length; x++) {
sb.append(prios[x]);
if (x!=(prios.length-1))
sb.append(", ");
}
sb.append(" ]");
// store priority
filename = String.format("_priorities1/sol%d_prio%d.json", sID, pID);
GAWriter writer = new GAWriter(filename, Level.FINE, null);
writer.info(sb.toString());
writer.close();
}
}
| 6,868 | 30.654378 | 163 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/arrivals/AbstractArrivalGA.java | package lu.uni.svv.PriorityAssignment.arrivals;
import lu.uni.svv.PriorityAssignment.utils.Monitor;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.uma.jmetal.algorithm.impl.AbstractGeneticAlgorithm;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.problem.Problem;
import org.uma.jmetal.util.JMetalLogger;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@SuppressWarnings("serial")
public abstract class AbstractArrivalGA extends AbstractGeneticAlgorithm<ArrivalsSolution, ArrivalsSolution> {
protected int maxIterations;
protected int iterations;
protected Comparator<ArrivalsSolution> comparator;
protected SolutionPrinter printer;
protected List<ArrivalsSolution> initials;
protected long startTime;
/**
* Constructor
*/
public AbstractArrivalGA(int _cycle,
List<ArrivalsSolution> _initial,
Problem<ArrivalsSolution> problem,
int maxIterations, int populationSize,
CrossoverOperator<ArrivalsSolution> crossoverOperator,
MutationOperator<ArrivalsSolution> mutationOperator,
SelectionOperator<List<ArrivalsSolution>, ArrivalsSolution> selectionOperator,
Comparator<ArrivalsSolution> comparator)
{
super(problem);
setMaxPopulationSize(populationSize);
this.maxIterations = maxIterations;
this.crossoverOperator = crossoverOperator;
this.mutationOperator = mutationOperator;
this.selectionOperator = selectionOperator;
this.comparator = comparator;
this.initials = _initial;
this.printer = new SolutionPrinter(problem.getNumberOfVariables(), _cycle);
this.startTime = System.currentTimeMillis();
}
//////////////////////////////////////////////////////////////////////////////////////////
// Execution algorithm
//////////////////////////////////////////////////////////////////////////////////////////
@Override
public void run() {
List<ArrivalsSolution> offspringPopulation;
List<ArrivalsSolution> matingPopulation;
population = (initials==null)?createInitialPopulation():initials;
population = evaluatePopulation(population);
initProgress();
while (!isStoppingConditionReached()) {
matingPopulation = selection(population);
offspringPopulation = reproduction(matingPopulation);
offspringPopulation = evaluatePopulation(offspringPopulation);
population = replacement(population, offspringPopulation);
updateProgress();
}
printer.close();
}
@Override
protected boolean isStoppingConditionReached() {
if (Settings.TIME_LIMITATION != 0){
long ts = System.currentTimeMillis();
return (ts-this.startTime) > Settings.TIME_LIMITATION;
}
else{
return (iterations >= maxIterations);
}
}
@Override
protected List<ArrivalsSolution> evaluatePopulation(List<ArrivalsSolution> population) {
Monitor.start("evaluateP1", true);
// Add logging message
ArrivalProblem problem = (ArrivalProblem)this.problem;
int count =0;
for (ArrivalsSolution solution : population) {
count += 1;
problem.evaluate(solution);
// if (Settings.PRINT_DETAILS)
// printer.saveExpendedInfo(solution);
// String msg = String.format("[%s] Evaluated solution [%d/%d] with %d priorities", getName(), count, population.size(), problem.Priorities.size());
// JMetalLogger.logger.info(msg);
}
Monitor.end("evaluateP1", true);
Monitor.updateMemory();
return population;
}
@Override
public void initProgress() {
// Add logging message and start iteration from 0
iterations = 0;
// JMetalLogger.logger.info("["+ getName() +"] initialized population");
if (Settings.PRINT_FITNESS) {
Collections.sort(getPopulation(), comparator);
printer.print(getPopulation(), iterations);
}
}
@Override
public void updateProgress() {
// Add logging message and garbage collection
iterations++;
JMetalLogger.logger.info(String.format("[%s] iteration: %d", getName(), iterations));
if (Settings.PRINT_FITNESS) {
Collections.sort(getPopulation(), comparator);
printer.print(getPopulation(), iterations);
}
System.gc();
}
//////////////////////////////////////////////////////////////////////////////////////////
// Properties
//////////////////////////////////////////////////////////////////////////////////////////
@Override
public ArrivalsSolution getResult() {
// Same code with library SSGA code
Collections.sort(getPopulation(), comparator);
return getPopulation().get(0);
}
}
| 4,687 | 32.014085 | 150 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/arrivals/Arrivals.java | package lu.uni.svv.PriorityAssignment.arrivals;
import java.util.ArrayList;
/**
* This is a wrapper class
* We use ArrayList of Integer as ArrivalTimeList
*/
public class Arrivals extends ArrayList<Long> {
/**
*
*/
private static final long serialVersionUID = 1L;
// reference https://programming.guide/java/generic-array-creation.html
// sentence, to make a generic array
}
| 394 | 18.75 | 72 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/arrivals/ArrivalsSolution.java | package lu.uni.svv.PriorityAssignment.arrivals;
import java.io.*;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.uma.jmetal.solution.Solution;
import org.uma.jmetal.solution.impl.AbstractGenericSolution;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.task.TaskType;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import org.uma.jmetal.util.pseudorandom.JMetalRandom;
/**
* Class Responsibility
* - A method to create a solution
* - A method to copy a solution
* So, this class need to reference Problem object
*/
@SuppressWarnings("serial")
public class ArrivalsSolution extends AbstractGenericSolution<Arrivals, ArrivalProblem> {//implements Solution<Integer>{
public enum ARRIVAL_OPTION {RANDOM, MIN, MAX, MIDDLE, TASK, LIMIT_MIN, LIMIT_MAX, FIXED}
/**
* Static varibles and functions
*/
private static long UUID = 1L;
public static void initUUID(){
ArrivalsSolution.UUID = 1L;
}
protected JMetalRandom random;
/**
* varibles and functions
*/
public long ID = 0L;
/**
* Create solution following Testing problem
* @param _problem
*/
public ArrivalsSolution(ArrivalProblem _problem)
{
this(_problem, ARRIVAL_OPTION.RANDOM, 0);
}
/**
* Create solution following Testing problem
* @param _problem
*/
public ArrivalsSolution(ArrivalProblem _problem, ARRIVAL_OPTION _arrivalOption)
{
this(_problem, _arrivalOption, 0);
}
public ArrivalsSolution(ArrivalProblem _problem, ARRIVAL_OPTION _arrivalOption, double rate)
{
super(_problem);
this.random = JMetalRandom.getInstance();
ID = ArrivalsSolution.UUID++;
//Encoding chromosomes
for (int x = 0; x < problem.getNumberOfVariables(); x++) {
this.setVariableValue(x, this.createRandomList(x, _arrivalOption, rate));
}
}
public ArrivalsSolution(ArrivalProblem _problem, List<Arrivals> _variables)
{
super(_problem);
this.random = JMetalRandom.getInstance();
ID = ArrivalsSolution.UUID++;
//Encoding chromosomes
for(int i = 0; i < this.problem.getNumberOfVariables(); ++i) {
this.setVariableValue(i, (Arrivals)_variables.get(i).clone());
}
}
public ArrivalsSolution(ArrivalProblem _problem, Arrivals[] _variables)
{
super(_problem);
this.random = JMetalRandom.getInstance();
ID = ArrivalsSolution.UUID++;
//Encoding chromosomes
for(int i = 0; i < this.problem.getNumberOfVariables(); ++i) {
this.setVariableValue(i, (Arrivals)_variables[i].clone());
}
}
/**
* Create a Gene (a factor of Chromosomes) for each task
* @param _index: task index
* @param _option: generating option
* @return
*/
private Arrivals createRandomList(int _index, ARRIVAL_OPTION _option, double _rate) {
Arrivals list = new Arrivals();
TaskDescriptor T = problem.Tasks[_index];
long arrival=0;
long interval=0;
// create arrival time table for periodic task
if (T.Type == TaskType.Periodic) {
// we gives phase time to arrival time at the starting point
if (Settings.ALLOW_OFFSET_RANGE)
arrival = this.random.nextInt(0, T.Offset);
else
arrival = T.Offset;
interval = T.Period;
}
else{
switch(_option){
case RANDOM: interval = this.random.nextInt(T.MinIA, T.MaxIA); break;
case MIN: interval = T.MinIA; break;
case MAX: interval = T.MaxIA; break;
case MIDDLE: interval = T.MinIA + (T.MaxIA - T.MinIA)/2; break;
case TASK: interval = this.random.nextInt(T.MinIA, T.MaxIA); break;
case FIXED: interval = (int)((T.MaxIA - T.MinIA) * _rate + T.MinIA); break;
case LIMIT_MIN:
int rateRange = (int)((T.MaxIA-T.MinIA)*_rate);
interval = this.random.nextInt(T.MinIA, T.MinIA+rateRange);
break;
case LIMIT_MAX:
rateRange = (int)((T.MaxIA-T.MinIA)*_rate);
interval = this.random.nextInt(T.MaxIA - rateRange, T.MaxIA);
break;
}
arrival = interval;
}
while(arrival <= problem.SIMULATION_TIME) {
list.add(arrival); // Input first
if (T.Type != TaskType.Periodic && _option==ARRIVAL_OPTION.RANDOM){
interval = this.random.nextInt(T.MinIA, T.MaxIA);
}
arrival += interval;
}
return list;
}
//////////////////////////////////////////////////////////////////////
// implementing functions from interface
//////////////////////////////////////////////////////////////////////
/**
* copy of this solution
* all values of objectives are initialized by 0 (This means the solution is not evaluated)
*/
@Override
public Solution<Arrivals> copy() {
return new ArrivalsSolution(this.problem, this.getVariables());
}
@Override
public Map<Object, Object> getAttributes() {
return this.attributes;
}
//////////////////////////////////////////////////////////////////////
// convert variables to string
//////////////////////////////////////////////////////////////////////
@Override
@SuppressWarnings("resource")
public String getVariableValueString(int index) {
Arrivals aVariable = this.getVariableValue(index);
StringBuilder sb = new StringBuilder();
Formatter fmt = new Formatter(sb);
fmt.format("[");
for(int i=0; i< aVariable.size(); i++) {
fmt.format("%d", aVariable.get(i));
if ( aVariable.size() > (i+1) )
sb.append(",");
}
fmt.format("]");
return sb.toString();
}
public String getVariablesStringInline(){
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int x=0; x < this.getNumberOfVariables(); x++) {
sb.append(this.getVariableValueString(x));
if (x!=(this.getNumberOfVariables()-1))
sb.append(", ");
}
sb.append("]");
return sb.toString();
}
public String getVariablesString() {
StringBuilder sb = new StringBuilder();
sb.append("[\n");
for (int x=0; x < this.getNumberOfVariables(); x++) {
sb.append("\t");
sb.append(this.getVariableValueString(x));
if (x!=(this.getNumberOfVariables()-1))
sb.append(",");
sb.append("\n");
}
sb.append("]");
return sb.toString();
}
public int[] getReprVariables() {
int[] repr = new int[this.getNumberOfVariables()];
for (int x=0; x < this.getNumberOfVariables(); x++) {
if (problem.Tasks[x].Type==TaskType.Periodic)
repr[x] = problem.Tasks[x].Period;
else {
double avg = 0;
Arrivals arrivals = this.getVariableValue(x);
long prev = 0;
for(int t=0; t<arrivals.size(); t++){
long val = arrivals.get(t);
avg += (val - prev);
prev = val;
}
repr[x] = (int)avg/arrivals.size(); //Math.toIntExact((Long) this.getVariableValue(x).get(0));
}
}
return repr;
}
public String getSolutionString(int _rep_size, int[] _priorities) {
StringBuilder sb = new StringBuilder();
sb.append("[ \n");
for (int x=0; x < this.getNumberOfVariables(); x++) {
sb.append("Task");
sb.append(this.problem.Tasks[x].ID);
sb.append("(");
sb.append(_priorities[x]);
sb.append("): ");
sb.append(this.getLineVariableValueString(x, _rep_size));
sb.append("\n");
}
sb.append(" ]");
return sb.toString();
}
/**
* Make a string with Variable values, this show rep_size numbers.
* @param index
* @param rep_size
* @return
*/
@SuppressWarnings("resource")
public String getCustomVariableValueString(int index, int rep_size) {
Arrivals aVariable = this.getVariableValue(index);
StringBuilder sb = new StringBuilder();
Formatter fmt = new Formatter(sb);
fmt.format("P%02d: ", index);
for(int i=0; i< MIN(aVariable.size(), rep_size); i++) {
fmt.format("%d", aVariable.get(i));
if ( aVariable.size() > (i+1) )
sb.append(",");
}
if(aVariable.size() > rep_size )
fmt.format("...(more %d)\n", (aVariable.size() - rep_size));
else
fmt.format("\n");
return sb.toString();
}
public String getCustomVariableValueString(int rep_size) {
StringBuilder sb = new StringBuilder();
for (int x=0; x < this.getNumberOfVariables(); x++) {
sb.append(this.getCustomVariableValueString(x, rep_size));
}
return sb.toString();
}
/**
* This function returns string of values in the Variables
* @param rep_size
* @return
*/
public String getLineVariableValueString(int rep_size) {
StringBuilder sb = new StringBuilder();
sb.append("[ ");
for (int x=0; x < this.getNumberOfVariables(); x++) {
sb.append(this.getLineVariableValueString(x, rep_size));
if (x!=(this.getNumberOfVariables()-1))
sb.append(", ");
}
sb.append(" ]");
return sb.toString();
}
/**
* This function returns string of values in a specific Variable
* @param index
* @param rep_size
* @return
*/
public String getLineVariableValueString(int index, int rep_size) {
Arrivals aVariable = this.getVariableValue(index);
StringBuilder sb = new StringBuilder();
Formatter fmt = new Formatter(sb);
fmt.format("[");
for(int i=0; i< MIN(aVariable.size(), rep_size); i++) {
fmt.format("%d", aVariable.get(i));
if ( aVariable.size() > (i+1) )
sb.append(",");
}
if(aVariable.size() > rep_size )
fmt.format("...(more %d)]", (aVariable.size() - rep_size));
else
fmt.format("]");
return sb.toString();
}
private final int MIN(int a, int b){
return (a>b)? b:a;
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("ArrivalsSolution{ ID(");
sb.append(ID);
sb.append("), Arrivals: [");
sb.append(getVariablesSize());
sb.append("], fitness: ");
sb.append(getObjective(0));
sb.append(", ");
if (attributes.containsKey("DeadlineMiss")) {
sb.append("DM: ");
sb.append(attributes.get("DeadlineMiss"));
sb.append(", ");
}
sb.append(attributes);
sb.append("}");
return sb.toString();
}
public String getVariablesSize(){
StringBuilder sb = new StringBuilder();
for (Arrivals item : getVariables()){
sb.append(item.size());
sb.append(",");
}
return sb.toString();
}
////////////////////////////////////////////////////////////////////////
// Loading and saving ArrivalsSolution
////////////////////////////////////////////////////////////////////////
public void store(String _filepath){
GAWriter writer = new GAWriter(_filepath, Level.FINE, null);
writer.info(this.getVariablesString());
writer.close();
}
/**
* [Static] Generate ArrivalsSolution from file
* @param _problem
* @param _jsonText
* @return
*/
public static ArrivalsSolution loadFromJSONString(ArrivalProblem _problem, String _jsonText){
List<Arrivals> variables = null;
try {
JSONParser parser = new JSONParser();
JSONArray json = (JSONArray) parser.parse(_jsonText);
variables = new ArrayList<Arrivals>(json.size());
for (int i = 0; i < json.size(); i++) {
JSONArray array = (JSONArray) json.get(i);
Arrivals arrivals = new Arrivals();
for (Object item : array) {
arrivals.add(((Long)item).longValue());
}
variables.add(arrivals);
}
}
catch (ParseException e){
e.printStackTrace();
}
return new ArrivalsSolution(_problem, variables);
}
public static ArrivalsSolution loadFromJSON(ArrivalProblem _problem, String _filepath){
List<Arrivals> variables = null;
FileReader reader = null;
try {
reader = new FileReader(_filepath);
JSONParser parser = new JSONParser();
JSONArray json = (JSONArray) parser.parse(reader);
variables = new ArrayList<Arrivals>(json.size());
for (int i = 0; i < json.size(); i++) {
JSONArray array = (JSONArray) json.get(i);
Arrivals arrivals = new Arrivals();
for (Object item : array) {
arrivals.add(((Long)item).longValue());
}
variables.add(arrivals);
}
}
catch (IOException | ParseException e){
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return new ArrivalsSolution(_problem, variables);
}
////////////////////////////////////////////////////////////////////////
// Exchange internal variables
////////////////////////////////////////////////////////////////////////
/**
* convert to arrays
* @return
*/
public Arrivals[] toArray(){
Arrivals[] arrivals = new Arrivals[this.getNumberOfVariables()];
for (int y=0; y<this.getNumberOfVariables(); y++){
arrivals[y] = this.getVariableValue(y);
}
return arrivals;
}
/**
* Convert solutions to list of arrivals
* @param solutions
* @return
*/
public static List<Arrivals[]> toArrays(List<ArrivalsSolution> solutions) {
List<Arrivals[]> arrivals = new ArrayList<>();
for(ArrivalsSolution solution: solutions){
arrivals.add(solution.toArray());
}
return arrivals;
}
@Override
protected void finalize() throws Throwable{
for (int i=0; i<this.getNumberOfVariables(); i++)
this.setVariableValue(i, null);
this.attributes.clear();
this.attributes = null;
super.finalize();
// Utils.printMemory("delete "+this.ID);
}
}
| 13,172 | 25.828921 | 120 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/arrivals/OnePointCrossover.java | package lu.uni.svv.PriorityAssignment.arrivals;
import java.util.ArrayList;
import java.util.List;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.util.JMetalException;
import lu.uni.svv.PriorityAssignment.utils.RandomGenerator;
@SuppressWarnings("serial")
public class OnePointCrossover implements CrossoverOperator<ArrivalsSolution>
{
private double crossoverProbability;
private RandomGenerator randomGenerator;
private List<Integer> PossibleTasks = null;
/** Constructor */
public OnePointCrossover(List<Integer> _possibleTasks, double crossoverProbability) {
if (crossoverProbability < 0) {
throw new JMetalException("Crossover probability is negative: " + crossoverProbability) ;
}
this.crossoverProbability = crossoverProbability;
this.randomGenerator = new RandomGenerator();
PossibleTasks = _possibleTasks;
}
/* Getter and Setter */
public double getCrossoverProbability() {
return crossoverProbability;
}
public void setCrossoverProbability(double crossoverProbability) {
this.crossoverProbability = crossoverProbability;
}
@Override
public int getNumberOfRequiredParents() {
return 2;
}
@Override
public int getNumberOfGeneratedChildren() {
return 2;
}
/* Executing */
@Override
public List<ArrivalsSolution> execute(List<ArrivalsSolution> solutions)
{
if (solutions == null) {
throw new JMetalException("Null parameter") ;
} else if (solutions.size() != 2) {
throw new JMetalException("There must be two parents instead of " + solutions.size()) ;
}
return doCrossover(crossoverProbability, solutions.get(0), solutions.get(1)) ;
}
/** doCrossover method */
public List<ArrivalsSolution> doCrossover(double probability, ArrivalsSolution parent1, ArrivalsSolution parent2)
{
List<ArrivalsSolution> offspring = new ArrayList<ArrivalsSolution>(2);
offspring.add((ArrivalsSolution) parent1.copy()) ;
offspring.add((ArrivalsSolution) parent2.copy()) ;
if (randomGenerator.nextDouble() < probability) {
//System.out.println("[Debug] Executed crossover");
// 1. Get the total number of bits
int totalNumberOfVariables = parent1.getNumberOfVariables();
// 2. Get crossover point
int crossoverPoint = randomGenerator.nextInt(1, PossibleTasks.size() - 1);
crossoverPoint = PossibleTasks.get(crossoverPoint);
//System.out.println(String.format("Crossover Point: Task %d", crossoverPoint));
// 3. Exchange values
for (int x = crossoverPoint-1; x < totalNumberOfVariables; x++) {
offspring.get(0).setVariableValue(x, (Arrivals)parent2.getVariableValue(x).clone());
offspring.get(1).setVariableValue(x, (Arrivals)parent1.getVariableValue(x).clone());
}
}
return offspring;
}
}
| 2,752 | 29.252747 | 114 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/arrivals/search/SSGA.java | package lu.uni.svv.PriorityAssignment.arrivals.search;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import lu.uni.svv.PriorityAssignment.arrivals.AbstractArrivalGA;
import lu.uni.svv.PriorityAssignment.arrivals.ArrivalsSolution;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.problem.Problem;
@SuppressWarnings("serial")
public class SSGA extends AbstractArrivalGA {
/**
* Constructor
*
* @param _cycle
* @param _initial
* @param problem
* @param maxIterations
* @param populationSize
* @param crossoverOperator
* @param mutationOperator
* @param selectionOperator
* @param comparator
*/
public SSGA(int _cycle, List<ArrivalsSolution> _initial, Problem<ArrivalsSolution> problem, int maxIterations, int populationSize, CrossoverOperator<ArrivalsSolution> crossoverOperator, MutationOperator<ArrivalsSolution> mutationOperator, SelectionOperator<List<ArrivalsSolution>, ArrivalsSolution> selectionOperator, Comparator<ArrivalsSolution> comparator) {
super(_cycle, _initial, problem, maxIterations, populationSize, crossoverOperator, mutationOperator, selectionOperator, comparator);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Execution algorithm
//////////////////////////////////////////////////////////////////////////////////////////
@Override
protected List<ArrivalsSolution> replacement(List<ArrivalsSolution> population, List<ArrivalsSolution> offspringPopulation) {
// Same code with library SSGA code
Collections.sort(population, comparator);
int worstSolutionIndex = population.size() - 1;
if (comparator.compare(population.get(worstSolutionIndex), offspringPopulation.get(0)) > 0) {
population.remove(worstSolutionIndex);
population.add(offspringPopulation.get(0));
}
return population;
}
@Override
protected List<ArrivalsSolution> reproduction(List<ArrivalsSolution> matingPopulation) {
// Same code with library SSGA code
List<ArrivalsSolution> offspringPopulation = new ArrayList(1);
List<ArrivalsSolution> parents = new ArrayList(2);
parents.add(matingPopulation.get(0));
parents.add(matingPopulation.get(1));
List<ArrivalsSolution> offspring = (List)this.crossoverOperator.execute(parents);
this.mutationOperator.execute(offspring.get(0));
offspringPopulation.add(offspring.get(0));
return offspringPopulation;
}
@Override
protected List<ArrivalsSolution> selection(List<ArrivalsSolution> population) {
// modified not to select the same solutions
List<ArrivalsSolution> matingPopulation = new ArrayList<>(2);
int i=0;
long prev_id = -1;
while (i<2){
ArrivalsSolution solution = selectionOperator.execute(population);
long id = solution.ID;
if (prev_id==id) continue;
prev_id = id;
matingPopulation.add(solution);
i += 1;
}
return matingPopulation;
}
@Override
public String getName() {
return "ssGA";
}
@Override
public String getDescription() {
return "Steady-State Genetic Algorithm";
}
}
| 3,191 | 32.957447 | 361 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/arrivals/search/FullReplaceGA.java | package lu.uni.svv.PriorityAssignment.arrivals.search;
import lu.uni.svv.PriorityAssignment.arrivals.AbstractArrivalGA;
import lu.uni.svv.PriorityAssignment.arrivals.ArrivalsSolution;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.problem.Problem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@SuppressWarnings("serial")
public class FullReplaceGA extends AbstractArrivalGA {
/**
* Constructor
*
* @param _cycle
* @param _initial
* @param problem
* @param maxIterations
* @param populationSize
* @param crossoverOperator
* @param mutationOperator
* @param selectionOperator
* @param comparator
*/
public FullReplaceGA(int _cycle, List<ArrivalsSolution> _initial, Problem<ArrivalsSolution> problem, int maxIterations, int populationSize, CrossoverOperator<ArrivalsSolution> crossoverOperator, MutationOperator<ArrivalsSolution> mutationOperator, SelectionOperator<List<ArrivalsSolution>, ArrivalsSolution> selectionOperator, Comparator<ArrivalsSolution> comparator) {
super(_cycle, _initial, problem, maxIterations, populationSize, crossoverOperator, mutationOperator, selectionOperator, comparator);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Execution algorithm
//////////////////////////////////////////////////////////////////////////////////////////
@Override
protected List<ArrivalsSolution> replacement(List<ArrivalsSolution> population, List<ArrivalsSolution> offspringPopulation) {
// Full replacement
return offspringPopulation;
}
@Override
public String getName() {
return "FullReplaceGA";
}
@Override
public String getDescription() {
return "Fully Replacement Genetic Algorithm (Algorithm 20)";
}
}
| 1,916 | 32.631579 | 370 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/arrivals/search/GenerationalGA.java | package lu.uni.svv.PriorityAssignment.arrivals.search;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import lu.uni.svv.PriorityAssignment.arrivals.AbstractArrivalGA;
import lu.uni.svv.PriorityAssignment.arrivals.ArrivalsSolution;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.problem.Problem;
@SuppressWarnings("serial")
public class GenerationalGA extends AbstractArrivalGA {
/**
* Constructor
*
* @param _cycle
* @param _initial
* @param problem
* @param maxIterations
* @param populationSize
* @param crossoverOperator
* @param mutationOperator
* @param selectionOperator
* @param comparator
*/
public GenerationalGA(int _cycle, List<ArrivalsSolution> _initial, Problem<ArrivalsSolution> problem, int maxIterations, int populationSize, CrossoverOperator<ArrivalsSolution> crossoverOperator, MutationOperator<ArrivalsSolution> mutationOperator, SelectionOperator<List<ArrivalsSolution>, ArrivalsSolution> selectionOperator, Comparator<ArrivalsSolution> comparator) {
super(_cycle, _initial, problem, maxIterations, populationSize, crossoverOperator, mutationOperator, selectionOperator, comparator);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Execution algorithm
//////////////////////////////////////////////////////////////////////////////////////////
@Override
protected List<ArrivalsSolution> replacement(List<ArrivalsSolution> population, List<ArrivalsSolution> offspringPopulation) {
// Same code with library GenerationalGeneticAlgorithm code
Collections.sort(population, this.comparator);
offspringPopulation.add(population.get(0));
offspringPopulation.add(population.get(1));
Collections.sort(offspringPopulation, this.comparator);
offspringPopulation.remove(offspringPopulation.size() - 1);
offspringPopulation.remove(offspringPopulation.size() - 1);
return offspringPopulation;
}
@Override
public String getName() {
return "GenerationalGA";
}
@Override
public String getDescription() {
return "Generational Genetic Algorithm";
}
}
| 2,236 | 34.507937 | 371 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/arrivals/search/RandomSearch.java | package lu.uni.svv.PriorityAssignment.arrivals.search;
import lu.uni.svv.PriorityAssignment.arrivals.AbstractArrivalGA;
import lu.uni.svv.PriorityAssignment.arrivals.ArrivalsSolution;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.problem.Problem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@SuppressWarnings("serial")
public class RandomSearch extends AbstractArrivalGA {
/**
* Constructor
*
* @param _cycle
* @param _initial
* @param problem
* @param maxIterations
* @param populationSize
* @param crossoverOperator
* @param mutationOperator
* @param selectionOperator
* @param comparator
*/
public RandomSearch(int _cycle, List<ArrivalsSolution> _initial, Problem<ArrivalsSolution> problem, int maxIterations, int populationSize, CrossoverOperator<ArrivalsSolution> crossoverOperator, MutationOperator<ArrivalsSolution> mutationOperator, SelectionOperator<List<ArrivalsSolution>, ArrivalsSolution> selectionOperator, Comparator<ArrivalsSolution> comparator) {
super(_cycle, _initial, problem, maxIterations, populationSize, crossoverOperator, mutationOperator, selectionOperator, comparator);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Execution algorithm
//////////////////////////////////////////////////////////////////////////////////////////
@Override
protected List<ArrivalsSolution> replacement(List<ArrivalsSolution> population, List<ArrivalsSolution> offspringPopulation) {
// Same code with library SSGA code
Collections.sort(population, comparator);
int worstSolutionIndex = population.size() - 1;
if (comparator.compare(population.get(worstSolutionIndex), offspringPopulation.get(0)) > 0) {
population.remove(worstSolutionIndex);
population.add(offspringPopulation.get(0));
}
return population;
}
@Override
public List<ArrivalsSolution> reproduction(List<ArrivalsSolution> matingPopulation) {
// Random Search
List<ArrivalsSolution> offsprings = new ArrayList<>(1);
ArrivalsSolution solution = problem.createSolution();
offsprings.add(solution);
return offsprings;
}
@Override
protected List<ArrivalsSolution> selection(List<ArrivalsSolution> population) {
// do not selection
return null;
}
@Override
public String getName() {
return "RS";
}
@Override
public String getDescription() {
return "Random Search";
}
}
| 2,574 | 32.881579 | 369 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/priority/AbstractPrioritySearch.java | package lu.uni.svv.PriorityAssignment.priority;
import java.util.*;
import java.util.logging.Level;
import lu.uni.svv.PriorityAssignment.utils.Monitor;
import lu.uni.svv.PriorityAssignment.utils.UniqueList;
import org.uma.jmetal.algorithm.multiobjective.nsgaii.NSGAII;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.operator.impl.selection.RankingAndCrowdingSelection;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.evaluator.SolutionListEvaluator;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
public class AbstractPrioritySearch extends NSGAII<PrioritySolution> {
protected int cycle;
protected int iterations;
protected int maxIterations;
protected List<PrioritySolution> initial;
protected static UniqueList searchedList = null;
protected GAWriter fwriter;
protected GAWriter mwriter;
protected ExternalFitness externalFitness = null;
protected long maxFact = 0;
protected long startTime = 0;
public AbstractPrioritySearch(int _cycle,
List<PrioritySolution> _initial, Map<String, Object> _best, PriorityProblem _problem,
int _maxIterations, int _populationSize, int _matingPoolSize, int _offspringPopulationSize,
CrossoverOperator<PrioritySolution> _crossoverOperator,
MutationOperator<PrioritySolution> _mutationOperator,
SelectionOperator<List<PrioritySolution>, PrioritySolution> _selectionOperator,
SolutionListEvaluator<PrioritySolution> _evaluator)
{
super(_problem, _maxIterations*_populationSize, _populationSize, _matingPoolSize, _offspringPopulationSize,
_crossoverOperator, _mutationOperator, _selectionOperator, _evaluator);
this.cycle = _cycle;
this.initial = _initial;
this.iterations = 0;
this.maxIterations = _maxIterations;
this.evaluations = 0;
// _best parameter is used for the external fitness so sub-class should set this parameter
this.maxFact = factorial(_problem.Tasks.length);
if (searchedList==null) {
searchedList = new UniqueList();
}
this.startTime = System.currentTimeMillis();
}
public static void init(){
searchedList = new UniqueList();
}
@Override
public void run() {
// Need to define in each algorithm
}
@Override
protected List<PrioritySolution> evaluatePopulation(List<PrioritySolution> population) {
JMetalLogger.logger.info("\t\tcalculating internal fitness (iteration "+iterations+")");
Monitor.start("evaluateP2", true);
population = this.evaluator.evaluate(population, this.getProblem());
Monitor.end("evaluateP2", true);
Monitor.updateMemory();
return population;
}
public void externalProcess(List<PrioritySolution> _population, boolean _withOrigin){
Monitor.start("external", true);
if (externalFitness==null) return;
if(_withOrigin){
externalFitness.evaluateOrigin(_population, 0, 0);
}
else{
externalFitness.run(_population, cycle, iterations);
}
Monitor.end("external", true);
Monitor.updateMemory();
}
/**
* create offsprings randomly
* @return
*/
public List<PrioritySolution> createRandomOffspirings() {
List<PrioritySolution> offspringPopulation = new ArrayList(this.offspringPopulationSize);
for(int i = 0; i < this.offspringPopulationSize; i++) {
PrioritySolution individual = this.problem.createSolution();
offspringPopulation.add(individual);
}
return offspringPopulation;
}
/**
* Create initial priority assignments
* @return
*/
@Override
public List<PrioritySolution> createInitialPopulation() {
List<PrioritySolution> population = new ArrayList<>(this.maxPopulationSize);
PrioritySolution individual;
for (int i = 0; i < this.maxPopulationSize; i++) {
if (initial != null && i < initial.size()){
individual = initial.get(i);
}
else {
individual = this.problem.createSolution();
}
population.add(individual);
}
return population;
}
@Override
protected boolean isStoppingConditionReached() {
// return this.evaluations >= this.maxEvaluations;
if (Settings.TIME_LIMITATION != 0){
long ts = System.currentTimeMillis();
return (ts-this.startTime) > Settings.TIME_LIMITATION;
}
else{
return this.iterations > this.maxIterations;
}
}
@Override
protected List<PrioritySolution> replacement(List<PrioritySolution> _population, List<PrioritySolution> _offspringPopulation) {
List<PrioritySolution> jointPopulation = new ArrayList();
jointPopulation.addAll(_population);
jointPopulation.addAll(_offspringPopulation);
RankingAndCrowdingSelection<PrioritySolution> rankingAndCrowdingSelection = new RankingAndCrowdingSelection(this.getMaxPopulationSize(), this.dominanceComparator);
return rankingAndCrowdingSelection.execute(jointPopulation);
}
protected void printPopulation(String _title, List<PrioritySolution> _population){
System.out.println(_title);
for(PrioritySolution individual : _population){
String plist = individual.getVariablesString();
double fd = -individual.getObjective(0);
double fc = -individual.getObjective(1);
String output = String.format("\tID(%d): %s (F_C: %.0f, F_D: %e)", individual.ID , plist, fc, fd);
System.out.println(output);
}
}
@Override
protected void initProgress() {
super.initProgress();
// JMetalLogger.logger.info("["+getName()+"] Iteration "+iterations+": created initial population: "+evaluations);
if (Settings.PRINT_FITNESS) {
print_fitness();
print_maximum();
}
iterations = 1;
}
@Override
protected void updateProgress() {
super.updateProgress();
// JMetalLogger.logger.info("["+getName()+"] Iteration "+iterations+" (evaluated solutions: "+evaluations+")");
if (Settings.PRINT_FITNESS) {
print_fitness();
print_maximum();
}
iterations += 1;
System.gc();
}
////////////////////////////////////////////////////////////////////////////////
// Properties
////////////////////////////////////////////////////////////////////////////////
public Map<String, Object> getBest(){
return externalFitness.best;
}
public List<PrioritySolution> getPopulation(){
return population;
}
// get Best Pareto, parent NSGAII algorithm have this method
// public List<PrioritySolution> getResult(){
// return population;
// }
////////////////////////////////////////////////////////////////////////////////
// Utils
////////////////////////////////////////////////////////////////////////////////
protected int factorial(int _num){
int ret = 1;
for(int x=2; x<=_num; x++){
ret = ret * x;
if (ret < 0) {
ret = Integer.MAX_VALUE;
break;
}
}
return ret;
}
////////////////////////////////////////////////////////////////////////////////
// Print out intermediate results
////////////////////////////////////////////////////////////////////////////////
protected void init_fitness(){
if (externalFitness==null){
// When this class works for only NSGA mode, it produce the results like the external fitness results
// iteration value will be located at Cycle and the Iteration value will be set 2.
String title = "Cycle,Iteration,Distance,SolutionIndex,SolutionID,Schedulability,Satisfaction,DeadlineMiss,Rank,CrowdingDistance";
fwriter = new GAWriter("_fitness/fitness_external.csv", Level.INFO, title, null, true);
}
else{
String title = "Cycle,Iteration,SolutionIndex,SolutionID,Schedulability,Satisfaction,DeadlineMiss,Rank,CrowdingDistance"; //
fwriter = new GAWriter("_fitness/fitness_phase2.csv", Level.INFO, title, null, true);
}
}
protected void print_fitness(){
StringBuilder sb = new StringBuilder();
int idx =0;
List<PrioritySolution> pop = getPopulation();
for (PrioritySolution solution: pop){
// if (!(rank==null || (int)rank==0)) continue;
int rank = 0;
Object rankClass = org.uma.jmetal.util.solutionattribute.impl.DominanceRanking.class;
if (solution.hasAttribute(rankClass))
rank = (Integer)solution.getAttribute(rankClass);
if (externalFitness==null && rank!=0) continue;
double cDistance = 0.0;
Object distClass = org.uma.jmetal.util.solutionattribute.impl.CrowdingDistance.class;
if (solution.hasAttribute(distClass))
cDistance = (Double)solution.getAttribute(distClass);
int dms = (int)solution.getAttribute("DeadlineMiss");
if (externalFitness==null) {
sb.append(iterations); //actual iteration value is located at Cycle
sb.append(",");
sb.append((iterations==0)?0:2); //result Iteration value set 2 (for the analysis purpose)
sb.append(",");
sb.append(0); // distance
sb.append(",");
}
else{
sb.append(cycle);
sb.append(",");
sb.append(iterations);
sb.append(",");
}
sb.append(idx);
sb.append(",");
sb.append(solution.ID);
sb.append(",");
sb.append(String.format("%e",-solution.getObjective(0)));
sb.append(",");
sb.append(-solution.getObjective(1));
sb.append(",");
sb.append(dms);
sb.append(",");
sb.append(rank);
sb.append(",");
sb.append(cDistance);
sb.append("\n");
idx ++;
// if (dms[fIndex] > 0){
// printDeadlines(solution, iterations, idx);
// }
}
fwriter.write(sb.toString());
}
public void init_maximum(){
// title
StringBuilder sb = new StringBuilder();
sb.append("Cycle,Iteration,");
for(int num=0; num<problem.getNumberOfVariables(); num++){
sb.append(String.format("Task%d",num+1));
if (num+1 < problem.getNumberOfVariables())
sb.append(",");
}
mwriter = new GAWriter(String.format("_maximums/maximums_phase2.csv"), Level.FINE, sb.toString(), null, true);
}
public void print_maximum() {
// get maximums from best individual
int[] maximums = (int[])getPopulation().get(0).getAttribute("Maximums");
// generate text
StringBuilder sb = new StringBuilder();
sb.append(cycle);
sb.append(",");
sb.append(iterations);
sb.append(",");
int x=0;
for (; x < maximums.length - 1; x++) {
sb.append(maximums[x]);
sb.append(',');
}
sb.append(maximums[x]);
mwriter.info(sb.toString());
}
protected void close() {
if (mwriter != null)
mwriter.close();
if (fwriter != null)
fwriter.close();
if (externalFitness != null)
externalFitness.close();
}
protected void printDeadlines(PrioritySolution _solution, int _iter, int _idx){
if (_solution==null) return ;
String text = (String)_solution.getAttribute("DMString");
String title = "ArrivalID,Task,Execution,DeadlineMiss";
GAWriter writer = new GAWriter(String.format("_deadlines/deadlines_phase2_iter%d_sol%d_rankIdx%d.csv", _iter, _solution.ID, _idx), Level.INFO, title, null);
writer.info(text);
writer.close();
text = _solution.getVariablesString();
writer = new GAWriter(String.format("_priorities_rank/priorities_phase2_iter%d_sol%d_rankIdx%d.csv", _iter, _solution.ID, _idx), Level.INFO, "", null);
writer.info(text);
writer.close();
}
}
| 10,990 | 30.135977 | 165 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/priority/ConstrantsEvaluator.java | package lu.uni.svv.PriorityAssignment.priority;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.task.TaskType;
import java.util.List;
public class ConstrantsEvaluator {
/**
* Assuming that the greater value of priority has the higher priority level,
* This function calculates the distance of priority level of aperiodic task
* from the lowest priority level among periodic tasks
* The higher return value represents the higher extent of the constraint satisfaction
* @param solution
* @param tasks
* @return
*/
public static double calculate(PrioritySolution solution, TaskDescriptor[] tasks){
List<Integer> priorities = solution.getVariables();
// calculate lowest priority among periodic tasks
int lowest = Integer.MAX_VALUE;
for (int x=0; x<priorities.size(); x++){
if(tasks[x].Type!= TaskType.Aperiodic && lowest > priorities.get(x)){
lowest = priorities.get(x);
}
}
// calculate distance lowest priority of priority task and each aperiodic task
int priorityDistance = 0;
for (int x=0; x<priorities.size(); x++){
if(tasks[x].Type==TaskType.Aperiodic){
int diff = lowest - priorities.get(x);
priorityDistance += diff;
}
}
return priorityDistance;
}
}
| 1,299 | 31.5 | 87 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/priority/PriorityProblem.java | package lu.uni.svv.PriorityAssignment.priority;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import lu.uni.svv.PriorityAssignment.scheduler.RTScheduler;
import lu.uni.svv.PriorityAssignment.task.TaskType;
import org.uma.jmetal.problem.Problem;
import org.uma.jmetal.util.JMetalLogger;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
/**
* Class Responsibility
* - Definition of the problem to solve
* - Basic environments (This is included the definition of the problem)
* - An interface to create a solution
* - A method to evaluate a solution
* @author jaekwon.lee
*/
@SuppressWarnings("serial")
public class PriorityProblem implements Problem<PrioritySolution> {
private int NumberOfVariables = 0;
private int NumberOfObjectives = 0;
private int NumberOfAperiodics = 0;
private List<Double[]> ranges = null;
public TaskDescriptor[] Tasks;
public int SimulationTime;
public String SchedulerName;
/**
* Constructor
* * Load input data and setting environment of experiment
* @throws NumberFormatException
* @throws IOException
*/
public PriorityProblem(TaskDescriptor[] _tasks, int _simulationTime, String _schedulerType) throws NumberFormatException, IOException{
// Set environment of this problem.
this.Tasks = _tasks;
this.NumberOfVariables = _tasks.length;
this.NumberOfObjectives = 2; //Multi Objective Problem
this.SimulationTime = _simulationTime;
this.SchedulerName = _schedulerType;
// counting the number of aperiodic tasks
for(TaskDescriptor task:this.Tasks){
if (task.Type== TaskType.Aperiodic) this.NumberOfAperiodics++;
}
this.calculateRange(_tasks, _simulationTime);
}
protected void calculateRange(TaskDescriptor[] _tasks, int _simulationTime){
this.ranges = new ArrayList<>();
// get log normalization
double minFitness = TaskDescriptor.getMinFitness(_tasks, _simulationTime);
double maxFitness = TaskDescriptor.getMaxFitness(_tasks, _simulationTime);
this.ranges.add(new Double[]{minFitness, maxFitness});
// get range of condition
int nTasks = _tasks.length;
int nAperiodics = TaskDescriptor.getNumberOfAperiodics(_tasks);
int maxCondition = (nAperiodics * (nAperiodics+1))/2;
int maxValue = (nTasks-1);
int minValue = (nTasks-nAperiodics)-1;
int minCondition = (minValue*(minValue+1))/2 - (maxValue*(maxValue+1))/2;
this.ranges.add(new Double[]{(double)minCondition, (double)maxCondition});
JMetalLogger.logger.info(String.format("[Fitness 1] min: %e, max: %e", ranges.get(0)[0], ranges.get(0)[1]));
JMetalLogger.logger.info(String.format("[Fitness 2] min: %.0f, max: %.0f", ranges.get(1)[0], ranges.get(1)[1]));
}
public TaskDescriptor[] getTasks(){ return Tasks;}
public Double[] getFitnessRange(int objectiveID){
return this.ranges.get(objectiveID);
}
@Override
public int getNumberOfVariables() {
return NumberOfVariables;
}
@Override
public int getNumberOfObjectives() {
return NumberOfObjectives;
}
@Override
public int getNumberOfConstraints() {
return 0;
}
@Override
public String getName() {
return null;
}
@Override
public void evaluate(PrioritySolution prioritySolution) {
}
/**
* Class Responsibility :create solution interface
* Delegate this responsibility to Solution Class.
*/
@Override
public PrioritySolution createSolution() {
return new PrioritySolution(this);
}
public int getNumberOfAperiodics(){
return NumberOfAperiodics;
}
public RTScheduler getScheduler(){
// Load a scheduler class
Class schedulerClass = null;
try {
String packageName = this.getClass().getPackage().getName();
packageName = packageName.substring(0, packageName.lastIndexOf("."));
schedulerClass = Class.forName(packageName + ".scheduler." + this.SchedulerName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
// System.exit(1);
}
if (schedulerClass==null) return null;
// Make an instance
Constructor constructor = schedulerClass.getConstructors()[0];
Object[] parameters = {this.Tasks, this.SimulationTime};
RTScheduler scheduler = null;
try {
scheduler = (RTScheduler) constructor.newInstance(parameters);
}catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return scheduler;
}
}
| 4,441 | 28.223684 | 135 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/priority/ExternalFitness.java | package lu.uni.svv.PriorityAssignment.priority;
import java.util.*;
import java.util.logging.Level;
import lu.uni.svv.PriorityAssignment.arrivals.Arrivals;
import lu.uni.svv.PriorityAssignment.scheduler.Schedule;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import lu.uni.svv.PriorityAssignment.utils.StoreManger;
import org.apache.commons.math3.ml.distance.EuclideanDistance;
import org.uma.jmetal.operator.impl.selection.RankingAndCrowdingSelection;
import org.uma.jmetal.util.solutionattribute.impl.DominanceRanking;
import org.uma.jmetal.util.solutionattribute.impl.CrowdingDistance;
import org.uma.jmetal.util.SolutionListUtils;
import org.uma.jmetal.util.comparator.DominanceComparator;
public class ExternalFitness {
public int maxPopulation = 0;
public Map<String, Object> best;
protected GAWriter writer;
protected GAWriter writerEx;
protected PriorityProblem problem;
protected PrioritySolutionEvaluator evaluator;
protected DominanceComparator<PrioritySolution> dominanceComparator;
public ExternalFitness(PriorityProblem _problem, PrioritySolutionEvaluator _evaluator, Map<String, Object> _best, int _maxPopulation){
this(_problem, _evaluator, _best, _maxPopulation, new DominanceComparator());
}
public ExternalFitness(PriorityProblem _problem, PrioritySolutionEvaluator _evaluator, Map<String, Object> _best, int _maxPopulation, DominanceComparator<PrioritySolution> _dominanceComparator){
problem = _problem;
maxPopulation = _maxPopulation;
dominanceComparator = _dominanceComparator;
evaluator = _evaluator;
this.best = _best;
if (this.best == null){
this.best = new HashMap<>();
this.best.put("Distance", (Double)0.0);
this.best.put("Pareto", new ArrayList<PrioritySolution>());
this.best.put("Population", new ArrayList<PrioritySolution>());
}
init_external_fitness();
init_external_fitness_ex();
}
public void summaryPop(String name, List<PrioritySolution> _pop){
int[] ids = new int[_pop.size()];
for (int x=0; x< _pop.size(); x++){
ids[x] = (int)_pop.get(x).ID;
}
Arrays.sort(ids);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%15s(%2d): [",name, _pop.size()));
for(int x=0; x<_pop.size(); x++){
sb.append(String.format("%4d, ", ids[x]));
}
sb.append("]");
System.out.println(sb.toString());
}
/**
* Evaluate a population
* @param _population
* @param _cycle
* @param _iterations
* @return
*/
public double evaluateOrigin(List<PrioritySolution> _population, int _cycle, int _iterations){
if( _population == null) return 0;
// copy population
List<PrioritySolution> empty = new ArrayList<>();
List<PrioritySolution> jointP = difference(_population, empty, true);
((PrioritySolutionEvaluator)this.evaluator).evaluateForExternal(jointP, this.problem);
// Calculate ranking for external fitness
RankingAndCrowdingSelection<PrioritySolution> rncSelection = null;
int popSize = (Settings.NOLIMIT_POPULATION)?jointP.size():this.maxPopulation;
if (jointP.size()<popSize){
popSize = jointP.size();
}
rncSelection = new RankingAndCrowdingSelection(popSize, this.dominanceComparator); //this.getMaxPopulationSize()
List<PrioritySolution> selected = rncSelection.execute(jointP);
// find new best pareto
double distance = calculateDistance(selected);
print_external_fitness(_cycle, _iterations, selected, distance);
print_external_fitness_ex(_cycle, _iterations, selected, distance);
return distance;
}
//////////////////////////////////////////////////////////////////////////////
// External fitness functions
//////////////////////////////////////////////////////////////////////////////
public double run(List<PrioritySolution> _population, int _cycle, int _iterations){
if( _population == null) return 0;
// copy population and recalculate fitness values
List<PrioritySolution> lastPopulation = (List<PrioritySolution>)best.get("Population");
// select individuals which are not evaluated before
List<PrioritySolution> jointP = difference(_population, lastPopulation, true);
((PrioritySolutionEvaluator)this.evaluator).evaluateForExternal(jointP, this.problem);
// Add evaluated individuals into joint population
jointP.addAll( lastPopulation );
// Calculate ranking for external fitness
RankingAndCrowdingSelection<PrioritySolution> rncSelection = null;
int popSize = (Settings.NOLIMIT_POPULATION)?jointP.size():this.maxPopulation;
if (jointP.size()<popSize){
popSize = jointP.size();
}
rncSelection = new RankingAndCrowdingSelection(popSize, this.dominanceComparator); //this.getMaxPopulationSize()
List<PrioritySolution> selected = rncSelection.execute(jointP);
List<PrioritySolution> pareto = SolutionListUtils.getNondominatedSolutions(selected);
// find new best pareto
double distance = calculateDistance(pareto);
best.put("Distance", distance);
best.put("Pareto", pareto);
best.put("Population", selected);
best.put("Cycle", _cycle);
best.put("Iteration", _iterations);
print_external_fitness(_cycle, _iterations, pareto, distance);
print_external_fitness_ex(_cycle, _iterations, pareto, distance);
// printPopulation("Full Population", selected);
// printPopulation("Pareto", pareto);
// summaryPop("FullPopulation", jointP);
// summaryPop("Pareto", pareto);
// summaryPop("External", selected);
return distance;
}
public void close(){
if (writer != null)
writer.close();
}
protected List<PrioritySolution> intersection(List<PrioritySolution> A, List<PrioritySolution> B){
List<PrioritySolution> result = new ArrayList<>();
for (PrioritySolution a:A) {
boolean flag = false;
for(PrioritySolution b:B){
if (a.ID==b.ID){
flag=true;
break;
}
}
if (!flag) continue;
result.add(a);
}
return result;
}
protected List<PrioritySolution> difference(List<PrioritySolution> A, List<PrioritySolution> B, boolean isClone){
List<PrioritySolution> result = new ArrayList<>();
for (PrioritySolution a:A) {
boolean flag = false;
for(PrioritySolution b:B){
if (a.ID==b.ID){
flag=true;
break;
}
}
if (flag) continue;
result.add( (isClone)?a.clone():a );
}
return result;
}
protected double calculateDistance(List<PrioritySolution> _pareto){
// set ideal point (if not apply normailzed, ideal for F_C is the maximum value of F_C)
double[] ideal = new double[]{0, 0};
Double[] range = this.problem.getFitnessRange(1);
ideal[1] = range[1];
// calculate euclidian distance with ideal point
EuclideanDistance ed = new EuclideanDistance();
double[] fitnesses = null;
double minDistance = Double.MAX_VALUE;
for (int i=0; i<_pareto.size(); i++){
PrioritySolution individual = _pareto.get(i);
fitnesses = individual.getObjectives();
double distance = ed.compute(fitnesses, ideal);
if (minDistance > distance){
minDistance = distance;
}
}
return minDistance;
}
/**
* print out titles for external fitness values
*/
private void init_external_fitness(){
// Title
String title = "Cycle,Iteration,Distance,SolutionIndex,SolutionID,Schedulability,Satisfaction,DeadlineMiss,Rank,CrowdingDistance"; //
writer = new GAWriter("_fitness/fitness_external.csv", Level.INFO, title, null, true);
}
/**
* print out external fitness values for each cycle
*/
public void print_external_fitness(int cycle, int iterations, List<PrioritySolution> _pareto, double _dist){
String baseItems = String.format("%d,%d,%e",cycle, iterations, _dist);
StringBuilder sb = new StringBuilder();
int idx =0;
for (PrioritySolution solution: _pareto){
// if (!(rank==null || (int)rank==0)) continue;
int DM = (int)solution.getAttribute("DeadlineMiss");
int rank = 0;
if (solution.hasAttribute(DominanceRanking.class))
rank = (Integer)solution.getAttribute(DominanceRanking.class);
double cDistance = 0.0;
if (solution.hasAttribute(CrowdingDistance.class))
cDistance = (Double)solution.getAttribute(CrowdingDistance.class);
sb.append(baseItems);
sb.append(",");
sb.append(idx);
sb.append(",");
sb.append(solution.ID);
sb.append(",");
sb.append(String.format("%e", -solution.getObjective(0)));
sb.append(",");
sb.append(-solution.getObjective(1));
sb.append(",");
sb.append(DM);
sb.append(",");
sb.append(rank);
sb.append(",");
sb.append(cDistance);
sb.append("\n");
idx ++;
// Print out the final cycle results
if(Settings.PRINT_FINAL_DETAIL && cycle==0 && solution.ID==1) {
List<Arrivals[]> arrivals = ((PrioritySolutionEvaluator)evaluator).TestArrivalsList;
List<Schedule[][]> schedulesList = (ArrayList)solution.getAttribute("schedulesList");
for (int k=0; k< schedulesList.size(); k++){
storeForDebug(arrivals.get(k), schedulesList.get(k), solution.toArray(), solution.ID, k);
}
}
// Print out the final cycle results
if(Settings.PRINT_FINAL_DETAIL && cycle==Settings.CYCLE_NUM) {
List<Arrivals[]> arrivals = ((PrioritySolutionEvaluator)evaluator).TestArrivalsList;
List<Schedule[][]> schedulesList = (ArrayList)solution.getAttribute("schedulesList");
for (int k=0; k< schedulesList.size(); k++){
storeForDebug(arrivals.get(k), schedulesList.get(k), solution.toArray(), solution.ID, k);
}
}
}
writer.write(sb.toString());
}
/**
* print out titles for external fitness values
*/
private void init_external_fitness_ex(){
// Title
String title = "Cycle,Iteration,Distance,SolutionIndex,SolutionID,ArrivalsID,Schedulability,Satisfaction,DeadlineMiss,Rank,CrowdingDistance"; //
writerEx = new GAWriter("_fitness/fitness_external_ex.csv", Level.INFO, title, null, true);
}
/**
* print out external fitness values for each cycle (all evaluation)
*/
public void print_external_fitness_ex(int cycle, int iterations, List<PrioritySolution> _pareto, double _dist){
String baseItems = String.format("%d,%d,%e",cycle, iterations, _dist);
StringBuilder sb = new StringBuilder();
int solIdx =0;
for (PrioritySolution solution: _pareto){
// if (!(rank==null || (int)rank==0)) continue;
int rank = 0;
if (solution.hasAttribute(DominanceRanking.class))
rank = (Integer)solution.getAttribute(DominanceRanking.class);
double cDistance = 0.0;
if (solution.hasAttribute(CrowdingDistance.class))
cDistance = (Double)solution.getAttribute(CrowdingDistance.class);
int[] DM = (int[])solution.getAttribute("DeadlineList");
double[] fitnessList = (double[])solution.getAttribute("FitnessList");
for (int k=0; k< fitnessList.length; k++){
sb.append(baseItems);
sb.append(",");
sb.append(solIdx);
sb.append(",");
sb.append(solution.ID);
sb.append(",");
sb.append(k);
sb.append(",");
sb.append(String.format("%e", fitnessList[k]));
sb.append(",");
sb.append(-solution.getObjective(1));
sb.append(",");
sb.append(DM[k]);
sb.append(",");
sb.append(rank);
sb.append(",");
sb.append(cDistance);
sb.append("\n");
}
solIdx ++;
}
writerEx.write(sb.toString());
}
protected void printPopulation(String title, List<PrioritySolution> population){
System.out.println(title);
for(PrioritySolution individual : population){
String plist = individual.getVariablesString();
double fd = -individual.getObjective(0);
double fc = -individual.getObjective(1);
String output = String.format("\tID(%d): %s (F_C: %.0f, F_D: %e)", individual.ID , plist, fc, fd);
System.out.println(output);
}
}
public void storeForDebug(Arrivals[] arrivals, Schedule[][] schedules, Integer[] priorities, long sID, int aID){
String filename = String.format("_arrivalsEx/arr%d.json", aID);
StoreManger.storeArrivals(arrivals, filename);
filename = String.format("_schedulesEx/sol%d_arr%d.json", sID, aID);
Schedule.printSchedules(filename, schedules);
filename = String.format("_prioritiesEx/sol%d.json", sID);
StoreManger.storePriority(priorities, filename);
}
}
| 12,153 | 32.20765 | 195 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/priority/ExternalFitnessRandom.java | package lu.uni.svv.PriorityAssignment.priority;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.uma.jmetal.util.archive.impl.NonDominatedSolutionListArchive;
import org.uma.jmetal.util.comparator.DominanceComparator;
import java.util.*;
import java.util.logging.Level;
public class ExternalFitnessRandom extends ExternalFitness {
public ExternalFitnessRandom(PriorityProblem _problem, PrioritySolutionEvaluator _evaluator, Map<String, Object> _best, int _maxPopulation){
this(_problem, _evaluator, _best, _maxPopulation, new DominanceComparator());
}
public ExternalFitnessRandom(PriorityProblem _problem, PrioritySolutionEvaluator _evaluator, Map<String, Object> _best, int _maxPopulation, DominanceComparator<PrioritySolution> _dominanceComparator){
super(_problem, _evaluator, _best, _maxPopulation, _dominanceComparator);
}
/**
* Evaluate a population
* @param _population
* @param _cycle
* @param _iterations
* @return
*/
public double evaluateOrigin(List<PrioritySolution> _population, int _cycle, int _iterations){
if( _population == null) return 0;
// copy population
List<PrioritySolution> empty = new ArrayList<>();
List<PrioritySolution> jointP = difference(_population, empty, true);
((PrioritySolutionEvaluator)this.evaluator).evaluateForExternal(jointP, this.problem);
//TODO:: Do we need Size filter..??
int popSize = (Settings.NOLIMIT_POPULATION)?jointP.size():this.maxPopulation;
if (jointP.size()<popSize){
popSize = jointP.size();
}
NonDominatedSolutionListArchive<PrioritySolution> nonDominatedArchive =
new NonDominatedSolutionListArchive<PrioritySolution>(this.dominanceComparator);
nonDominatedArchive.addAll(jointP);
List<PrioritySolution> pareto = nonDominatedArchive.getSolutionList();
// find new best pareto
double distance = calculateDistance(pareto);
print_external_fitness(_cycle, _iterations, pareto, distance);
print_external_fitness_ex(_cycle, _iterations, pareto, distance);
return distance;
}
//////////////////////////////////////////////////////////////////////////////
// External fitness functions
//////////////////////////////////////////////////////////////////////////////
public double run(List<PrioritySolution> _population, int _cycle, int _iterations){
if( _population == null) return 0;
// copy population and recalculate fitness values
List<PrioritySolution> lastPopulation = (List<PrioritySolution>)best.get("Population");
// select individuals which are not evaluated before
List<PrioritySolution> jointP = difference(_population, lastPopulation, true);
((PrioritySolutionEvaluator)this.evaluator).evaluateForExternal(jointP, this.problem);
// Add evaluated individuals into joint population
jointP.addAll( lastPopulation );
// Calculate ranking for external fitness
NonDominatedSolutionListArchive<PrioritySolution> nonDominatedArchive = new NonDominatedSolutionListArchive<>(dominanceComparator);
nonDominatedArchive.addAll(jointP);
List<PrioritySolution> pareto = nonDominatedArchive.getSolutionList();
// find new best pareto
double distance = calculateDistance(pareto);
best.put("Distance", distance);
best.put("Pareto", pareto);
best.put("Population", pareto);
best.put("Cycle", _cycle);
best.put("Iteration", _iterations);
print_external_fitness(_cycle, _iterations, pareto, distance);
print_external_fitness_ex(_cycle, _iterations, pareto, distance);
// printPopulation("Full Population", selected);
// printPopulation("Pareto", pareto);
// summaryPop("FullPopulation", jointP);
// summaryPop("Pareto", pareto);
// summaryPop("External", selected);
return distance;
}
}
| 3,685 | 37.395833 | 201 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/priority/SwapMutation.java | package lu.uni.svv.PriorityAssignment.priority;
import java.util.List;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.JMetalLogger;
import lu.uni.svv.PriorityAssignment.utils.RandomGenerator;
@SuppressWarnings("serial")
public class SwapMutation implements MutationOperator<PrioritySolution>
{
//This class changes only Aperiodic or Sporadic tasks that can be changeable
private double mutationProbability;
RandomGenerator randomGenerator = null;
/** Constructor */
public SwapMutation(double probability) throws JMetalException {
if (probability < 0) {
throw new JMetalException("Mutation probability is negative: " + probability) ;
}
if (probability > 1) {
throw new JMetalException("Mutation probability is over 1.0: " + probability) ;
}
this.mutationProbability = probability ;
this.randomGenerator = new RandomGenerator() ;
}
/** Execute() method */
@Override
public PrioritySolution execute(PrioritySolution solution) throws JMetalException {
if (null == solution) {
throw new JMetalException("Executed SwapMutation with Null parameter");
}
List<Integer> variables = solution.getVariables();
int mutated = 0;
for(int x=0; x<solution.getNumberOfVariables(); x++){
if (randomGenerator.nextDouble() >= mutationProbability) continue;
int point1 = randomGenerator.nextInt(0, solution.getNumberOfVariables()-1);
int point2 = randomGenerator.nextInt(0, solution.getNumberOfVariables()-1);
int temp = solution.getVariableValue(point1);
solution.setVariableValue(point1, solution.getVariableValue(point2));
solution.setVariableValue(point2, temp);
mutated += 1;
}
if (mutated>1){
JMetalLogger.logger.fine("Mutated("+mutated+"): "+solution.toString());
}
return solution;
}
/** Implements the mutation operation */
private void doMutation(int[] _list, int _position) {
}
} | 1,944 | 30.370968 | 84 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/priority/PrioritySolution.java | package lu.uni.svv.PriorityAssignment.priority;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.logging.Level;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.uma.jmetal.solution.impl.AbstractGenericSolution;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
/**
* Class Responsibility
* - A method to create a solution
* - A method to copy a solution
* So, this class need to reference Problem object
* @author jaekwon.lee
*/
@SuppressWarnings("serial")
public class PrioritySolution extends AbstractGenericSolution<Integer, PriorityProblem> {//implements Solution<Integer>{
private static long UUID = 1L;
public static void initUUID(){
PrioritySolution.UUID = 1L;
}
public long ID = 0L;
public PrioritySolution(PriorityProblem _problem, boolean isEmpty) {
super(_problem);
}
/**
* Create solution following Testing problem
* @param _problem
*/
public PrioritySolution(PriorityProblem _problem)
{
super(_problem);
ID = PrioritySolution.UUID++;
List<Integer> randomSequence = new ArrayList(problem.getNumberOfVariables());
int i;
for(i = 0; i < problem.getNumberOfVariables(); ++i) {
randomSequence.add(i);
}
Collections.shuffle(randomSequence);
for(i = 0; i < this.getNumberOfVariables(); ++i) {
this.setVariableValue(i, randomSequence.get(i));
}
}
public PrioritySolution(PriorityProblem _problem, List<Integer> _priorities)
{
super(_problem);
ID = PrioritySolution.UUID++;
for(int i = 0; i < this.problem.getNumberOfVariables(); ++i) {
this.setVariableValue(i, _priorities.get(i));
}
}
public PrioritySolution(PriorityProblem _problem, Integer[] _priorities) {
super(_problem);
ID = PrioritySolution.UUID++;
for (int i = 0; i < this.problem.getNumberOfVariables(); ++i) {
this.setVariableValue(i, _priorities[i]);
}
}
public PrioritySolution(PriorityProblem _problem, String _jsonString) throws Exception{
super(_problem);
ID = PrioritySolution.UUID++;
Integer[] priorities = loadFromJSON(_jsonString);
for (int i = 0; i < this.problem.getNumberOfVariables(); ++i) {
this.setVariableValue(i, priorities[i]);
}
}
public PrioritySolution(PrioritySolution _solution) {
super(_solution.problem);
ID = _solution.ID;
for (int i = 0; i < this.problem.getNumberOfVariables(); ++i) {
this.setVariableValue(i, _solution.getVariableValue(i));
}
}
/**
* return variables as String (JSON notation)
* @return
*/
public String getVariablesString() {
StringBuilder sb = new StringBuilder();
sb.append("[ ");
int length = this.getNumberOfVariables();
for (int x=0; x < length; x++) {
sb.append(this.getVariableValue(x));
if (x!=(length-1))
sb.append(", ");
}
sb.append(" ]");
return sb.toString();
}
@Override
@SuppressWarnings("resource")
public String getVariableValueString(int index) {
return String.valueOf(getVariableValue(index));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("PrioritySolution{ ID(");
sb.append(ID);
sb.append("), ");
sb.append(getVariablesString());
sb.append(", fitness: [");
sb.append(getObjective(0));
sb.append(", ");
sb.append(getObjective(1));
sb.append("], ");
if (attributes.containsKey("DeadlineList")) {
sb.append("DM: [");
int[] dms = (int[])attributes.get("DeadlineList");
for(int i=0; i<dms.length; i++){
sb.append(dms[i]);
sb.append(",");
}
sb.append("], ");
}
sb.append(attributes);
sb.append("}");
return sb.toString();
}
/**
* store solution into file
* @param _filepath
*/
public void store(String _filepath){
GAWriter writer = new GAWriter(_filepath, Level.FINE, null);
writer.info(this.getVariablesString());
writer.close();
}
/**
* copy of this solution
* all values of objectives are initialized by 0 (This means the solution is not evaluated)
*/
@Override
public PrioritySolution copy() {
return new PrioritySolution(this.problem, getVariables());
}
public PrioritySolution clone() {
return new PrioritySolution(this);
}
@Override
public Map<Object, Object> getAttributes() {
return this.attributes;
}
public boolean hasAttribute(Object key){
return this.attributes.containsKey(key);
}
/**
* Load solution from JSON string
* @param _jsonString
* @return
*/
public Integer[] loadFromJSON(String _jsonString) throws ParseException{
Integer[] variables = null;
JSONParser parser = new JSONParser();
JSONArray json = (JSONArray) parser.parse(_jsonString);
variables = new Integer[json.size()];
for (int i = 0; i < json.size(); i++) {
variables[i] = ((Long)json.get(i)).intValue();
}
return variables;
}
@Override
protected void finalize() throws Throwable{
for (int i=0; i<this.getNumberOfVariables(); i++)
this.setVariableValue(i, null);
this.attributes.clear();
this.attributes = null;
super.finalize();
// Utils.printMemory("delete "+this.ID);
}
////////////////////////////////////////////////////////////////////////
// Exchange internal variables
////////////////////////////////////////////////////////////////////////
/**
* convert to arrays
* @return
*/
public Integer[] toArray(){
Integer[] arr = new Integer[this.getNumberOfVariables()];
for (int i=0; i<this.getNumberOfVariables(); i++)
arr[i] = this.getVariableValue(i);
return arr;
}
/**
* Convert solutions to list of arrivals
* @param solutions
* @return
*/
public static List<Integer[]> toArrays(List<PrioritySolution> solutions) {
List<Integer[]> prioritySets = new ArrayList<>();
for(PrioritySolution solution: solutions){
prioritySets.add(solution.toArray());
}
return prioritySets;
}
}
| 5,946 | 23.372951 | 120 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/priority/PrioritySolutionEvaluator.java | package lu.uni.svv.PriorityAssignment.priority;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.logging.Level;
import lu.uni.svv.PriorityAssignment.scheduler.Schedule;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import org.uma.jmetal.problem.Problem;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.evaluator.SolutionListEvaluator;
import lu.uni.svv.PriorityAssignment.arrivals.Arrivals;
import lu.uni.svv.PriorityAssignment.scheduler.RTScheduler;
import lu.uni.svv.PriorityAssignment.scheduler.ScheduleCalculator;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import lu.uni.svv.PriorityAssignment.utils.ListUtil;
public class PrioritySolutionEvaluator implements SolutionListEvaluator<PrioritySolution> {
// Internal Values
private List<Arrivals[]> ArrivalsList; // Arrivals
public List<Arrivals[]> TestArrivalsList; // Test Arrivals
private Class schedulerClass; // scheduler will be used to evaluate chromosome
public PrioritySolutionEvaluator(List<Arrivals[]> _arrivalsList, List<Arrivals[]> _testArrivalsList) throws NumberFormatException, IOException {
// Set environment of this problem.
this.ArrivalsList = _arrivalsList;
this.TestArrivalsList = _testArrivalsList;
}
@Override
public List<PrioritySolution> evaluate(List<PrioritySolution> population, Problem<PrioritySolution> problem) {
// get scheduler object
// RTScheduler.DETAIL = true;
// RTScheduler.PROOF = true;
try {
int x=0;
for(PrioritySolution solution:population){
evaluateSolution( (PriorityProblem)problem, solution, ArrivalsList, false, false, 0);
x++;
// JMetalLogger.logger.info(String.format("\tEvaluated solution [%d/%d] with %s arrivals", x, population.size(), ArrivalsList.size()));
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
System.exit(1);
}
return population;
}
public List<PrioritySolution> evaluateForExternal(List<PrioritySolution> population, Problem<PrioritySolution> problem) {
try {
int x=0;
for(PrioritySolution solution:population){
evaluateSolution( (PriorityProblem)problem, solution, TestArrivalsList, true, x==0,0);
x++;
// JMetalLogger.logger.info(String.format("\tEvaluated solution for external [%d/%d] with %s arrivals", x, population.size(), TestArrivalsList.size()));
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
System.exit(1);
}
return population;
}
public void evaluateSolution(PriorityProblem _problem, PrioritySolution solution, List<Arrivals[]> arrivalsList, boolean isSimple, boolean ext, int showingProgress)
throws IllegalAccessException, InvocationTargetException, InstantiationException {
// convert solution to priorities array
Integer[] priorities = solution.toArray();
// prepare scheduler
RTScheduler scheduler = _problem.getScheduler();;
// calculate fitness values for each arrivals
double[] fitnessList = new double[arrivalsList.size()];
int[] deadlineList = new int[arrivalsList.size()];
int[][] maximums = new int[arrivalsList.size()][];
String[] deadlineStrings = null;
if (!isSimple) {
deadlineStrings = new String[arrivalsList.size()];
}
List<Schedule[][]> schedulesList = new ArrayList<>();
for (int x=0; x< arrivalsList.size(); x++){
// run scheduler
scheduler.run(arrivalsList.get(x), priorities);
// make result
Schedule[][] schedules = scheduler.getResult();
ScheduleCalculator calculator = new ScheduleCalculator(schedules, Settings.TARGET_TASKS);
fitnessList[x] = calculator.distanceMargin(true);
deadlineList[x] = calculator.checkDeadlineMiss();
maximums[x] = calculator.getMaximumExecutions();
if (Settings.PRINT_FINAL_DETAIL)
schedulesList.add(schedules);
// for Debug
//calculator.checkBins();
if (arrivalsList.size()>1 && showingProgress!=0){
if((x+1)%showingProgress==0) {
JMetalLogger.logger.info(String.format("\t\tScheduling test has done [%d/%d]", x + 1, arrivalsList.size()));
}
}
if (!isSimple && deadlineList[x]>0){
String header = String.format("%d,",x);
deadlineStrings[x] = calculator.getDeadlineMiss(header);
}
// for debug
if (Settings.PRINT_DETAILS && ((ext==true && x==0) || solution.ID == 1)) {
storeForDebug(arrivalsList.get(x), schedules, priorities, solution.ID, x);
}
}
// String filename = String.format("_solutions2/phase2_priorities_sol%d.json", solution.ID);
// solution.store(filename);
// save fitness information
int idx = selectedFitnessValue(fitnessList);
solution.setObjective(0, -mergeFitnessValues(fitnessList));
solution.setObjective(1, -ConstrantsEvaluator.calculate(solution, _problem.Tasks));
solution.setAttribute("DeadlineMiss", mergeDeadlineMiss(deadlineList));
solution.setAttribute("FitnessIndex", idx);
solution.setAttribute("Maximums", maximums[idx]);
solution.setAttribute("FitnessList", fitnessList);
solution.setAttribute("DeadlineList", deadlineList);
if (Settings.PRINT_FINAL_DETAIL)
solution.setAttribute("schedulesList", schedulesList);
if (!isSimple) {
solution.setAttribute("DMString", deadlineStrings[idx]);
}
}
@Override
public void shutdown() {
}
/**
* calculate fitness value among multiple fitness values
* @param list
* @return
*/
public double mergeFitnessValues(double[] list){
double fitness = 0.0;
if (Settings.P2_GROUP_FITNESS.compareTo("maximum")==0)
fitness = list[ListUtil.maximumIdx(list)];
else if (Settings.P2_GROUP_FITNESS.compareTo("minimum")==0)
fitness = list[ListUtil.minimumIdx(list)];
else // average
fitness = ListUtil.average(list);
return fitness;
}
/**
* check how many deadline miss are occurred among multiple fitness values
* @param deadlineList
* @return
*/
public int mergeDeadlineMiss(int[] deadlineList){
int sumDM = 0;
for (int x=0; x<deadlineList.length; x++){
sumDM += deadlineList[x];
}
return sumDM;
}
/**
* select index calculated fitness value among multiple fitness values
* @param list
* @return
*/
public int selectedFitnessValue(double[] list){
int idx = 0;
if (Settings.P2_GROUP_FITNESS.compareTo("maximum")==0)
idx = ListUtil.maximumIdx(list);
else if (Settings.P2_GROUP_FITNESS.compareTo("minimum")==0)
idx = ListUtil.minimumIdx(list);
else // average
idx = ListUtil.averageIdx(list);
return idx;
}
/**
* print out arrivals and priorities and schedule result
* @param
* @return
*/
public void storeForDebug(Arrivals[] arrivals, Schedule[][] schedules, Integer[] priorities, long sID, int aID){
String filename = String.format("_arrivals2/sol%d_arr%d.json", sID, aID);
printArrivals(arrivals, filename);
filename = String.format("_schedules2/sol%d_arr%d.json", sID, aID);
Schedule.printSchedules(filename, schedules);
// convert priority
StringBuilder sb = new StringBuilder();
sb.append("[ ");
for (int x=0; x < priorities.length; x++) {
sb.append(priorities[x]);
if (x!=(priorities.length-1))
sb.append(", ");
}
sb.append(" ]");
// store priority
filename = String.format("_priorities2/sol%d_arr%d.json", sID, aID);
GAWriter writer = new GAWriter(filename, Level.FINE, null);
writer.info(sb.toString());
writer.close();
}
public void printArrivals(Arrivals[] arrivals, String filename){
GAWriter writer = new GAWriter(filename, Level.FINE, null);
StringBuilder sb = new StringBuilder();
Formatter fmt = new Formatter(sb);
sb.append("[\n");
for (int x=0; x < arrivals.length; x++) {
sb.append("\t");
fmt.format("[");
Arrivals item = arrivals[x];
for(int i=0; i< item.size(); i++) {
fmt.format("%d", item.get(i));
if ( item.size() > (i+1) )
sb.append(",");
}
fmt.format("]");
if (x!=(arrivals.length-1))
sb.append(",");
sb.append("\n");
}
sb.append("]");
writer.info(sb.toString());
writer.close();
}
}
| 8,299 | 31.046332 | 165 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/priority/PMXCrossover.java | package lu.uni.svv.PriorityAssignment.priority;
import java.util.ArrayList;
import java.util.List;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.pseudorandom.BoundedRandomGenerator;
import org.uma.jmetal.util.pseudorandom.JMetalRandom;
import org.uma.jmetal.util.pseudorandom.RandomGenerator;
/**
* This class allows to apply a PMX crossover operator using two parent solutions.
*
* @author Antonio J. Nebro <antonio@lcc.uma.es>
* @author Juan J. Durillo
*/
@SuppressWarnings("serial")
public class PMXCrossover implements CrossoverOperator<PrioritySolution> {
private double crossoverProbability = 1.0;
private BoundedRandomGenerator<Integer> cuttingPointRandomGenerator ;
private RandomGenerator<Double> crossoverRandomGenerator ;
/**
* Constructor
*/
public PMXCrossover(double crossoverProbability) {
this(crossoverProbability, () -> JMetalRandom.getInstance().nextDouble(), (a, b) -> JMetalRandom.getInstance().nextInt(a, b));
}
/**
* Constructor
*/
public PMXCrossover(double crossoverProbability, RandomGenerator<Double> randomGenerator) {
this(crossoverProbability, randomGenerator, BoundedRandomGenerator.fromDoubleToInteger(randomGenerator));
}
/**
* Constructor
*/
public PMXCrossover(double crossoverProbability, RandomGenerator<Double> crossoverRandomGenerator, BoundedRandomGenerator<Integer> cuttingPointRandomGenerator) {
if ((crossoverProbability < 0) || (crossoverProbability > 1)) {
throw new JMetalException("Crossover probability value invalid: " + crossoverProbability) ;
}
this.crossoverProbability = crossoverProbability;
this.crossoverRandomGenerator = crossoverRandomGenerator ;
this.cuttingPointRandomGenerator = cuttingPointRandomGenerator ;
}
/* Getters */
public double getCrossoverProbability() {
return crossoverProbability;
}
/* Setters */
public void setCrossoverProbability(double crossoverProbability) {
this.crossoverProbability = crossoverProbability;
}
/**
* Executes the operation
*
* @param parents An object containing an array of two solutions
*/
public List<PrioritySolution> execute(List<PrioritySolution> parents) {
if (null == parents) {
throw new JMetalException("Null parameter") ;
} else if (parents.size() != 2) {
throw new JMetalException("There must be two parents instead of " + parents.size()) ;
}
return doCrossover(crossoverProbability, parents) ;
}
/**
* Perform the crossover operation
*
* @param probability Crossover probability
* @param parents Parents
* @return An array containing the two offspring
*/
public List<PrioritySolution> doCrossover(double probability, List<PrioritySolution> parents) {
List<PrioritySolution> offspring = new ArrayList<>(2);
offspring.add( parents.get(0).copy() );
offspring.add( parents.get(1).copy() );
int permutationLength = parents.get(0).getNumberOfVariables();
if (crossoverRandomGenerator.getRandomValue() < probability) {
int cuttingPoint1;
int cuttingPoint2;
// STEP 1: Get two cutting points
cuttingPoint1 = cuttingPointRandomGenerator.getRandomValue(0, permutationLength - 1);
cuttingPoint2 = cuttingPointRandomGenerator.getRandomValue(0, permutationLength - 1);
while (cuttingPoint2 == cuttingPoint1)
cuttingPoint2 = cuttingPointRandomGenerator.getRandomValue(0, permutationLength - 1);
if (cuttingPoint1 > cuttingPoint2) {
int swap;
swap = cuttingPoint1;
cuttingPoint1 = cuttingPoint2;
cuttingPoint2 = swap;
}
// STEP 2: Get the subchains to interchange
int replacement1[] = new int[permutationLength];
int replacement2[] = new int[permutationLength];
for (int i = 0; i < permutationLength; i++)
replacement1[i] = replacement2[i] = -1;
// STEP 3: Interchange
for (int i = cuttingPoint1; i <= cuttingPoint2; i++) {
offspring.get(0).setVariableValue(i, parents.get(1).getVariableValue(i));
offspring.get(1).setVariableValue(i, parents.get(0).getVariableValue(i));
replacement1[parents.get(1).getVariableValue(i)] = parents.get(0).getVariableValue(i) ;
replacement2[parents.get(0).getVariableValue(i)] = parents.get(1).getVariableValue(i) ;
}
// STEP 4: Repair offspring
for (int i = 0; i < permutationLength; i++) {
if ((i >= cuttingPoint1) && (i <= cuttingPoint2))
continue;
int n1 = parents.get(0).getVariableValue(i);
int m1 = replacement1[n1];
int n2 = parents.get(1).getVariableValue(i);
int m2 = replacement2[n2];
while (m1 != -1) {
n1 = m1;
m1 = replacement1[m1];
}
while (m2 != -1) {
n2 = m2;
m2 = replacement2[m2];
}
offspring.get(0).setVariableValue(i, n1);
offspring.get(1).setVariableValue(i, n2);
}
}
return offspring;
}
@Override
public int getNumberOfRequiredParents() {
return 2 ;
}
@Override
public int getNumberOfGeneratedChildren() {
return 2;
}
} | 5,017 | 30.559748 | 162 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/priority/search/PriorityNSGAII.java | package lu.uni.svv.PriorityAssignment.priority.search;
import lu.uni.svv.PriorityAssignment.priority.*;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.comparator.DominanceComparator;
import org.uma.jmetal.util.evaluator.SolutionListEvaluator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
public class PriorityNSGAII extends AbstractPrioritySearch {
public PriorityNSGAII(int _cycle, List<PrioritySolution> _initial, Map<String, Object> _best, PriorityProblem _problem, int _maxIterations, int _populationSize, int _matingPoolSize, int _offspringPopulationSize, CrossoverOperator<PrioritySolution> _crossoverOperator, MutationOperator<PrioritySolution> _mutationOperator, SelectionOperator<List<PrioritySolution>, PrioritySolution> _selectionOperator, SolutionListEvaluator<PrioritySolution> _evaluator) {
super(_cycle, _initial, _best, _problem, _maxIterations, _populationSize, _matingPoolSize, _offspringPopulationSize, _crossoverOperator, _mutationOperator, _selectionOperator, _evaluator);
if (this.cycle!=0) {
externalFitness = new ExternalFitness(_problem, (PrioritySolutionEvaluator) _evaluator, _best,
getMaxPopulationSize(), (DominanceComparator<PrioritySolution>) dominanceComparator);
}
init_fitness();
init_maximum();
}
@Override
public void run() {
List<PrioritySolution> offspringPopulation;
List<PrioritySolution> matingPopulation;
population = createInitialPopulation();
population = evaluatePopulation(population);
population = replacement(population, new ArrayList<PrioritySolution>());
// printPopulation(String.format("[%d] population", iterations), population);
initProgress();
externalProcess(population, cycle==1);
this.initial = null;
while (!isStoppingConditionReached()){
// Breeding
matingPopulation = selection(population);
offspringPopulation = reproduction(matingPopulation);
offspringPopulation = evaluatePopulation(offspringPopulation);
// printPopulation(String.format("[%d] offspring", iterations), offspringPopulation);
population = replacement(population, offspringPopulation);
// printPopulation(String.format("[%d] population", iterations), population);
updateProgress();
}
JMetalLogger.logger.info("\t\tcalculating external fitness (cycle "+cycle+")");
externalProcess(population, false);
close();
}
protected List<PrioritySolution> reproduction(List<PrioritySolution> matingPool) {
int numberOfParents = this.crossoverOperator.getNumberOfRequiredParents();
this.checkNumberOfParents(matingPool, numberOfParents);
List<PrioritySolution> offspringPopulation = new ArrayList(this.offspringPopulationSize);
boolean flagFULL = false;
for(int i = 0; i < matingPool.size(); i += numberOfParents) {
if (flagFULL==true) break;
List<PrioritySolution> parents = new ArrayList(numberOfParents);
for(int j = 0; j < numberOfParents; ++j) {
parents.add(this.population.get(i + j));
}
List<PrioritySolution> offspring = (List)this.crossoverOperator.execute(parents);
Iterator it = offspring.iterator();
while(it.hasNext()) {
PrioritySolution s = (PrioritySolution) it.next();
do {
this.mutationOperator.execute(s);
if (searchedList.size() >= maxFact){
flagFULL = true;
break;
}
} while(!searchedList.add(s.toArray()));
if (flagFULL==true) break;
offspringPopulation.add(s);
if (offspringPopulation.size() >= this.offspringPopulationSize) {
break;
}
}
}
return offspringPopulation;
}
@Override
public String getName() {
return "NSGA-II";
}
@Override
public String getDescription() {
return "Nondominated Sorting Genetic Algorithm version II";
}
}
| 3,941 | 35.841121 | 456 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/priority/search/PriorityRandom.java | package lu.uni.svv.PriorityAssignment.priority.search;
import lu.uni.svv.PriorityAssignment.priority.*;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.archive.impl.NonDominatedSolutionListArchive;
import org.uma.jmetal.util.comparator.DominanceComparator;
import org.uma.jmetal.util.evaluator.SolutionListEvaluator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
public class PriorityRandom extends AbstractPrioritySearch {
NonDominatedSolutionListArchive<PrioritySolution> nonDominatedArchive ;
public PriorityRandom(int _cycle, List<PrioritySolution> _initial, Map<String, Object> _best, PriorityProblem _problem, int _maxIterations, int _populationSize, int _matingPoolSize, int _offspringPopulationSize, CrossoverOperator<PrioritySolution> _crossoverOperator, MutationOperator<PrioritySolution> _mutationOperator, SelectionOperator<List<PrioritySolution>, PrioritySolution> _selectionOperator, SolutionListEvaluator<PrioritySolution> _evaluator) {
super(_cycle, _initial, _best, _problem, _maxIterations, _populationSize, _matingPoolSize, _offspringPopulationSize, _crossoverOperator, _mutationOperator, _selectionOperator, _evaluator);
// nonDominatedArchive = new NonDominatedSolutionListArchive<PrioritySolution>((DominanceComparator<PrioritySolution>) dominanceComparator);
externalFitness = new ExternalFitnessRandom(_problem, (PrioritySolutionEvaluator) _evaluator, _best,
getMaxPopulationSize(), (DominanceComparator<PrioritySolution>) dominanceComparator);
init_fitness();
init_maximum();
}
@Override
public void run() {
List<PrioritySolution> offspringPopulation;
population = createInitialPopulation();
population = evaluatePopulation(population);
// population = replacement(population, new ArrayList<>());
// printPopulation(String.format("[%d] population", iterations), population);
initProgress();
externalProcess(population, cycle==1);
this.initial = null;
while (!isStoppingConditionReached()){
// Breeding
offspringPopulation = createRandomOffspirings();
offspringPopulation = evaluatePopulation(offspringPopulation);
population = replacement(population, offspringPopulation);
updateProgress();
}
JMetalLogger.logger.info("\t\tcalculating external fitness (cycle "+cycle+") // pop size: "+population.size());
externalProcess(population, false);
close();
}
/**
* Create initial priority assignments
* @return
*/
@Override
public List<PrioritySolution> createInitialPopulation() {
List<PrioritySolution> population = new ArrayList<>();
if (initial != null && initial.size()>0){
for(PrioritySolution item:initial) {
population.add(item);
}
}
else {
for (int i = 0; i < this.maxPopulationSize; i++) {
population.add(this.problem.createSolution());
}
}
return population;
}
@Override
protected List<PrioritySolution> replacement(List<PrioritySolution> population, List<PrioritySolution> offspringPopulation) {
NonDominatedSolutionListArchive<PrioritySolution> nonDominatedArchive =
new NonDominatedSolutionListArchive<>((DominanceComparator<PrioritySolution>) dominanceComparator);
// add to the non-dominated archive
for (PrioritySolution individual:population){
nonDominatedArchive.add(individual);
}
for (PrioritySolution offspring:offspringPopulation){
nonDominatedArchive.add(offspring);
}
return nonDominatedArchive.getSolutionList();
}
@Override
public String getName() {
return "RS";
}
@Override
public String getDescription() { return "Multi-objective random search algorithm" ; }
}
| 3,790 | 37.292929 | 456 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/priority/search/PrioritySearch.java | package lu.uni.svv.PriorityAssignment.priority.search;
import java.util.*;
import java.util.logging.Level;
import lu.uni.svv.PriorityAssignment.priority.*;
import lu.uni.svv.PriorityAssignment.utils.Monitor;
import lu.uni.svv.PriorityAssignment.utils.UniqueList;
import org.uma.jmetal.algorithm.multiobjective.nsgaii.NSGAII;
import org.uma.jmetal.operator.CrossoverOperator;
import org.uma.jmetal.operator.MutationOperator;
import org.uma.jmetal.operator.SelectionOperator;
import org.uma.jmetal.operator.impl.selection.RankingAndCrowdingSelection;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.comparator.DominanceComparator;
import org.uma.jmetal.util.evaluator.SolutionListEvaluator;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
public class PrioritySearch extends NSGAII<PrioritySolution> {
protected int cycle;
protected int iterations;
protected int maxIterations;
protected List<PrioritySolution> initial;
protected Map<String, Object> best;
protected static UniqueList searchedList = null;
protected GAWriter fwriter;
protected GAWriter mwriter;
protected ExternalFitness externalFitness = null;
private long maxFact = 0;
public PrioritySearch(int _cycle,
List<PrioritySolution> _initial, Map<String, Object> _best, PriorityProblem problem,
int maxIterations, int populationSize, int matingPoolSize, int offspringPopulationSize,
CrossoverOperator<PrioritySolution> crossoverOperator,
MutationOperator<PrioritySolution> mutationOperator,
SelectionOperator<List<PrioritySolution>, PrioritySolution> selectionOperator,
SolutionListEvaluator<PrioritySolution> evaluator)
{
super(problem, maxIterations*populationSize, populationSize, matingPoolSize, offspringPopulationSize,
crossoverOperator, mutationOperator, selectionOperator, evaluator);
this.cycle = _cycle;
this.initial = _initial;
this.iterations = 0;
this.maxIterations = maxIterations;
this.evaluations = 0;
if (this.cycle!=0) {
externalFitness = new ExternalFitness(problem, (PrioritySolutionEvaluator) evaluator, _best,
getMaxPopulationSize(), (DominanceComparator<PrioritySolution>) dominanceComparator);
}
init_fitness();
init_maximum();
if (searchedList==null) {
searchedList = new UniqueList();
}
this.maxFact = factorial(problem.Tasks.length);
}
public static void init(){
searchedList = new UniqueList();
}
@Override
public void run() {
List<PrioritySolution> offspringPopulation;
List<PrioritySolution> matingPopulation;
population = createInitialPopulation();
population = evaluatePopulation(population);
population = replacement(population, new ArrayList<PrioritySolution>());
// printPopulation(String.format("[%d] population", iterations), population);
initProgress();
externalProcess(cycle==1);
this.initial = null;
while (!isStoppingConditionReached()){
// Breeding
if (Settings.P2_SIMPLE_SEARCH){
offspringPopulation = createRandomOffspirings();
}
else{
matingPopulation = selection(population);
offspringPopulation = reproduction(matingPopulation);
}
offspringPopulation = evaluatePopulation(offspringPopulation);
// printPopulation(String.format("[%d] offspring", iterations), offspringPopulation);
population = replacement(population, offspringPopulation);
// printPopulation(String.format("[%d] population", iterations), population);
updateProgress();
}
JMetalLogger.logger.info("\t\tcalculating external fitness (cycle "+cycle+")");
externalProcess(false);
close();
}
@Override
protected List<PrioritySolution> evaluatePopulation(List<PrioritySolution> population) {
JMetalLogger.logger.info("\t\tcalculating internal fitness (iteration "+iterations+")");
Monitor.start("evaluateP2", true);
population = this.evaluator.evaluate(population, this.getProblem());
Monitor.end("evaluateP2", true);
Monitor.updateMemory();
return population;
}
public void externalProcess(boolean withOrigin){
Monitor.start("external", true);
if (externalFitness==null) return;
if(withOrigin){
externalFitness.evaluateOrigin(population, 0, 0);
}
else{
externalFitness.run(population, cycle, iterations);
}
Monitor.end("external", true);
Monitor.updateMemory();
}
/**
* create offsprings randomly
* @return
*/
public List<PrioritySolution> createRandomOffspirings() {
List<PrioritySolution> offspringPopulation = new ArrayList(this.offspringPopulationSize);
for(int i = 0; i < this.offspringPopulationSize; i++) {
PrioritySolution individual = this.problem.createSolution();
offspringPopulation.add(individual);
}
return offspringPopulation;
}
/**
* Create initial priority assignments
* @return
*/
@Override
public List<PrioritySolution> createInitialPopulation() {
List<PrioritySolution> population = new ArrayList<>(this.maxPopulationSize);
PrioritySolution individual;
for (int i = 0; i < this.maxPopulationSize; i++) {
if (initial != null && i < initial.size()){
individual = initial.get(i);
}
else {
individual = this.problem.createSolution();
}
population.add(individual);
}
return population;
}
@Override
protected boolean isStoppingConditionReached() {
// return this.evaluations >= this.maxEvaluations;
return this.iterations > this.maxIterations;
}
protected List<PrioritySolution> reproduction(List<PrioritySolution> matingPool) {
int numberOfParents = this.crossoverOperator.getNumberOfRequiredParents();
this.checkNumberOfParents(matingPool, numberOfParents);
List<PrioritySolution> offspringPopulation = new ArrayList(this.offspringPopulationSize);
boolean flagFULL = false;
for(int i = 0; i < matingPool.size(); i += numberOfParents) {
if (flagFULL==true) break;
List<PrioritySolution> parents = new ArrayList(numberOfParents);
for(int j = 0; j < numberOfParents; ++j) {
parents.add(this.population.get(i + j));
}
List<PrioritySolution> offspring = (List)this.crossoverOperator.execute(parents);
Iterator it = offspring.iterator();
while(it.hasNext()) {
PrioritySolution s = (PrioritySolution) it.next();
do {
this.mutationOperator.execute(s);
if (searchedList.size() >= maxFact){
flagFULL = true;
break;
}
} while(!searchedList.add(s.toArray()));
if (flagFULL==true) break;
offspringPopulation.add(s);
if (offspringPopulation.size() >= this.offspringPopulationSize) {
break;
}
}
}
return offspringPopulation;
}
@Override
protected List<PrioritySolution> replacement(List<PrioritySolution> population, List<PrioritySolution> offspringPopulation) {
List<PrioritySolution> jointPopulation = new ArrayList();
jointPopulation.addAll(population);
jointPopulation.addAll(offspringPopulation);
RankingAndCrowdingSelection<PrioritySolution> rankingAndCrowdingSelection = new RankingAndCrowdingSelection(this.getMaxPopulationSize(), this.dominanceComparator);
return rankingAndCrowdingSelection.execute(jointPopulation);
}
protected void printPopulation(String title, List<PrioritySolution> population){
System.out.println(title);
for(PrioritySolution individual : population){
String plist = individual.getVariablesString();
double fd = -individual.getObjective(0);
double fc = -individual.getObjective(1);
String output = String.format("\tID(%d): %s (F_C: %.0f, F_D: %e)", individual.ID , plist, fc, fd);
System.out.println(output);
}
}
@Override
protected void initProgress() {
super.initProgress();
// JMetalLogger.logger.info("["+getName()+"] Iteration "+iterations+": created initial population: "+evaluations);
if (Settings.PRINT_FITNESS) {
print_fitness();
print_maximum();
}
iterations = 1;
}
@Override
protected void updateProgress() {
super.updateProgress();
// JMetalLogger.logger.info("["+getName()+"] Iteration "+iterations+" (evaluated solutions: "+evaluations+")");
if (Settings.PRINT_FITNESS) {
print_fitness();
print_maximum();
}
iterations += 1;
System.gc();
}
////////////////////////////////////////////////////////////////////////////////
// Properties
////////////////////////////////////////////////////////////////////////////////
public Map<String, Object> getBest(){
return externalFitness.best;
}
public List<PrioritySolution> getPopulation(){
return population;
}
// get Best Pareto, parent NSGAII algorithm have this method
// public List<PrioritySolution> getResult(){
// return population;
// }
////////////////////////////////////////////////////////////////////////////////
// Utils
////////////////////////////////////////////////////////////////////////////////
private int factorial(int F){
int ret = 1;
for(int x=2; x<=F; x++){
ret = ret * x;
if (ret < 0) {
ret = Integer.MAX_VALUE;
break;
}
}
return ret;
}
////////////////////////////////////////////////////////////////////////////////
// Print out intermediate results
////////////////////////////////////////////////////////////////////////////////
private void init_fitness(){
if (externalFitness==null){
// When this class works for only NSGA mode, it produce the results like the external fitness results
// iteration value will be located at Cycle and the Iteration value will be set 2.
String title = "Cycle,Iteration,Distance,SolutionIndex,SolutionID,Schedulability,Satisfaction,DeadlineMiss,Rank,CrowdingDistance";
fwriter = new GAWriter("_fitness/fitness_external.csv", Level.INFO, title, null, true);
}
else{
String title = "Cycle,Iteration,SolutionIndex,SolutionID,Schedulability,Satisfaction,DeadlineMiss,Rank,CrowdingDistance"; //
fwriter = new GAWriter("_fitness/fitness_phase2.csv", Level.INFO, title, null, true);
}
}
private List<PrioritySolution> getBestSolutions(){
// minimum is the best
List<PrioritySolution> pop = new ArrayList<>();
PrioritySolution selected = population.get(0);
double minV = selected.getObjective(0);
for (PrioritySolution solution: population){
double value = solution.getObjective(0);
if (minV > value){
selected = solution;
minV = value;
}
}
pop.add(selected);
return pop;
}
private void print_fitness(){
StringBuilder sb = new StringBuilder();
int idx =0;
for (PrioritySolution solution: population){
// if (!(rank==null || (int)rank==0)) continue;
int rank = 0;
Object rankClass = org.uma.jmetal.util.solutionattribute.impl.DominanceRanking.class;
if (solution.hasAttribute(rankClass))
rank = (Integer)solution.getAttribute(rankClass);
if (externalFitness==null && rank!=0) continue;
double cDistance = 0.0;
Object distClass = org.uma.jmetal.util.solutionattribute.impl.CrowdingDistance.class;
if (solution.hasAttribute(distClass))
cDistance = (Double)solution.getAttribute(distClass);
int dms = (int)solution.getAttribute("DeadlineMiss");
if (externalFitness==null) {
sb.append(iterations); //actual iteration value is located at Cycle
sb.append(",");
sb.append((iterations==0)?0:2); //result Iteration value set 2 (for the analysis purpose)
sb.append(",");
sb.append(0); // distance
sb.append(",");
}
else{
sb.append(cycle);
sb.append(",");
sb.append(iterations);
sb.append(",");
}
sb.append(idx);
sb.append(",");
sb.append(solution.ID);
sb.append(",");
sb.append(String.format("%e",-solution.getObjective(0)));
sb.append(",");
sb.append(-solution.getObjective(1));
sb.append(",");
sb.append(dms);
sb.append(",");
sb.append(rank);
sb.append(",");
sb.append(cDistance);
sb.append("\n");
idx ++;
// if (dms[fIndex] > 0){
// printDeadlines(solution, iterations, idx);
// }
}
fwriter.write(sb.toString());
}
public void init_maximum(){
// title
StringBuilder sb = new StringBuilder();
sb.append("Cycle,Iteration,");
for(int num=0; num<problem.getNumberOfVariables(); num++){
sb.append(String.format("Task%d",num+1));
if (num+1 < problem.getNumberOfVariables())
sb.append(",");
}
mwriter = new GAWriter(String.format("_maximums/maximums_phase2.csv"), Level.FINE, sb.toString(), null, true);
}
public void print_maximum() {
// get maximums from best individual
int[] maximums = (int[])population.get(0).getAttribute("Maximums");
// generate text
StringBuilder sb = new StringBuilder();
sb.append(cycle);
sb.append(",");
sb.append(iterations);
sb.append(",");
int x=0;
for (; x < maximums.length - 1; x++) {
sb.append(maximums[x]);
sb.append(',');
}
sb.append(maximums[x]);
mwriter.info(sb.toString());
}
protected void close() {
if (mwriter != null)
mwriter.close();
if (fwriter != null)
fwriter.close();
if (externalFitness != null)
externalFitness.close();
}
private void printDeadlines(PrioritySolution _solution, int _iter, int _idx){
if (_solution==null) return ;
String text = (String)_solution.getAttribute("DMString");
String title = "ArrivalID,Task,Execution,DeadlineMiss";
GAWriter writer = new GAWriter(String.format("_deadlines/deadlines_phase2_iter%d_sol%d_rankIdx%d.csv", _iter, _solution.ID, _idx), Level.INFO, title, null);
writer.info(text);
writer.close();
text = _solution.getVariablesString();
writer = new GAWriter(String.format("_priorities_rank/priorities_phase2_iter%d_sol%d_rankIdx%d.csv", _iter, _solution.ID, _idx), Level.INFO, "", null);
writer.info(text);
writer.close();
}
} | 13,595 | 30.327189 | 165 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/task/TaskSeverity.java | package lu.uni.svv.PriorityAssignment.task;
public enum TaskSeverity {
HARD,
SOFT
}
| 87 | 11.571429 | 43 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/task/TaskType.java | package lu.uni.svv.PriorityAssignment.task;
public enum TaskType {
Periodic,
Aperiodic,
Sporadic
}
| 103 | 12 | 43 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/task/Task.java | package lu.uni.svv.PriorityAssignment.task;
public class Task {
public int ID; // Task Identification (Foreign key refers ID of TaskDescriptor)
public int ExecutionID; // Task's execution ID
public int ExecutionTime; // Worst-Case Execution Time
public int ArrivedTime; // time at which a task arrived in the ready queue
public int StartedTime; // time at which a task starts its execution
public int FinishedTime; // time at which a task finishes its execution
public int RemainTime; // remain time to execute
public int Deadline; // ArrivedTime + Deadline == deadline for this task
public int Priority; // Fixed Priority
public TaskSeverity Severity; // Hard or Soft deadline
public TaskState State; // Hard or Soft deadline
public int StateTime; // State changed Time
public Task(int _id, int _exID, int _execTime, int _arrivalTime, int _deadline, int _priority, TaskSeverity _severity) {
ID = _id;
ExecutionID = _exID;
ExecutionTime = _execTime;
ArrivedTime = _arrivalTime;
StartedTime = 0;
FinishedTime = 0;
RemainTime = _execTime;
Deadline = _deadline;
Priority = _priority;
Severity = _severity;
State = TaskState.Idle;
StateTime = _arrivalTime;
}
@Override
public String toString(){
return String.format("{ID:%d (%d), exID:%d, arrival:%d, started:%d, ended:%d, remain:%d}", ID, Priority, ExecutionID, ArrivedTime, StartedTime, FinishedTime, RemainTime);
}
public int updateTaskState(TaskState newState, int timelapsed){
if (newState==TaskState.Running && this.ExecutionTime==this.RemainTime)
StartedTime = timelapsed;
if (newState==TaskState.Idle)
FinishedTime = timelapsed;
int oldTimelapsed = StateTime;
State = newState;
StateTime = timelapsed;
return oldTimelapsed;
}
}
| 1,865 | 34.884615 | 172 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/task/TaskState.java | package lu.uni.svv.PriorityAssignment.task;
public enum TaskState {
Idle,
Ready,
Blocked,
Running,
Preempted
}
| 117 | 10.8 | 43 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/task/TaskDescriptor.java | package lu.uni.svv.PriorityAssignment.task;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Arrays;
import lu.uni.svv.PriorityAssignment.utils.Settings;
public class TaskDescriptor implements Comparable<TaskDescriptor>{
public static int UNIQUE_ID = 1;
public int ID; // The sequence of input data (main key for ordering)
public String Name; // Task Name
public TaskType Type; // Task type {Periodic, Aperiodic, Sporadic}
public int Offset; // first execution time of a periodic task
public int WCET; // Worst case execution time
public int MaxWCET; // Worst case execution time can be extended
public int Period; // Time period which a task occurs, This variable is for the Periodic task
public int MinIA; // Minimum inter-arrival time,This variable is for Aperiodic or Sporadic Task
public int MaxIA; // Maximum inter-arrival time, This variable is for Aperiodic or Sporadic Task
public int Deadline; // Time period which a task should be finished
public int Priority; // Fixed Priority read from input data
public TaskSeverity Severity; // {Hard, Soft}
public int[] Dependencies; // {Hard, Soft}
public int[] Triggers; // {Hard, Soft}
/**
* Create object without paramter
*/
public TaskDescriptor() {
ID = TaskDescriptor.UNIQUE_ID++;
Name = "";
Type = TaskType.Periodic;
Offset = 0;
WCET = 0;
MaxWCET = 0;
Period = 0;
MinIA = 0;
MaxIA = 0;
Deadline = 0;
Priority = 0;
Severity = TaskSeverity.HARD;
Dependencies= new int[0];
Triggers = new int[0];
}
/**
* Create object for copy
*/
public TaskDescriptor(TaskDescriptor _task) {
ID = _task.ID;
Name = _task.Name;
Type = _task.Type;
Offset = _task.Offset;
WCET = _task.WCET;
MaxWCET = _task.MaxWCET;
Period = _task.Period;
MinIA = _task.MinIA;
MaxIA = _task.MaxIA;
Deadline = _task.Deadline;
Priority = _task.Priority;
Severity = _task.Severity;
Dependencies= Arrays.copyOf(_task.Dependencies, _task.Dependencies.length);
Triggers = Arrays.copyOf(_task.Triggers, _task.Triggers.length);
}
public TaskDescriptor copy(){
return new TaskDescriptor(this);
}
@Override
public String toString(){
String period = String.format("%d", Period);
if (Type != TaskType.Periodic){
period = String.format("[%d-%d]", MinIA, MaxIA);
}
return String.format("%s: {ID: %d, type:%s, priority:%d, period:%s, wcet:%d}, deadline:%d", Name, ID, Type, Priority, period, WCET, Deadline);
}
/* ********************************************************************
Comparator
*/
@Override
public int compareTo(TaskDescriptor _o) {
if ((this.Period - _o.Period) > 0)
return 1;
else
return -1;
}
public static Comparator<TaskDescriptor> PriorityComparator = new Comparator<TaskDescriptor>() {
@Override
public int compare(TaskDescriptor _o1, TaskDescriptor _o2) {
if ((_o1.Priority - _o2.Priority) > 0)
return 1;
else
return -1;
}
};
public static Comparator<TaskDescriptor> PeriodComparator = new Comparator<TaskDescriptor>() {
@Override
public int compare(TaskDescriptor _o1, TaskDescriptor _o2) {
if ((_o1.Period - _o2.Period) > 0)
return 1;
else
return -1;
}
};
public static Comparator<TaskDescriptor> OrderComparator = new Comparator<TaskDescriptor>() {
@Override
public int compare(TaskDescriptor _o1, TaskDescriptor _o2) {
if ((_o1.ID - _o2.ID) > 0)
return 1;
else
return -1;
}
};
/**
* This comparator is for the assuming maximum fitness value
*/
public static Comparator<TaskDescriptor> deadlineComparator = new Comparator<TaskDescriptor>() {
@Override
public int compare(TaskDescriptor o1, TaskDescriptor o2) {
int diff = o2.Deadline - o1.Deadline;
if (diff==0){
diff = ((o2.Type==TaskType.Periodic)?o2.Period:o2.MinIA);
diff -= ((o1.Type==TaskType.Periodic)?o1.Period:o1.MinIA);
if (diff == 0){
diff = o2.MaxWCET - o1.MaxWCET;
}
}
return diff;
}
};
/* **********************************************************
* Functions to deal with multiple task descriptions
*/
/**
* copy an array of task descriptors
* @param _tasks
* @return
*/
public static TaskDescriptor[] copyArray(TaskDescriptor[] _tasks){
TaskDescriptor[] tasks = new TaskDescriptor[_tasks.length];
for (int i=0; i< _tasks.length; i++){
tasks[i] = _tasks[i].copy();
}
return tasks;
}
/**
* load from CSV file (Time unit is TIME_QUANTA )
* @param _filepath
* @param _maximumTime
* @param _timeQuanta
* @return
* @throws NumberFormatException
* @throws IOException
*/
public static TaskDescriptor[] loadFromCSV(String _filepath, double _maximumTime, double _timeQuanta) throws NumberFormatException, IOException {
List<TaskDescriptor> listJobs = new ArrayList<>();
File file = new File(_filepath);
BufferedReader br = new BufferedReader(new FileReader(file));
long lineCnt=0;
String data;
while ((data = br.readLine()) != null) {
lineCnt++;
if (lineCnt==1) continue; // Remove CSV file header
if (data.trim().length()==0) continue;
String[] cols = data.split(",");
TaskDescriptor aJob = new TaskDescriptor();
aJob.Name = cols[1].trim(); // Name
aJob.Type = getTypeFromString(cols[2].trim());
aJob.Priority = getValueFromString(cols[3].trim(), 10000);
aJob.Offset = getTimeFromString(cols[4].trim(), 0, _maximumTime, _timeQuanta);
aJob.WCET = getTimeFromString(cols[5].trim(), 0, _maximumTime, _timeQuanta);
aJob.MaxWCET = getTimeFromString(cols[6].trim(), 0, _maximumTime,_timeQuanta);
aJob.Period = getTimeFromString(cols[7].trim(), _maximumTime, _maximumTime, _timeQuanta);
aJob.MinIA = getTimeFromString(cols[8].trim(), 0, _maximumTime,_timeQuanta);
aJob.MaxIA = getTimeFromString(cols[9].trim(), _maximumTime, _maximumTime, _timeQuanta);
aJob.Deadline = getTimeFromString(cols[10].trim(), _maximumTime, _maximumTime, _timeQuanta);
aJob.Severity = getSeverityFromString(cols[11].trim()); // Severity type
if (cols.length>12) {
aJob.Dependencies = getListFromString(cols[12].trim());
}
if (cols.length>13) {
aJob.Triggers = getListFromString(cols[13].trim());
}
listJobs.add(aJob);
}
// after loop, close reader
br.close();
// Return loaded data
TaskDescriptor[] tasks = new TaskDescriptor[listJobs.size()];
listJobs.toArray(tasks);
return tasks;
}
/**
* converting to string to store an array of task descriptors
* @param _tasks
* @param _timeQuanta
* @return
*/
public static String toString(TaskDescriptor[] _tasks, double _timeQuanta){
StringBuilder sb = new StringBuilder();
sb.append("Task ID, Task Name,Task Type,Task Priority,Offset,WCET min,WCET max,Task Period (ms),Minimum interarrival-time (ms),Maximum Interarrival time,Task Deadline, Deadline Type, Dependencies, Triggers\n");
for(TaskDescriptor task:_tasks)
{
sb.append(String.format("%d,%s,%s,%d,%f,%f,%f,%f",
task.ID,
task.Name, task.Type.toString(), task.Priority, task.Offset* _timeQuanta,
task.WCET * _timeQuanta, task.MaxWCET* _timeQuanta,
task.Period * _timeQuanta));
if (task.Type==TaskType.Periodic) {
sb.append(",,");
}
else{
sb.append(String.format(",%f,%f", task.MinIA* _timeQuanta, task.MaxIA* _timeQuanta));
}
sb.append(String.format(",%f,%s,%s,%s\n",
task.Deadline* _timeQuanta, task.Severity,
listtoString(task.Dependencies), listtoString(task.Triggers)));
}
return sb.toString();
}
/**
* Generates masks for each task that is not arrived by its period due to the triggering tasks
* @param _tasks
* @return
*/
public static boolean[] getArrivalExceptionTasks(TaskDescriptor[] _tasks){
boolean[] list = new boolean[_tasks.length+1];
for(int x=0; x<_tasks.length; x++){
for(int i=0; i<_tasks[x].Triggers.length; i++){
list[_tasks[x].Triggers[i]] = true;
}
}
return list;
}
/**
* Finds the maximum number of resources from task descriptions
* @param _tasks
* @return
*/
public static int getMaxNumResources(TaskDescriptor[] _tasks){
// find max number of resources;
int maxResource = 0;
for (int tIDX=0; tIDX<_tasks.length; tIDX++) {
for (int r=0; r<_tasks[tIDX].Dependencies.length; r++){
if (_tasks[tIDX].Dependencies[r] > maxResource)
maxResource = _tasks[tIDX].Dependencies[r];
}
}
return maxResource;
}
/**
* Get aperiodic tasks which inter-arrival times are different
* @return
*/
public static List<Integer> getVaryingTasks(TaskDescriptor[] _tasks){
List<Integer> list = new ArrayList<Integer>();
for(TaskDescriptor task : _tasks){
if (task.Type != TaskType.Periodic && task.MinIA != task.MaxIA)
list.add(task.ID);
}
return list;
}
/**
* Get a number of aperiodic tasks
* @return
*/
public static int getNumberOfAperiodics(TaskDescriptor[] _tasks){
int count=0;
for (TaskDescriptor task:_tasks){
if (task.Type == TaskType.Aperiodic)
count+=1;
}
return count;
}
/**
* Find maximum deadline among an array of task descriptors
* @param _tasks
* @return
*/
public static int findMaximumDeadline(TaskDescriptor[] _tasks){
int max_dealine=0;
for (TaskDescriptor task:_tasks){
if (task.Deadline> max_dealine)
max_dealine = task.Deadline;
}
return max_dealine;
}
/**
* Get minimim fitness value (not exact)
* @param _tasks
* @param simulationTime
* @return
*/
public static double getMinFitness(TaskDescriptor[] _tasks, long simulationTime){
double fitness = 0.0;
for (TaskDescriptor task: _tasks){
int period = (task.Type== TaskType.Periodic)?task.Period:task.MaxIA;
int nArrivals = (int)Math.ceil(simulationTime / (double)period);
int diff = task.WCET - task.Deadline;
fitness += Math.pow(Settings.FD_BASE, diff/Settings.FD_EXPONENT) * nArrivals;
}
return fitness;
}
/**
* Get maximum fitness value order by deadline and calculate cumulated WCET
* This assumes the maximum fitness value (not exact)
* @param _tasks
* @param simulationTime
* @return
*/
public static double getMaxFitness(TaskDescriptor[] _tasks, long simulationTime){
TaskDescriptor[] tasks = TaskDescriptor.copyArray(_tasks);
Arrays.sort(tasks,TaskDescriptor.deadlineComparator);
double fitness = 0.0;
int WCET = 0;
for (TaskDescriptor task: tasks){
int period = (task.Type == TaskType.Periodic)?task.Period:task.MinIA;
int nArrivals = (int)Math.ceil(simulationTime / (double)period);
WCET = WCET + task.MaxWCET;
int diff = WCET - task.Deadline;
double fitItem = Math.pow(Settings.FD_BASE, diff/Settings.FD_EXPONENT);
if (fitItem == Double.NEGATIVE_INFINITY) fitItem = 0;
if (fitItem == Double.POSITIVE_INFINITY) fitItem = Double.MAX_VALUE;
fitness += fitItem * nArrivals;
}
return fitness;
}
/**
* Convert list to string with ';' delimiter
* This function is for the dependency and triggering list
* @param _items
* @return
*/
public static String listtoString(int[] _items){
StringBuilder sb = new StringBuilder();
for (int x=0; x<_items.length; x++){
if (x!=0) sb.append(';');
sb.append(_items[x]);
}
return sb.toString();
}
/////////
// sub functions for Loading from CSV
/////////
public static TaskType getTypeFromString(String _text) {
if (_text.toLowerCase().compareTo("sporadic")==0)
return TaskType.Sporadic;
else if (_text.toLowerCase().compareTo("aperiodic")==0)
return TaskType.Aperiodic;
else
return TaskType.Periodic;
}
public static TaskSeverity getSeverityFromString(String _text) {
if (_text.toLowerCase().compareTo("soft")==0)
return TaskSeverity.SOFT;
else
return TaskSeverity.HARD;
}
public static int getValueFromString(String _text, int _default) {
if (_text.compareTo("")==0 || _text.compareTo("N/A")==0)
return _default;
else
return (int)(Double.parseDouble(_text));
}
public static int getTimeFromString(String _text, double _default, double _max, double _timeQuanta) {
double value = 0.0;
if (_text.compareTo("")==0 || _text.compareTo("N/A")==0)
value = _default;
else {
value = Double.parseDouble(_text);
if (_max !=0 && value > _max) value = _max;
}
return (int)(value * (1 / _timeQuanta));
}
public static int[] getListFromString(String _text) {
String[] texts = _text.split(";");
int[] items = new int[texts.length];
int cnt=0;
for ( int i=0; i< texts.length; i++){
texts[i] = texts[i].trim();
if(texts[i].length()==0) continue;
items[i] = Integer.parseInt(texts[i]);
cnt++;
}
if (cnt==0){
return new int[0];
}
return items;
}
} | 12,927 | 28.381818 | 212 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/analysis/UniqueNondominatedFrontRatio.java | package lu.uni.svv.PriorityAssignment.analysis;
import java.io.FileNotFoundException;
import java.util.List;
import org.uma.jmetal.qualityindicator.impl.GenericIndicator;
import org.uma.jmetal.solution.Solution;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.front.Front;
import org.uma.jmetal.util.front.imp.ArrayFront;
import org.uma.jmetal.util.point.Point;
public class UniqueNondominatedFrontRatio<S extends Solution<?>> extends GenericIndicator<S> {
private double pow;
public UniqueNondominatedFrontRatio() {
this.pow = 2.0D;
}
public UniqueNondominatedFrontRatio(String referenceParetoFrontFile, double p) throws FileNotFoundException {
super(referenceParetoFrontFile);
this.pow = 2.0D;
this.pow = p;
}
public UniqueNondominatedFrontRatio(String referenceParetoFrontFile) throws FileNotFoundException {
this(referenceParetoFrontFile, 2.0D);
}
public UniqueNondominatedFrontRatio(Front referenceParetoFront) {
super(referenceParetoFront);
this.pow = 2.0D;
}
public Double evaluate(List<S> solutionList) {
if (solutionList == null) {
throw new JMetalException("The pareto front approximation is null");
} else {
return this.calculateRatio(new ArrayFront(solutionList), this.referenceParetoFront);
}
}
public double calculateRatio(Front front, Front referenceFront) {
List<Point> uniqueFront = DominateUtils.getUniqueSolutions(front);
List<Point> uniqueReferenceFront = DominateUtils.getUniqueSolutions(referenceFront);
List<Point> exFront = DominateUtils.getNonDominateSolutions(uniqueFront, uniqueReferenceFront);
return exFront.size() / (double)uniqueReferenceFront.size();
}
public String getName() {
return "UNFR";
}
public String getDescription() {
return "Unique Non-dominated Front Ratio quality indicator";
}
public boolean isTheLowerTheIndicatorValueTheBetter() {
return false;
}
}
| 2,074 | 29.970149 | 113 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/analysis/EuclidianDistanceBySuperior.java | package lu.uni.svv.PriorityAssignment.analysis;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.point.Point;
import org.uma.jmetal.util.point.util.distance.PointDistance;
public class EuclidianDistanceBySuperior implements PointDistance {
public EuclidianDistanceBySuperior() {
}
public double compute(Point a, Point b) {
if (a == null) {
throw new JMetalException("The first point is null");
} else if (b == null) {
throw new JMetalException("The second point is null");
} else if (a.getDimension() != b.getDimension()) {
throw new JMetalException("The dimensions of the points are different: " + a.getDimension() + ", " + b.getDimension());
} else {
double distance = 0.0D;
for(int i = 0; i < a.getDimension(); ++i) {
distance += Math.pow(Math.max(a.getValue(i) - b.getValue(i), 0), 2.0D);
}
return Math.sqrt(distance);
}
}
} | 1,012 | 33.931034 | 131 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/analysis/QIEvaluatorPaired.java | package lu.uni.svv.PriorityAssignment.analysis;
import lu.uni.svv.PriorityAssignment.Initializer;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.uma.jmetal.qualityindicator.impl.GeneralizedSpread;
import org.uma.jmetal.qualityindicator.impl.GenerationalDistance;
import org.uma.jmetal.qualityindicator.impl.GenericIndicator;
import org.uma.jmetal.qualityindicator.impl.hypervolume.PISAHypervolume;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.front.Front;
import org.uma.jmetal.util.front.imp.ArrayFront;
import org.uma.jmetal.util.front.util.FrontNormalizer;
import org.uma.jmetal.util.point.PointSolution;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
public class QIEvaluatorPaired extends QIEvaluator {
public static void main(String[] args) throws Exception {
// Environment Settings
Initializer.initLogger();
Settings.update(args);
GAWriter.init(null, false);
// define output paths
String[] approaches = Settings.APPROACHES.split(",");
String[] paths = new String[]{Settings.COMPARE_PATH1, Settings.COMPARE_PATH2};
new QIEvaluatorPaired().run(approaches, paths, Settings.OUTPUT_PATH,
Settings.RUN_CNT, Settings.NUM_TEST);
}
////////////////////////////////////////////////////////
// non-static members
////////////////////////////////////////////////////////
public FrontNormalizer frontNormalizer = null;
public List<GenericIndicator<PointSolution> > QIs = null;
public double[] defaults;
public String[] names;
public QIEvaluatorPaired() {
// CI result will be ranged [0, 0.5] because the reference front will weakly dominate the pareto front produced by one single run
// default values for GD, GD+, HV, GS, CI, UNFR, SP and CS
names = new String[]{ "GD", "GDP", "HV", "GS", "CI", "UNFR", "SP", "CS", "CSunique"};
defaults = new double[]{0.0, 0.0, 1.0, 0.0, 0.5, 1.0, 0.0, 1.0, 1.0};
}
public void run(String[] approaches, String[] paths, String output, int runNum, int targetCycle) throws Exception {
// create output file
GAWriter writer = new GAWriter(output, Level.INFO, null, "./", false);
StringBuilder title = new StringBuilder("Approach,Subject,Run");
for (String name:names){
title.append(",");
title.append(name);
}
title.append("\n");
writer.write(title.toString());
// load all populations
HashMap<String, List<PointSolution>[]> pops1 = this.load_fitness(paths[0], targetCycle, runNum);
HashMap<String, List<PointSolution>[]> pops2 = this.load_fitness(paths[1], targetCycle, runNum);
// calculate QIs for each subjects
Set<String> subjects = pops1.keySet();
for (String subject:subjects) {
JMetalLogger.logger.info(String.format("Calculating quality indicators for %s...", subject));
// Generate reference Pareto
List<PointSolution>[] pops1Run = pops1.get(subject);
List<PointSolution>[] pops2Run = pops2.get(subject);
// calculate QI values
for (int runID=0; runID<runNum; runID++) {
if (initializeQIs(pops1Run[runID], pops2Run[runID])) {
writer.write(calculate(runID+1, approaches[0], subject, pops1Run[runID]));
writer.write(calculate(runID+1, approaches[1], subject, pops2Run[runID]));
} else {
writer.write(calculateForError(runID+1, approaches[0], subject));
writer.write(calculateForError(runID+1, approaches[1], subject));
}
}
}
writer.close();
JMetalLogger.logger.info("Calculating quality indicators...Done.");
}
public boolean initializeQIs(List<PointSolution> _setList1, List<PointSolution> _setList2) throws Exception {
// create reference Pareto
List<PointSolution> jointPopulation = getCyclePoints(_setList1, _setList2);
List<PointSolution> ref = this.getReferencePareto(jointPopulation);
// Data normalizing
this.frontNormalizer = new FrontNormalizer(jointPopulation) ;
ArrayFront refFront = new ArrayFront(ref);
Front normalizedReferenceFront;
try{
normalizedReferenceFront = this.frontNormalizer.normalize(refFront);
}
catch (Exception e){
return false;
}
// define quality indicators
QIs = new ArrayList<GenericIndicator<PointSolution> >();
QIs.add(new GenerationalDistance<>(normalizedReferenceFront));
QIs.add(new GenerationalDistancePlus<>(normalizedReferenceFront));
QIs.add(new PISAHypervolume<>(normalizedReferenceFront)); // need to normalize values [0,1]
QIs.add(new GeneralizedSpread<>(normalizedReferenceFront));
QIs.add(new ContributionIndicator<>(normalizedReferenceFront));
QIs.add(new UniqueNondominatedFrontRatio<>(normalizedReferenceFront));
QIs.add(new Spacing<>());
QIs.add(new CoverageIndicator<>(normalizedReferenceFront, false));
QIs.add(new CoverageIndicator<>(normalizedReferenceFront, true));
return true;
}
public List<PointSolution> getCyclePoints(List<PointSolution> pops1, List<PointSolution> pops2) {
List<PointSolution> jointPopulation = new ArrayList<>();
jointPopulation.addAll(pops1);
jointPopulation.addAll(pops2);
return jointPopulation;
}
}
| 5,122 | 37.518797 | 131 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/analysis/GenerationalDistancePlus.java | package lu.uni.svv.PriorityAssignment.analysis;
import java.io.FileNotFoundException;
import java.util.List;
import org.uma.jmetal.qualityindicator.impl.GenericIndicator;
import org.uma.jmetal.solution.Solution;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.front.Front;
import org.uma.jmetal.util.front.imp.ArrayFront;
import org.uma.jmetal.util.front.util.FrontUtils;
public class GenerationalDistancePlus<S extends Solution<?>> extends GenericIndicator<S> {
private double pow;
public GenerationalDistancePlus() {
this.pow = 2.0D;
}
public GenerationalDistancePlus(String referenceParetoFrontFile, double p) throws FileNotFoundException {
super(referenceParetoFrontFile);
this.pow = 2.0D;
this.pow = p;
}
public GenerationalDistancePlus(String referenceParetoFrontFile) throws FileNotFoundException {
this(referenceParetoFrontFile, 2.0D);
}
public GenerationalDistancePlus(Front referenceParetoFront) {
super(referenceParetoFront);
this.pow = 2.0D;
}
public Double evaluate(List<S> solutionList) {
if (solutionList == null) {
throw new JMetalException("The pareto front approximation is null");
} else {
return this.generationalDistance(new ArrayFront(solutionList), this.referenceParetoFront);
}
}
public double generationalDistance(Front front, Front referenceFront) {
EuclidianDistanceBySuperior distanceMeasure = new EuclidianDistanceBySuperior();
double sum = 0.0D;
for(int i = 0; i < front.getNumberOfPoints(); ++i) {
sum += Math.pow(FrontUtils.distanceToClosestPoint(front.getPoint(i), referenceFront, distanceMeasure), this.pow);
}
sum = Math.pow(sum, 1.0D / this.pow);
return sum / (double)front.getNumberOfPoints();
}
public String getName() {
return "GD+";
}
public String getDescription() {
return "Generational distance plus quality indicator";
}
public boolean isTheLowerTheIndicatorValueTheBetter() {
return true;
}
}
| 2,141 | 30.043478 | 125 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/analysis/ExtendedFrontNormalizer.java | package lu.uni.svv.PriorityAssignment.analysis;
import java.util.List;
import org.uma.jmetal.solution.Solution;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.front.Front;
import org.uma.jmetal.util.front.imp.ArrayFront;
import org.uma.jmetal.util.front.util.FrontUtils;
public class ExtendedFrontNormalizer{
private double[] maximumValues;
private double[] minimumValues;
public ExtendedFrontNormalizer(List<? extends Solution<?>> referenceFront) {
if (referenceFront == null) {
throw new JMetalException("The reference front is null");
} else {
this.maximumValues = FrontUtils.getMaximumValues(new ArrayFront(referenceFront));
this.minimumValues = FrontUtils.getMinimumValues(new ArrayFront(referenceFront));
}
}
public ExtendedFrontNormalizer(Front referenceFront) {
if (referenceFront == null) {
throw new JMetalException("The reference front is null");
} else {
this.maximumValues = FrontUtils.getMaximumValues(referenceFront);
this.minimumValues = FrontUtils.getMinimumValues(referenceFront);
}
}
public ExtendedFrontNormalizer(double[] minimumValues, double[] maximumValues) {
if (minimumValues == null) {
throw new JMetalException("The array of minimum values is null");
} else if (maximumValues == null) {
throw new JMetalException("The array of maximum values is null");
} else if (maximumValues.length != minimumValues.length) {
throw new JMetalException("The length of the maximum array (" + maximumValues.length + ") is different from the length of the minimum array (" + minimumValues.length + ")");
} else {
this.maximumValues = maximumValues;
this.minimumValues = minimumValues;
}
}
public List<? extends Solution<?>> normalize(List<? extends Solution<?>> solutionList) {
if (solutionList == null) {
throw new JMetalException("The front is null");
} else {
Front normalizedFront = this.getNormalizedFront(new ArrayFront(solutionList), this.maximumValues, this.minimumValues);
return FrontUtils.convertFrontToSolutionList(normalizedFront);
}
}
public Front normalize(Front front) {
if (front == null) {
throw new JMetalException("The front is null");
} else {
return this.getNormalizedFront(front, this.maximumValues, this.minimumValues);
}
}
private Front getNormalizedFront(Front front, double[] maximumValues, double[] minimumValues) {
if (front.getNumberOfPoints() == 0) {
throw new JMetalException("The front is empty");
} else if (front.getPoint(0).getDimension() != maximumValues.length) {
throw new JMetalException("The length of the point dimensions (" + front.getPoint(0).getDimension() + ") is different from the length of the maximum array (" + maximumValues.length + ")");
} else {
Front normalizedFront = new ArrayFront(front);
int numberOfPointDimensions = front.getPoint(0).getDimension();
for(int i = 0; i < front.getNumberOfPoints(); ++i) {
for(int j = 0; j < numberOfPointDimensions; ++j) {
if (maximumValues[j] - minimumValues[j] == 0.0D) {
normalizedFront.getPoint(i).setValue(j, 1);
}else {
normalizedFront.getPoint(i).setValue(j, (front.getPoint(i).getValue(j) - minimumValues[j]) / (maximumValues[j] - minimumValues[j]));
}
}
}
return normalizedFront;
}
}
}
| 3,292 | 37.290698 | 191 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/analysis/ContributionIndicator.java | package lu.uni.svv.PriorityAssignment.analysis;
import org.uma.jmetal.qualityindicator.impl.GenericIndicator;
import org.uma.jmetal.solution.Solution;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.front.Front;
import org.uma.jmetal.util.front.imp.ArrayFront;
import org.uma.jmetal.util.point.Point;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
/**
* ContributionIndicator (CI)
* @param <S>
*/
public class ContributionIndicator<S extends Solution<?>> extends GenericIndicator<S> {
public ContributionIndicator(String referenceParetoFrontFile) throws FileNotFoundException {
super(referenceParetoFrontFile);
}
public ContributionIndicator(Front referenceParetoFront) {
super(referenceParetoFront);
}
public Double evaluate(List<S> solutionList) {
if (solutionList == null) {
throw new JMetalException("The pareto front approximation is null");
} else {
return this.calculate(new ArrayFront(solutionList), this.referenceParetoFront);
}
}
/**
* Calculate the ratio of the solutions of a set (A) that are not dominated by any solution in the other set (B)
* if all the solutions produced by the set (A) are dominated by the solutions produced by the set (B), then return 0
* if all the solutions produced by the set (B) are dominated by the solutions produced by the set (A), then return 1
* if both set (A) and (B) are the same, the function returns 0.5
* @param A
* @param B
* @return
*/
public double calculate(Front A, Front B) {
List<Point> intersecFront = DominateUtils.getIntersectionFront(A, B);
List<Point> someDomA = DominateUtils.getSomeDominateSolutions(A, B);
List<Point> someDomB = DominateUtils.getSomeDominateSolutions(B, A);
List<Point> exDomA = DominateUtils.getNotComparableSolutions(A, B);
List<Point> exDomB = DominateUtils.getNotComparableSolutions(B, A);
double upper = intersecFront.size()/2.0 + someDomA.size() + exDomA.size();
double lower = intersecFront.size() + someDomA.size() + exDomA.size() +
someDomB.size() + exDomB.size();
return upper / lower;
}
public String getName() {
return "CI";
}
public String getDescription() {
return "Contribution indicator";
}
public boolean isTheLowerTheIndicatorValueTheBetter() {
return false;
}
}
| 2,522 | 34.041667 | 121 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/analysis/QIEvaluator.java | package lu.uni.svv.PriorityAssignment.analysis;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import lu.uni.svv.PriorityAssignment.Initializer;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.uma.jmetal.operator.impl.selection.RankingAndCrowdingSelection;
import org.uma.jmetal.qualityindicator.impl.GeneralizedSpread;
import org.uma.jmetal.qualityindicator.impl.GenerationalDistance;
import org.uma.jmetal.qualityindicator.impl.GenericIndicator;
import org.uma.jmetal.qualityindicator.impl.hypervolume.PISAHypervolume;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.SolutionListUtils;
import org.uma.jmetal.util.comparator.DominanceComparator;
import org.uma.jmetal.util.front.Front;
import org.uma.jmetal.util.front.imp.ArrayFront;
import org.uma.jmetal.util.front.util.FrontNormalizer;
import org.uma.jmetal.util.front.util.FrontUtils;
import org.uma.jmetal.util.point.PointSolution;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
public class QIEvaluator {
public static void main(String[] args) throws Exception {
// Environment Settings
Initializer.initLogger();
Settings.update(args);
GAWriter.init(null, false);
// define output paths
String[] approaches = Settings.APPROACHES.split(",");
String[] paths = new String[]{Settings.COMPARE_PATH1, Settings.COMPARE_PATH2};
new QIEvaluator().run(approaches, paths, Settings.OUTPUT_PATH,
Settings.RUN_CNT, Settings.CYCLE_NUM);
}
////////////////////////////////////////////////////////
// non-static members
////////////////////////////////////////////////////////
public ExtendedFrontNormalizer frontNormalizer = null;
public List<GenericIndicator<PointSolution> > QIs = null;
public double[] defaults;
public String[] names;
public QIEvaluator() {
// CI result will be ranged [0, 0.5] because the reference front will weakly dominate the pareto front produced by one single run
// default values for GD, GD+, HV, GS, CI, UNFR, SP and CS
names = new String[]{ "GD", "GDP", "HV", "GS", "CI", "UNFR", "SP", "CS", "CSunique"};
defaults = new double[]{0.0, 0.0, 1.0, 0.0, 0.5, 1.0, 0.0, 1.0, 1.0};
}
public void run(String[] approaches, String[] paths, String output, int runNum, int targetCycle) throws Exception {
// create output file
GAWriter writer = new GAWriter(output, Level.INFO, null, "./", false);
StringBuilder title = new StringBuilder("Approach,Subject,Run");
for (String name:names){
title.append(",");
title.append(name);
}
title.append("\n");
writer.write(title.toString());
// load all populations
HashMap<String, List<PointSolution>[]> pops1 = this.load_fitness(paths[0], targetCycle, runNum);
HashMap<String, List<PointSolution>[]> pops2 = this.load_fitness(paths[1], targetCycle, runNum);
// calculate QIs for each subjects
Set<String> subjects = pops1.keySet();
for (String subject:subjects) {
JMetalLogger.logger.info(String.format("Calculating quality indicators for %s...", subject));
// Generate reference Pareto
List<PointSolution>[] pops1Run = pops1.get(subject);
List<PointSolution>[] pops2Run = pops2.get(subject);
// calculate QI values
if (initializeQIs(pops1Run, pops2Run)) {
for(int runID=0; runID<runNum; runID++)
writer.write(calculate(runID, approaches[0], subject, pops1Run[runID]));
for(int runID=0; runID<runNum; runID++)
writer.write(calculate(runID, approaches[1], subject, pops2Run[runID]));
}
else{
for(int runID=0; runID<runNum; runID++)
writer.write(calculateForError(runID, approaches[0], subject));
for(int runID=0; runID<runNum; runID++)
writer.write(calculateForError(runID, approaches[1], subject));
}
}
writer.close();
JMetalLogger.logger.info("Calculating quality indicators...Done.");
}
public boolean initializeQIs(List<PointSolution>[] _setList1, List<PointSolution>[] _setList2) throws Exception {
// create reference Pareto
List<PointSolution> jointPopulation = getCyclePoints(_setList1, _setList2);
List<PointSolution> ref = this.getReferencePareto(jointPopulation);
// Data normalizing
this.frontNormalizer = new ExtendedFrontNormalizer(jointPopulation) ;
ArrayFront refFront = new ArrayFront(ref);
Front normalizedReferenceFront;
try{
normalizedReferenceFront = this.frontNormalizer.normalize(refFront);
}
catch (Exception e){
return false;
}
// define quality indicators
QIs = new ArrayList<GenericIndicator<PointSolution> >();
QIs.add(new GenerationalDistance<>(normalizedReferenceFront));
QIs.add(new GenerationalDistancePlus<>(normalizedReferenceFront));
QIs.add(new PISAHypervolume<>(normalizedReferenceFront)); // need to normalize values [0,1]
QIs.add(new GeneralizedSpread<>(normalizedReferenceFront));
QIs.add(new ContributionIndicator<>(normalizedReferenceFront));
QIs.add(new UniqueNondominatedFrontRatio<>(normalizedReferenceFront));
QIs.add(new Spacing<>());
QIs.add(new CoverageIndicator<>(normalizedReferenceFront, false));
QIs.add(new CoverageIndicator<>(normalizedReferenceFront, true));
return true;
}
public String calculate(int runID, String approach, String subject, List<PointSolution> pops){
StringBuilder sb = new StringBuilder();
Front normalizedFront = this.frontNormalizer.normalize(new ArrayFront(pops)) ;
List<PointSolution> normalizedPopulation = FrontUtils.convertFrontToSolutionList(normalizedFront) ;
sb.append(String.format("%s,%s,%d", approach, subject, runID+1));
for (int q=0; q<QIs.size(); q++){
double value = QIs.get(q).evaluate(normalizedPopulation);
sb.append(String.format(",%f",value));
}
sb.append("\n");
return sb.toString();
}
public String calculateForError(int runID, String approach, String subject){
StringBuilder sb = new StringBuilder();
// if higher value is better, put 1.0, otherwise, put 0.0
//if two pareto are identical, CI values is equal to 0.5
sb.append(String.format("%s,%s,%d", approach, subject, runID+1));
for (int q=0; q<defaults.length; q++){
sb.append(",NA");
// sb.append(defaults[q]);
}
sb.append("\n");
return sb.toString();
}
public List<PointSolution> getCyclePoints(List<PointSolution>[] pops1, List<PointSolution>[] pops2) {
List<PointSolution> jointPopulation = new ArrayList<>();
for (int k = 0; k < pops1.length; k++) {
jointPopulation.addAll(pops1[k]);
}
for (int k = 0; k < pops2.length; k++) {
jointPopulation.addAll(pops2[k]);
}
return jointPopulation;
}
public List<PointSolution> getReferencePareto(List<PointSolution> pops) throws Exception {
RankingAndCrowdingSelection<PointSolution> selector = null;
selector = new RankingAndCrowdingSelection<>(pops.size(), new DominanceComparator<>());
// int size = Math.min(pops.size(), Settings.P2_POPULATION);
// selector = new RankingAndCrowdingSelection<>(size, new DominanceComparator<>());
List<PointSolution> selected = selector.execute(pops);
List<PointSolution> pareto = SolutionListUtils.getNondominatedSolutions(selected);
JMetalLogger.logger.info(String.format("\tCalculating reference pareto....Done (Size: %d).", pareto.size()));
return pareto;
}
/**
* Load fitness values from the result file
* To treat the fitness values as the same way as we do in the search (minimize the objectives),
* we multiply -1 to the fitness values
* @param filename
* @param cycleTarget
* @param runNum
* @return
* @throws IOException
*/
public HashMap<String, List<PointSolution>[]> load_fitness(String filename, int cycleTarget, int runNum) throws IOException, CsvValidationException {
HashMap<String, List<PointSolution>[]> dset = new HashMap<>();
List<List<PointSolution>[]> list = new ArrayList<List<PointSolution>[]>();
// read csv file
CSVReader csvReader = new CSVReader(new FileReader(filename));
csvReader.readNext(); // throw header
String[] values = null;
while ((values = csvReader.readNext()) != null) {
String subject = values[0];
int run = Integer.parseInt(values[2])-1;
int cycle = Integer.parseInt(values[3]);
if (cycle!=cycleTarget) continue;
List<PointSolution>[] variable = null;
if (dset.containsKey(subject)==false){
variable = new ArrayList[runNum];
dset.put(subject, variable);
}
else{
variable = dset.get(subject);
}
if (variable[run]==null){
variable[run] = new ArrayList<PointSolution>();
}
// put point info
PointSolution sol = new PointSolution(2);
sol.setObjective(0, -Double.parseDouble(values[8]));
sol.setObjective(1, -Double.parseDouble(values[9]));
variable[run].add(sol);
}
return dset;
}
}
| 8,805 | 36.632479 | 150 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/analysis/CoverageIndicator.java | package lu.uni.svv.PriorityAssignment.analysis;
import org.uma.jmetal.qualityindicator.impl.GenericIndicator;
import org.uma.jmetal.solution.Solution;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.front.Front;
import org.uma.jmetal.util.front.imp.ArrayFront;
import org.uma.jmetal.util.point.Point;
import java.io.FileNotFoundException;
import java.util.List;
/**
* Coverage Indicator (known as C or CS )
* C(A, B) gauges the proportion of solutions of B that are weakly dominated by at least one solution of A
* @param <S>
*/
public class CoverageIndicator<S extends Solution<?>> extends GenericIndicator<S> {
boolean isUnique = false;
public CoverageIndicator(String referenceParetoFrontFile, boolean considerUnique) throws FileNotFoundException {
super(referenceParetoFrontFile);
isUnique = considerUnique;
}
public CoverageIndicator(Front referenceParetoFront, boolean considerUnique) {
super(referenceParetoFront);
isUnique = considerUnique;
}
public Double evaluate(List<S> solutionList) {
if (solutionList == null) {
throw new JMetalException("The pareto front approximation is null");
} else {
if (this.isUnique){
return this.calculateUnique(new ArrayFront(solutionList), this.referenceParetoFront);
}
else {
return this.calculate(new ArrayFront(solutionList), this.referenceParetoFront);
}
}
}
/**
* Calculate the proportion of solutions of B that are weakly dominated by at least one solution of A
* @param A
* @param B
* @return
*/
public double calculate(Front A, Front B) {
List<Point> dominated = DominateUtils.getSomeWeeklyDominatedSolutions(B, A);
return dominated.size() / (double)B.getNumberOfPoints();
}
public double calculateUnique(Front A, Front B) {
List<Point> uniqueA = DominateUtils.getUniqueSolutions(A);
List<Point> uniqueB = DominateUtils.getUniqueSolutions(B);
List<Point> dominated = DominateUtils.getSomeWeeklyDominatedSolutions(uniqueB, uniqueA);
return dominated.size() / (double)uniqueB.size();
}
public String getName() {
return "CS";
}
public String getDescription() {
return "CS indicator";
}
public boolean isTheLowerTheIndicatorValueTheBetter() {
return false;
}
}
| 2,465 | 31.025974 | 116 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/analysis/DominateUtils.java | package lu.uni.svv.PriorityAssignment.analysis;
import org.uma.jmetal.util.front.Front;
import org.uma.jmetal.util.front.imp.ArrayFront;
import org.uma.jmetal.util.point.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DominateUtils {
/**
* Return a unique non-dominated solutsion in a front (remove duplicate solutions)
* Assuming that the search to minimize objectives
* a subset of solutions (A_unf) in the front (A) that
* the solutions in A_unf belong in the front A and
* the solutions in A_unf do weakly dominate the front A and
* for the different i and j, a solution a_j in A_unf should not weakly dominate a solution a_i in A_unf
* @param front
*/
public static List<Point> getUniqueSolutions(Front front){
List<Point> uniques = new ArrayList<>();
for (int j=0; j<front.getNumberOfPoints(); j++){
Point a = front.getPoint(j);
boolean flag = true;
for (int i=0; i<uniques.size(); i++){
if ( isWeaklyDominate(a, uniques.get(i)) ){
flag=false;
break;
}
}
if(flag) uniques.add(a);
}
return uniques;
}
/**
* Get the set of solutions in A that are weakly dominated by some solution of B
* Parameter types are the Front
* @param frontA
* @param frontB
*/
public static List<Point> getSomeWeeklyDominatedSolutions(Front frontA, Front frontB){
List<Point> ret = new ArrayList<>();
// for all points A
for(int x=0; x<frontA.getNumberOfPoints(); x++){
Point a = frontA.getPoint(x);
// checking conditions
boolean flag = false;
for(int y=0; y<frontB.getNumberOfPoints(); y++){
Point b = frontB.getPoint(y);
if (isWeaklyDominate(b, a)){
flag = true;
break;
}
}
if (flag) ret.add(a);
}
return ret;
}
/**
* Get the set of solutions in A that are weakly dominated by some solution of B
* Parameter types are the List<Point>
* @param frontA
* @param frontB
*/
public static List<Point> getSomeWeeklyDominatedSolutions(List<Point> frontA, List<Point> frontB){
List<Point> ret = new ArrayList<>();
// for all solutions in frontA
for (Point a : frontA){
// checking if solution a is dominated by any solution in frontB
boolean flag = false;
for(Point b: frontB){
if (isWeaklyDominate(b, a)){
flag = true;
break;
}
}
if (flag) ret.add(a);
}
return ret;
}
/**
* Return a subset of solutions (A_unf) in the front (A) that
* the solutions in A_unf belong in the front A and
* the solutions in A_unf do weakly dominate the front A and
* for the different i and j, a solution a_j in A_unf should not weakly dominate a solution a_i in A_unf
*/
public static List<Point> getNonDominateSolutions(Front front, Front ref){
List<Point> ret = new ArrayList<>();
for (int j=0; j<front.getNumberOfPoints(); j++){
Point a = front.getPoint(j);
boolean flag = true;
for (int i=0; i<ref.getNumberOfPoints(); i++){
if ( isDominate(ref.getPoint(i), a) ){
flag=false;
break;
}
}
if(flag) ret.add(a);
}
return ret;
}
/**
* Return a subset of solutions in the front (A) that are non-dominated by solutions in the front ref
*/
public static List<Point> getNonDominateSolutions(List<Point> front, List<Point> ref){
List<Point> ret = new ArrayList<>();
for (int j=0; j<front.size(); j++){
Point a = front.get(j);
boolean flag = true;
for (int i=0; i<ref.size(); i++){
if ( isDominate(ref.get(i), a) ){
flag=false;
break;
}
}
if(flag) ret.add(a);
}
return ret;
}
/**
* Get the set of solutions in front A that are not comparable to solutions in front B
* frontA_{\not\preceq \cap \not\succ frontB} =
* @param frontA
* @param frontB
* @return
*/
public static List<Point> getNotComparableSolutions(Front frontA, Front frontB){
List<Point> C = getIntersectionFront(frontA, frontB);
List<Point> W = getSomeDominateSolutions(frontA, frontB);
List<Point> L = getSomeDominatedSolutions(frontA, frontB);
List<Point> union = getUnionPoints(C, W);
union = getUnionPoints(union, L);
// Different set (frontA - union set)
List<Point> unique = new ArrayList<>();
for(int x=0; x<frontA.getNumberOfPoints(); x++){
Point a = frontA.getPoint(x);
boolean flag = true;
for(Point u: union){
if(isDuplicate(a, u)) flag = false;
}
if (flag) unique.add(a);
}
return unique;
}
public static boolean isDuplicate(Point a, Point b){
for(int t=0; t<a.getDimension(); t++){
if (a.getValue(t)!=b.getValue(t)) return false;
}
return true;
}
public static List<Point> getUnionPoints(List<Point> setA, List<Point> setB){
List<Point> union = new ArrayList<>();
for(Point a: setA){ union.add(a); }
for(Point b: setB){
boolean flag = true;
for(Point u:union) {
if (isDuplicate(b, u)){
flag=false;
break;
}
}
// add point b if it is not included in the union set
if (flag) union.add(b);
}
return union;
}
/**
* Return a subset of solutions that exist in front A and front B
*/
public static List<Point> getIntersectionFront(Front A, Front B){
List<Point> intersection = new ArrayList<>();
// looping front A
for (int x=0; x<A.getNumberOfPoints(); x++){
Point a = A.getPoint(x);
// looping front B
for (int y=0; y<B.getNumberOfPoints(); y++){
Point b = B.getPoint(y);
// check whether b is the same with a
boolean flag = true;
for(int i=0; i<a.getDimension(); i++){
if (a.getValue(i) != b.getValue(i)) {
flag = false;
break;
}
}
// add a to intersection if a is equal to b
if (flag) {
intersection.add(a);
break;
}
}
}
return intersection;
}
/**
* Get the set of solutions in A that are dominated by some solution of B
* frontA_{\prec frontB}
* @param frontA
* @param frontB
*/
public static List<Point> getSomeDominatedSolutions(Front frontA, Front frontB){
List<Point> ret = new ArrayList<>();
// for all points A
for(int x=0; x<frontA.getNumberOfPoints(); x++){
Point a = frontA.getPoint(x);
// checking conditions
boolean flag = false;
for(int y=0; y<frontB.getNumberOfPoints(); y++){
Point b = frontB.getPoint(y);
if (isDominate(b, a)){
flag = true;
break;
}
}
if (flag) ret.add(a);
}
return ret;
}
/**
* Get the set of solutions in A that dominate some solution of B
* frontA_{\prec frontB}
* @param frontA
* @param frontB
*/
public static List<Point> getSomeDominateSolutions(Front frontA, Front frontB){
List<Point> ret = new ArrayList<>();
for(int x=0; x<frontA.getNumberOfPoints(); x++){
Point a = frontA.getPoint(x);
boolean flag = false;
for(int y=0; y<frontB.getNumberOfPoints(); y++){
Point b = frontB.getPoint(y);
if (isDominate(a, b)){
flag=true;
break;
}
}
if (flag) ret.add(a);
}
return ret;
}
/**
* return TRUE whether the point a dominates b
* This function assumes the minimization scenario (minimum value is higher value for each objective)
* This function compares the values for each objective in both points whether a_i <= b_i, 1<=i<=m, m is the number of objectives
* This function compares the dominance for each objective in the points a_i <= b_i, 1<=i<=m, m is the number of objectives
* @param a
* @param b
* @return
*/
public static boolean isDominate(Point a, Point b){
boolean flag = isWeaklyDominate(a, b);
if (!flag) return false;
for (int i=0; i<a.getDimension(); i++){
if (a.getValue(i) < b.getValue(i)){
return true;
}
}
return false;
}
/**
* return TRUE whether the point a does weakly dominate b
* This function assumes the minimization scenario (minimum value is higher value for each objective)
* This function compares the dominance for each objective in the points (a_i <= b_i, 1<=i<=m, m is the number of objectives)
* @param a
* @param b
* @return
*/
public static boolean isWeaklyDominate(Point a, Point b){
for (int i=0; i<a.getDimension(); i++){
if (!(a.getValue(i) <= b.getValue(i))){
return false;
}
}
return true;
}
}
| 10,051 | 31.425806 | 133 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/analysis/Spacing.java | package lu.uni.svv.PriorityAssignment.analysis;
import org.uma.jmetal.qualityindicator.impl.GenericIndicator;
import org.uma.jmetal.solution.Solution;
import org.uma.jmetal.util.JMetalException;
import org.uma.jmetal.util.front.Front;
import org.uma.jmetal.util.front.imp.ArrayFront;
import org.uma.jmetal.util.front.util.FrontUtils;
import org.uma.jmetal.util.point.Point;
import java.io.FileNotFoundException;
import java.util.List;
/**
* Spacing indicator
* The indicator assumes the minimization scenario in search
* The lower the value, the better the uniformity
* The indicator does not need reference Pareto front
* This class implemented following
* Jason R. Schoott's Thesis (1995) "Fault Tolerant Design using Single and Multicriteria Genetic Algorithm Optimization"
* Li, M., & Yao, X. (2019) "Quality evaluation of solution sets in multiobjective optimisation: A survey". In ACM Computing Surveys (Vol. 52, Issue 2). https://doi.org/10.1145/3300148
* @param <S>
*/
public class Spacing<S extends Solution<?>> extends GenericIndicator<S> {
public Spacing() {
}
// Hide a Creator that takes reference Pareto front
private Spacing(String referenceParetoFrontFile) throws FileNotFoundException {
super(referenceParetoFrontFile);
}
// Hide a Creator that takes reference Pareto front
private Spacing(Front referenceParetoFront) {
super(referenceParetoFront);
}
public Double evaluate(List<S> solutionList) {
if (solutionList == null) {
throw new JMetalException("The pareto front approximation is null");
}
else if (solutionList.size()==1){
return 0.0D; //throw new JMetalException("Not enough number of solutions in the pareto front");
}
else{
return this.calculate(new ArrayFront(solutionList));
}
}
public double calculate(Front front) {
// calculate distance for each point
double[] dists = new double[front.getNumberOfPoints()];
for(int i = 0; i < front.getNumberOfPoints(); ++i) {
dists[i] = minDistance(i, front);
}
// calculate spacing
double avgDist = average(dists);
double sum = 0.0D;
for(int i = 0; i < front.getNumberOfPoints(); ++i) {
sum += Math.pow(avgDist - dists[i], 2);
}
double weight = 1.0D / (front.getNumberOfPoints()-1.0D);
return Math.sqrt(weight * sum);
}
public double average(double[] items){
double sum = 0.0D;
for(int i = 0; i < items.length; ++i) {
sum += items[i];
}
return sum/items.length;
}
public double minDistance(int index, Front A){
Point given = A.getPoint(index);
// calculate min distance
double minDist = Double.MAX_VALUE;
for(int x = 0; x < A.getNumberOfPoints(); ++x) {
if (index==x) continue; // to prevent every minDist equal to 0
double dist = manhattanDistance(given, A.getPoint(x));
minDist = Math.min(minDist, dist);
}
return minDist;
}
public double manhattanDistance(Point a, Point b) {
double dist = 0.0D;
for (int j = 0; j < a.getDimension(); ++j) {
dist += Math.abs(a.getValue(j) - b.getValue(j));
}
return dist;
}
public String getName() {
return "SP";
}
public String getDescription() {
return "Spacing indicator";
}
public boolean isTheLowerTheIndicatorValueTheBetter() {
return true;
}
}
| 3,594 | 32.287037 | 188 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/analysis/QIEvaluatorExt.java | package lu.uni.svv.PriorityAssignment.analysis;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import lu.uni.svv.PriorityAssignment.Initializer;
import lu.uni.svv.PriorityAssignment.utils.GAWriter;
import lu.uni.svv.PriorityAssignment.utils.Settings;
import org.uma.jmetal.util.JMetalLogger;
import org.uma.jmetal.util.point.PointSolution;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
public class QIEvaluatorExt extends QIEvaluator {
public static void main(String[] args) throws Exception {
// Environment Settings
Initializer.initLogger();
Settings.update(args);
GAWriter.init(null, false);
// define output paths
String[] approaches = Settings.APPROACHES.split(",");
String[] paths = new String[]{Settings.COMPARE_PATH1, Settings.COMPARE_PATH2};
new QIEvaluatorExt().run(approaches, paths, Settings.OUTPUT_PATH,
Settings.RUN_CNT, Settings.NUM_TEST);
}
////////////////////////////////////////////////////////
// non-static members
////////////////////////////////////////////////////////
public QIEvaluatorExt() {}
public void run(String[] approaches, String[] paths, String output, int runNum, int testNum) throws Exception {
// create output file
GAWriter writer = new GAWriter(output, Level.INFO, null, "./", false);
StringBuilder title = new StringBuilder("TestID,Approach,Subject,Run");
for (String name:names){
title.append(",");
title.append(name);
}
title.append("\n");
writer.write(title.toString());
// load fitness
for(int testID=1; testID<=testNum; testID++){
String testStr = String.format("%d,", testID);
// load all populations
HashMap<String, List<PointSolution>[]> pops1 = this.load_fitness(paths[0], testID, runNum);
HashMap<String, List<PointSolution>[]> pops2 = this.load_fitness(paths[1], testID, runNum);
// calculate QIs for each subjects
Set<String> subjects = pops1.keySet();
for (String subject:subjects) {
// if (subject.compareTo("ESAIL")==0) continue;
JMetalLogger.logger.info(String.format("[Test%02d] Calculating quality indicators for %s...", testID,subject));
// Generate reference Pareto
List<PointSolution>[] pops1Run = pops1.get(subject);
List<PointSolution>[] pops2Run = pops2.get(subject);
// calculate QI values
if (initializeQIs(pops1Run, pops2Run)) {
for(int runID=0; runID<runNum; runID++)
writer.write(testStr + calculate(runID, approaches[0], subject, pops1Run[runID]));
for(int runID=0; runID<runNum; runID++)
writer.write(testStr + calculate(runID, approaches[1], subject, pops2Run[runID]));
}
else{
for(int runID=0; runID<runNum; runID++)
writer.write(testStr + calculateForError(runID, approaches[0], subject));
for(int runID=0; runID<runNum; runID++)
writer.write(testStr + calculateForError(runID, approaches[1], subject));
}
}
JMetalLogger.logger.info("Calculating quality indicators...Done.");
}
writer.close();
}
/**
* Load fitness values from the result file
* To treat the fitness values as the same way as we do in the search (minimize the objectives),
* we multiply -1 to the fitness values
* @param filename
* @param runNum
* @return
* @throws IOException
*/
public HashMap<String, List<PointSolution>[]> load_fitness(String filename, int numTest, int runNum) throws IOException, CsvValidationException {
HashMap<String, List<PointSolution>[]> dset = new HashMap<>();
List<List<PointSolution>[]> list = new ArrayList<List<PointSolution>[]>();
// read csv file
CSVReader csvReader = new CSVReader(new FileReader(filename));
csvReader.readNext(); // throw header
String[] values = null;
while ((values = csvReader.readNext()) != null) {
String subject = values[0];
int run = Integer.parseInt(values[1])-1; // -1 for using as a index
int testID = Integer.parseInt(values[2]);
if (testID!=numTest) continue;
List<PointSolution>[] variable = null;
if (dset.containsKey(subject)==false){
variable = new ArrayList[runNum];
dset.put(subject, variable);
}
else{
variable = dset.get(subject);
}
if (variable[run]==null){
variable[run] = new ArrayList<PointSolution>();
}
// put point info
PointSolution sol = new PointSolution(2);
sol.setObjective(0, -Double.parseDouble(values[5]));
sol.setObjective(1, -Double.parseDouble(values[6]));
variable[run].add(sol);
}
return dset;
}
}
| 4,629 | 32.309353 | 146 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/utils/GAWriter.java | package lu.uni.svv.PriorityAssignment.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import org.apache.commons.io.FileUtils;
public class GAWriter {
/**
* Static path setting, the init function should be excuted at the beginning
*/
private static String basePath = "";
public static void setBasePath(String _path){ basePath = _path; }
public static String getBasePath(){ return GAWriter.basePath; }
public static void init(String _path, boolean makeEmpty){
// Only apply to multi run mode
if (_path == null){
_path = Settings.BASE_PATH;
if (Settings.RUN_NUM != 0){
_path += String.format("/Run%02d", Settings.RUN_NUM);
}
}
basePath = _path;
if (makeEmpty) {
File dir = new File(basePath);
if (dir.exists()) {
try {
FileUtils.deleteDirectory(dir);
} catch (IOException e) {
System.out.println("Failed to delete results");
e.printStackTrace();
}
}
}
}
/**
* Class members
*/
private BufferedWriter logger = null;
private Level level = Level.INFO;
public GAWriter(String _filename, Level _level, String _title) {
this(_filename, _level, _title,null, false);
}
public GAWriter(String _filename, Level _level, String _title, String _path){
this(_filename, _level, _title, _path, false);
}
public GAWriter(String _filename, Level _level, String _title, String _path, boolean _append) {
this.level = _level;
if (_path == null){
_path = basePath;
}
String filename = "";
if (_path == null || _path.length()==0)
filename = _filename;
else
filename = _path+"/"+_filename;
File fileObj = new File(filename);
// Create parent folder
File parent = fileObj.getParentFile();
if (!parent.exists()){
if (!fileObj.getParentFile().mkdirs()) {
System.out.println("Creating folder error: "+fileObj.getAbsolutePath());
System.exit(1);
}
}
// create output file
boolean flagTitle = false;
if (!fileObj.exists() && _title != null) flagTitle = true;
FileWriter fw = null;
try {
fw = new FileWriter(fileObj.getAbsolutePath(), _append);
logger = new BufferedWriter(fw);
if (flagTitle){
this.info(_title);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
public void close()
{
try {
logger.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void print(String msg) {
if (!(level==Level.INFO || level==Level.FINE)) return;
try {
System.out.print(msg);
logger.write(msg);
logger.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void write(String msg) {
try {
logger.write(msg);
logger.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void info(String msg) {
if (!(level==Level.INFO || level==Level.FINE)) return;
try {
logger.write(msg+"\n");
logger.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void fine(String msg) {
if (!(level == Level.FINE)) return;
try {
logger.write(msg + "\n");
logger.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 3,260 | 21.033784 | 96 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/utils/StoreManger.java | package lu.uni.svv.PriorityAssignment.utils;
import lu.uni.svv.PriorityAssignment.arrivals.Arrivals;
import java.util.Formatter;
import java.util.logging.Level;
public class StoreManger {
public static void storePriority(Integer[] priorities, String filename){
// convert priority
StringBuilder sb = new StringBuilder();
sb.append("[ ");
for (int x=0; x < priorities.length; x++) {
sb.append(priorities[x]);
if (x!=(priorities.length-1))
sb.append(", ");
}
sb.append(" ]");
// store priority
GAWriter writer = new GAWriter(filename, Level.FINE, null);
writer.info(sb.toString());
writer.close();
}
public static void storeArrivals(Arrivals[] arrivals, String filename){
GAWriter writer = new GAWriter(filename, Level.FINE, null);
StringBuilder sb = new StringBuilder();
Formatter fmt = new Formatter(sb);
sb.append("[\n");
for (int x=0; x < arrivals.length; x++) {
sb.append("\t");
fmt.format("[");
Arrivals item = arrivals[x];
for(int i=0; i< item.size(); i++) {
fmt.format("%d", item.get(i));
if ( item.size() > (i+1) )
sb.append(",");
}
fmt.format("]");
if (x!=(arrivals.length-1))
sb.append(",");
sb.append("\n");
}
sb.append("]");
writer.info(sb.toString());
writer.close();
}
}
| 1,297 | 23.037037 | 73 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/utils/Utils.java | package lu.uni.svv.PriorityAssignment.utils;
public class Utils {
public static void printMemory(String _msg){
Runtime runtime = Runtime.getRuntime();
double max = runtime.maxMemory()/ 1000000000.0;
double total = runtime.totalMemory()/1000000000.0;
double free = runtime.freeMemory()/1000000000.0;
System.out.println(String.format("\tMemory(%s): max(%.2fG), total(%.2fG), free(%.2fG), used(%.2fG))", _msg, max, total, free, total-free));
}
}
| 461 | 32 | 141 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/utils/Settings.java | package lu.uni.svv.PriorityAssignment.utils;
import java.io.*;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import lu.uni.svv.PriorityAssignment.utils.ArgumentParser.DataType;
public class Settings {
public static String SettingFile = "settings.json";
// common parameter
public static String INPUT_FILE = "";
public static String BASE_PATH = "results";
public static int RUN_NUM = 0;
public static int RUN_START = 1;
public static int RUN_CNT = 0;
public static int CYCLE_NUM = 1;
public static int N_CPUS = 1;
public static boolean RANDOM_PRIORITY = false;
// Scheduler
public static String SCHEDULER = "";
public static String TARGET_TASKLIST = "";
public static int[] TARGET_TASKS = null;
public static double TIME_QUANTA = 0.1;
public static double TIME_MAX = 60000; // ase unit ms
public static boolean ALLOW_OFFSET_RANGE = false;
public static boolean EXTEND_SIMULATION_TIME = true;
public static int ADDITIONAL_SIMULATION_TIME = 0;
public static boolean EXTEND_SCHEDULER = true;
public static double FD_BASE = 2;
public static double FD_EXPONENT = 10000;
public static int MAX_OVER_DEADLINE = 1000; // ase unit ms
public static boolean VERIFY_SCHEDULE = false;
// Phase1 GA
public static int P1_POPULATION = 10;
public static int P1_ITERATION = 1000;
public static double P1_CROSSOVER_PROB = 0.9;
public static double P1_MUTATION_PROB = 0.5;
public static String P1_GROUP_FITNESS = "average";
public static String P1_ALGORITHM = "SSGA";
//printing
public static boolean PRINT_FITNESS = false;
public static boolean PRINT_DETAILS = false;
public static boolean PRINT_FINAL_DETAIL = true;
public static boolean PRINT_INTERNAL_FITNESS = false;
//Second phase
public static int P2_POPULATION = 10;
public static int P2_ITERATIONS = 1000;
public static double P2_CROSSOVER_PROB = 0.8;
public static double P2_MUTATION_PROB = 0;
public static String P2_GROUP_FITNESS = "average";
public static boolean P2_SIMPLE_SEARCH = false;
public static String TEST_GENERATION = ""; // "", Random, Initial
public static String TEST_PATH = "";
public static int NUM_TEST = 10;
public static boolean NOLIMIT_POPULATION = false;
public static String TIME_LIMIT = "";
public static long TIME_LIMITATION = 0;
//Results Evaluator options
public static String COMPARE_PATH1 = "";
public static String COMPARE_PATH2 = "";
public static String OUTPUT_PATH = "";
public static String APPROACHES = "";
public Settings()
{
}
public static void update(String[] args) throws Exception {
// Setting arguments
ArgumentParser parser = new ArgumentParser();
parser.addOption(false,"Help", DataType.BOOLEAN, "h", "help", "Show how to use this program", false);
parser.addOption(false,"SettingFile", DataType.STRING, "f", null, "Base setting file.", SettingFile);
parser.addOption(false,"INPUT_FILE", DataType.STRING, null, "data", "input data that including job information");
parser.addOption(false,"BASE_PATH", DataType.STRING, "b", null, "Base path to save the result of experiments");
parser.addOption(false,"RUN_NUM", DataType.INTEGER, null, "runID", "Specific run ID when you execute run separately");
parser.addOption(false,"CYCLE_NUM", DataType.INTEGER, null, "cycle", "Specific run ID when you execute run separately");
parser.addOption(false,"N_CPUS", DataType.INTEGER, null, "cpus", "the number of CPUs");
parser.addOption(false,"RANDOM_PRIORITY", DataType.BOOLEAN, null, "random", "random priority");
parser.addOption(false,"RUN_START", DataType.INTEGER, null, "runStart", "starting number of run ID");
parser.addOption(false,"RUN_CNT", DataType.INTEGER, null, "runCnt", "number of runs");
//scheduler
parser.addOption(false,"SCHEDULER", DataType.STRING, "s", null, "Scheduler");
parser.addOption(false,"TARGET_TASKLIST", DataType.STRING, "t", "targets","target tasks for search");
parser.addOption(false,"TIME_QUANTA", DataType.DOUBLE, null, "quanta", "Scheduler time quanta");
parser.addOption(false,"TIME_MAX", DataType.DOUBLE, null, "max", "scheduler time max");
parser.addOption(false,"ALLOW_OFFSET_RANGE", DataType.BOOLEAN, null, "offsetRange", "Use offset value as a range from 0 to the Offset value");
parser.addOption(false,"EXTEND_SIMULATION_TIME", DataType.BOOLEAN, null, "extendSimulTime", "Extend simulation time");
parser.addOption(false,"ADDITIONAL_SIMULATION_TIME", DataType.INTEGER, null, "addMaxTime", "The length of simulation time");
parser.addOption(false,"EXTEND_SCHEDULER", DataType.BOOLEAN, null, "extendScheduler", "Scheduler extend when they finished simulation time, but the queue remains");
parser.addOption(false,"FD_BASE", DataType.DOUBLE, null, "base", "base for F_D calculation");
parser.addOption(false,"FD_EXPONENT", DataType.DOUBLE, null, "exponent", "exponent for F_D calculation");
parser.addOption(false,"MAX_OVER_DEADLINE", DataType.INTEGER, null, "maxMissed", "The maximum value for the one execution's deadline miss(e-d)");
parser.addOption(false,"VERIFY_SCHEDULE", DataType.BOOLEAN, null, "verifySchedule", "Do verification process of schedule result when it set");
// Phase 1 GA
parser.addOption(false,"P1_POPULATION", DataType.INTEGER, null, "p1", "Population for GA");
parser.addOption(false,"P1_ITERATION", DataType.INTEGER, null, "i1", "Maximum iterations for GA");
parser.addOption(false,"P1_CROSSOVER_PROB", DataType.DOUBLE, null, "c1", "Crossover rate for GA");
parser.addOption(false,"P1_MUTATION_PROB", DataType.DOUBLE, null, "m1", "Mutation rate for GA");
parser.addOption(false,"P1_GROUP_FITNESS", DataType.STRING, null, "fg1", "one type of fitness among average, maximum or minimum");
parser.addOption(false,"P1_ALGORITHM", DataType.STRING, null, "algo1", "Simple search mode, not using crossover and mutation just produce children randomly in phase 1");
// print results
parser.addOption(false,"PRINT_FITNESS", DataType.BOOLEAN, null, "printFitness", "If you set this parameter, The program will produce fitness detail information");
parser.addOption(false,"PRINT_DETAILS", DataType.BOOLEAN, null, "printDetails", "If you set this parameter, The program will produce detail information");
parser.addOption(false,"PRINT_FINAL_DETAIL", DataType.BOOLEAN, null, "printFinal", "If you set this parameter, The program will produce detail information for final cycle");
parser.addOption(false,"PRINT_INTERNAL_FITNESS", DataType.BOOLEAN, null, "printInternal", "If you set this parameter, The program will produce internal arrival fitness for each cycle");
// Second phase GA
parser.addOption(false,"P2_POPULATION", DataType.INTEGER, null, "p2", "Population size for NSGA-II");
parser.addOption(false,"P2_ITERATIONS", DataType.INTEGER, null, "i2", "Maximum iterations for NSGA-II");
parser.addOption(false,"P2_CROSSOVER_PROB", DataType.DOUBLE, null, "c2", "Crossover rate for GA2");
parser.addOption(false,"P2_MUTATION_PROB", DataType.DOUBLE, null, "m2", "Mutation rate for GA");
parser.addOption(false,"P2_GROUP_FITNESS", DataType.STRING, null, "fg2", "one type of fitness among average, maximum or minimum");
parser.addOption(false,"P2_SIMPLE_SEARCH", DataType.BOOLEAN, null, "simpleP2", "Simple search mode, not using crossover and mutation just produce children randomly in phase 2");
parser.addOption(false,"TEST_GENERATION", DataType.STRING, null, "genTest", "search mode: Normal, Random, Initial");
parser.addOption(false,"TEST_PATH", DataType.STRING, null, "testPath", "path to load test data");
parser.addOption(false,"NUM_TEST", DataType.INTEGER, null, "numTest", "The number of test arrivals");
parser.addOption(false,"NOLIMIT_POPULATION", DataType.BOOLEAN, null, "nolimitPop", "Apply limit population for external fitness");
parser.addOption(false,"TIME_LIMIT", DataType.STRING, null, "timeLimit", "execution time of limitation specify by a format HH:MM:SS");
//experiment options
parser.addOption(false,"COMPARE_PATH1", DataType.STRING, null, "compare1", "target path to compare");
parser.addOption(false,"COMPARE_PATH2", DataType.STRING, null, "compare2", "target path to compare");
parser.addOption(false,"OUTPUT_PATH", DataType.STRING, null, "output", "output path for QI evaluators");
parser.addOption(false,"APPROACHES", DataType.STRING, null, "apprs", "a list of approaches");
// parsing args
try{
parser.parseArgs(args);
}
catch(Exception e)
{
System.out.println("Error: "+e.getMessage());
System.out.println("");
System.out.println(parser.getHelpMsg());
System.exit(0);
}
if((Boolean)parser.getParam("Help")){
System.out.println(parser.getHelpMsg());
System.exit(1);
}
// Load settings from file
String filename = (String)parser.getParam("SettingFile");
Settings.updateSettings(filename); //Update settings from the settings.json file.
updateFromParser(parser); //Update settings from the command parameters
Settings.TARGET_TASKS = convertToIntArray(Settings.TARGET_TASKLIST);
Arrays.sort(Settings.TARGET_TASKS);
if (Settings.TIME_LIMIT.length()>0){
Settings.TIME_LIMITATION = convertTimeToLong(Settings.TIME_LIMIT);
}
}
public static long convertTimeToLong(String _timeStr){
long milliseconds=0;
_timeStr = "1970-01-01 "+_timeStr+" GMT";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
ZonedDateTime zonedDateTime = ZonedDateTime.parse(_timeStr, formatter);
LocalDateTime ldt = zonedDateTime.toLocalDateTime();
milliseconds = zonedDateTime.toEpochSecond()*1000;
return milliseconds;
}
public static int[] convertToIntArray(String commaSeparatedStr) {
if (commaSeparatedStr.startsWith("["))
commaSeparatedStr = commaSeparatedStr.substring(1);
if (commaSeparatedStr.endsWith("]"))
commaSeparatedStr = commaSeparatedStr.substring(0,commaSeparatedStr.length()-1);
int[] result = null;
if (commaSeparatedStr.trim().length()==0){
result = new int[0];
}
else {
String[] commaSeparatedArr = commaSeparatedStr.split("\\s*,\\s*");
result = new int[commaSeparatedArr.length];
for (int x = 0; x < commaSeparatedArr.length; x++) {
result[x] = Integer.parseInt(commaSeparatedArr[x]);
}
}
return result;
}
/**
* update setting information from json file
* @param filename
* @throws Exception
*/
public static void updateSettings(String filename) throws Exception {
// Parse Json
String jsontext = readPureJsonText(filename);
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject)parser.parse(jsontext);
for (Object key:json.keySet()) { // for in setting file keys
// find key in the Class fields
Field field = findKeyField(key.toString());
if (field == null) {
throw new Exception("Cannot find variable \"" + key + "\" in setting Class.");
}
// set value from setting file to class
field.setAccessible(true);
Object type = field.getType();
Object value = json.get(key);
if (type == int.class || type == long.class) {
field.set(Settings.class, Integer.parseInt(value.toString()));
} else if (type == float.class || type == double.class) {
field.set(Settings.class, Double.parseDouble(value.toString()));
} else if (type == boolean.class) {
field.set(Settings.class, value);
} else {
field.set(Settings.class, value.toString());
}
field.setAccessible(false);
}
}
/**
* update setting information from json file
* @param _parser
* @throws Exception
*/
public static void updateFromParser(ArgumentParser _parser) throws Exception {
for (String key:_parser.keySet()){
if (key.compareTo("Help")==0) continue;
if (key.compareTo("SettingFile")==0) continue;
// find key in the Class fields
Field field = findKeyField(key);
if (field == null) {
throw new Exception("Cannot find variable \"" + key + "\" in setting Class.");
}
// Set value
DataType paramType = _parser.getDataType(key);
Object paramValue = _parser.getParam(key);
try {
field.setAccessible(true);
if (paramType==DataType.STRING)
field.set(null, (String)paramValue);
else if (paramType==DataType.INTEGER)
field.setInt(null, (Integer)paramValue);
else if (paramType==DataType.BOOLEAN)
field.setBoolean(null, (Boolean)paramValue);
else if (paramType==DataType.DOUBLE)
field.setDouble(null, (Double)paramValue);
else {
throw new Exception("Undefined data type for " + field.getName());
}
field.setAccessible(false);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
private static Field findKeyField(String key){
Field[] fields = Settings.class.getFields();
Field field = null;
for (Field item : fields) {
if (key.compareTo(item.getName()) == 0) {
field = item;
break;
}
}
return field;
}
/**
* Setting text to Pure json text
* @param filename
* @return
* @throws IOException
* @throws Exception
*/
public static String readPureJsonText(String filename) throws IOException, Exception{
StringBuilder content = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(filename));
while (true) {
String line = br.readLine();
if (line == null) break;
// remove comment
int idx = getCommentIdx(line);
if (idx >= 0){
line = line.substring(0, idx);
}
// append them into content
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
private static int getCommentIdx(String s) {
int idx = -1;
if (s == null && s.length() <=1) return idx;
boolean string = false;
for(int x=0; x<s.length(); x++) {
if (!string && s.charAt(x) == '\"'){string = true; continue;} // string start
if (string)
{
if (s.charAt(x) == '\\') {x++; continue;} // escape
if (s.charAt(x) == '\"') {string = false; continue;} // string end
continue;
}
if (s.charAt(x) == '/' && s.charAt(x+1) == '/'){
idx = x;
break;
}
}
return idx;
}
/**
* convert Class Properties to string
*/
public static String getString(){
Field[] fields = Settings.class.getFields();
StringBuilder sb = new StringBuilder();
sb.append("---------------------Settings----------------------\n");
for (Field field:fields){
sb.append(String.format("%-20s: ",field.getName()));
field.setAccessible(true);
Object value;
try {
value = field.get(Settings.class);
}catch(IllegalAccessException e){
value = "";
}
if (value instanceof Integer) sb.append((Integer)value);
if (value instanceof Double) sb.append((Double)value);
if (value instanceof Boolean) sb.append((Boolean)value);
if (value instanceof String){
sb.append("\"");
sb.append((String)value);
sb.append("\"");
}
if (value instanceof int[]){
sb.append("[");
for (int x=0; x<((int[]) value).length; x++){
if (x!=0) sb.append(", ");
sb.append(((int[])value)[x]);
}
sb.append("]");
}
sb.append("\n");
}
sb.append("---------------------------------------------------\n\n");
return sb.toString();
}
}
| 15,799 | 38.798489 | 187 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/utils/RandomGenerator.java | package lu.uni.svv.PriorityAssignment.utils;
import java.util.Random;
public class RandomGenerator extends Random {
/**
*
*/
private static final long serialVersionUID = -3933147870525869710L;
public RandomGenerator()
{
super();
}
/**
* This function returns the random number between _start and _end including its border number.
* For example, if you give 10 and 20 as parameters respectively for _start and _end,
* this function returns one number of [10, 20].
* @param _start
* @param _end
* @return one number of [_start, _end] including _start and _end
*/
public int nextInt(int _start, int _end) {
int bound = _end - _start + 1;
int value = this.nextInt();
if (value < 0)
value = value *-1;
return (value % bound) + _start;
}
/**
* This function returns the random number between _start and _end including its border number.
* For example, if you give 10 and 20 as parameters respectively for _start and _end,
* this function returns one number of [10, 20].
* @param _start
* @param _end
* @return one number of [_start, _end] including _start and _end
*/
public long nextLong(long _start, long _end) {
long bound = _end - _start + 1;
long value = this.nextLong();
if (value < 0)
value = value *-1L;
return (value % bound) + _start;
}
}
| 1,319 | 25.938776 | 96 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/utils/UniqueList.java | package lu.uni.svv.PriorityAssignment.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class UniqueList {
private HashMap<Integer, ArrayList<Integer[]>> map;
private int size;
public UniqueList(){
this.map = new HashMap<>();
size = 0;
}
public boolean add(Integer[] item){
int key = hashCode(item);
ArrayList<Integer[]> list = map.get(key);
if (list != null){
int size = list.size();
for(int x=0; x<size; x++){
if (compareItem(list.get(x), item)) {
return false;
}
}
list.add(item);
}
else{
list = new ArrayList<>();
list.add(item);
map.put(key, list);
}
size++;
return true;
}
public boolean contains(Integer[] item){
int key = hashCode(item);
ArrayList<Integer[]> list = map.get(key);
if (list != null){
for(int x=0; x<list.size(); x++){
if (compareItem(list.get(x), item)) {
return true;
}
}
}
return false;
}
public boolean compareItem(Integer[] a, Integer[] b){
for(int x=0; x<a.length; x++){
if (!a[x].equals(b[x])) return false;
}
return true;
}
public int hashCode(Integer[] item){
int h = 0;
int size = item.length;
for (int i = 0; i < size; i++) {
h = 109*h + item[i];
}
return h;
}
public int size(){ return size; }
public Iterator<Integer> getIteratorKeys(){
return map.keySet().iterator();
}
public ArrayList<Integer[]> getSlot(Integer key){
return map.get(key);
}
}
| 1,480 | 17.746835 | 54 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/utils/ListUtil.java | package lu.uni.svv.PriorityAssignment.utils;
public class ListUtil {
public static double average(double[] list){
double value = 0.0;
for (int x = 0; x < list.length; x++)
value += (list[x]/list.length);
return value;
}
public static int averageIdx(double[] list){
int idx = 0;
double avg = average(list);
double[] diff = new double[list.length];
for (int x = 0; x < list.length; x++) {
diff[x] = Math.abs(list[x] - avg);
}
double min = diff[0];
for (int x = 1; x < diff.length; x++) {
if (diff[x] < min) {
min = diff[x];
idx = x;
}
}
return idx;
}
public static int maximumIdx(double[] list){
int idx = 0;
double value = list[0];
for (int x = 1; x < list.length; x++) {
if (list[x] > value) {
value = list[x];
idx = x;
}
}
return idx;
}
public static int minimumIdx(double[] list){
int idx = 0;
double value = list[0];
for (int x = 1; x < list.length; x++) {
if (list[x] < value) {
value = list[x];
idx = x;
}
}
return idx;
}
}
| 1,038 | 18.603774 | 45 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/utils/Monitor.java | package lu.uni.svv.PriorityAssignment.utils;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.HashMap;
public class Monitor {
public static HashMap<String, Long> times;
private static String workname = "";
private static long ts = 0;
public static long heapInit = 0;
public static long heapUsed = 0;
public static long heapCommit = 0;
public static long heapMax = 0;
public static long nonheapUsed = 0;
public static double kb = 1024.0;
public static double MB = 1024.0*1024.0;
public static double GB = 1024.0*1024.0*1024.0;
/**
* Initialize monitor class
* Use this function to measure total execution time and memory usages
* This function will save the time this function called with a key "all"
*/
public static void init(){
updateMemory();
Monitor.times = new HashMap<String, Long>();
Monitor.times.put("all", System.currentTimeMillis());
Monitor.workname = "";
}
/**
* Finish the monitor
* Use this function to measure total execution time and memory usages
* This function save the time difference between now and the previous value with a key "all"
*/
public static void finish() {
long ts = System.currentTimeMillis();
long prev = Monitor.times.get("all");
Monitor.times.put("all", ts - prev);
updateMemory();
}
/**
* This function starts to measure the time of a sub-work
* if you want to record time for different sub-work after called start(),
* you should call end() first to prevent a collision with the previous sub-work
* @param name
* @param cumulate this parameter lets you measure cumulative time for a particular-work
*/
public static void start(String name, boolean cumulate){
if (!cumulate) {
Monitor.times.put(name, System.currentTimeMillis());
}
else{
Monitor.ts = System.currentTimeMillis();
Monitor.workname = name;
}
}
/**
* This function saves time elapsed of a sub-work
* @param name a name of sub-work
* @param cumulate if you set cumulate when you use start(), you should set this parameter
*/
public static void end(String name, boolean cumulate){
long ts = System.currentTimeMillis();
if (!cumulate) {
long prev = Monitor.times.get(name);
Monitor.times.put(name, ts - prev);
}
else{
long prev = Monitor.times.containsKey(workname)?Monitor.times.get(workname):0;
Monitor.times.put(workname, prev + (ts - Monitor.ts));
}
}
/**
* Get a time elapsed
*/
public static long getTime(){
return Monitor.times.get("all");
}
/**
* Get a time elapsed for a particular sub-work
*/
public static long getTime(String name){
if (!Monitor.times.containsKey(name)) return 0;
return Monitor.times.get(name);
}
/**
* Update memory usages
*/
public static void updateMemory(){
MemoryMXBean membean = (MemoryMXBean) ManagementFactory.getMemoryMXBean();
MemoryUsage heap = membean.getHeapMemoryUsage();
MemoryUsage nonheap = membean.getNonHeapMemoryUsage();
Monitor.heapInit = (Monitor.heapInit < heap.getInit() ) ? heap.getInit() : Monitor.heapInit;
Monitor.heapUsed = (Monitor.heapUsed < heap.getUsed() ) ? heap.getUsed() : Monitor.heapUsed;
Monitor.heapCommit = (Monitor.heapCommit < heap.getCommitted() ) ? heap.getCommitted() : Monitor.heapCommit;
Monitor.heapMax = (Monitor.heapMax < heap.getMax() ) ? heap.getMax() : Monitor.heapMax;
Monitor.nonheapUsed = (Monitor.nonheapUsed < nonheap.getUsed() ) ? nonheap.getUsed() : Monitor.nonheapUsed;
}
/**
* get Memory usuage examples
*/
public static long[] getMemory() {
MemoryMXBean membean = (MemoryMXBean) ManagementFactory.getMemoryMXBean();
MemoryUsage heap = membean.getHeapMemoryUsage();
MemoryUsage nonheap = membean.getNonHeapMemoryUsage();
long heapInit = heap.getInit();
long heapUsed = heap.getUsed();
long heapCommit = heap.getCommitted();
long heapMax = heap.getMax();
long nonheapUsed = nonheap.getUsed();
long[] list = new long[5];
list[0] = heapInit;
list[0] = heapUsed;
list[1] = nonheapUsed;
list[2] = heapCommit;
list[3] = heapMax;
return list;
}
}
| 4,175 | 29.933333 | 110 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/utils/FileManager.java | package lu.uni.svv.PriorityAssignment.utils;
import lu.uni.svv.PriorityAssignment.arrivals.ArrivalProblem;
import lu.uni.svv.PriorityAssignment.arrivals.Arrivals;
import lu.uni.svv.PriorityAssignment.arrivals.ArrivalsSolution;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import org.uma.jmetal.util.JMetalLogger;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class FileManager {
/**
* Load Test Arrivals
* @return
*/
public static List<Arrivals[]> LoadTestArrivals(String _path, TaskDescriptor[] _input, int _simulationTime, int _numCnt) throws Exception{
// JMetalLogger.logger.info("Loading test arrivals....");
ArrivalProblem problemA = new ArrivalProblem(_input, null, _simulationTime, Settings.SCHEDULER);
List<Arrivals[]> arrivals = new ArrayList<>();
// load test file names
BufferedReader reader = new BufferedReader(new FileReader(_path));
String line = reader.readLine();
while(line!=null){
line = reader.readLine();
if (line==null || line.trim().compareTo("")==0) break;
String[] items = line.split("\t");
ArrivalsSolution sol = ArrivalsSolution.loadFromJSONString(problemA, items[items.length-1]);
arrivals.add(sol.toArray());
}
// selecting test files
if (_numCnt!=0) {
RandomGenerator random = new RandomGenerator();
while (arrivals.size() > _numCnt) {
int idx = random.nextInt(1, arrivals.size()) - 1;
arrivals.remove(idx);
}
}
if (arrivals.size()==0){
throw new Exception("No file to load arrivals");
}
// JMetalLogger.logger.info("Loading test arrivals....Done");
return arrivals;
}
public static List<String> listFilesUsingDirectoryStream(String dir) {
List<String> fileList = new ArrayList<>();
try {
DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(dir));
for (Path path : stream) {
if (!Files.isDirectory(path)) {
fileList.add(path.getFileName().toString());
}
}
}
catch (IOException e){
}
return fileList;
}
}
| 2,212 | 28.905405 | 139 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/utils/ArgumentParser.java | package lu.uni.svv.PriorityAssignment.utils;
import java.text.ParseException;
import java.util.*;
import java.util.function.Consumer;
public class ArgumentParser implements Iterable<HashSet>{
@Override
public Iterator<HashSet> iterator() {
return null;
}
@Override
public void forEach(Consumer<? super HashSet> action) {
}
public enum DataType {INTEGER, DOUBLE, STRING, BOOLEAN} ;
/**
* Internal optionsLong
*/
private List<String> variables;
private HashMap<String, Boolean> necessaries;
private HashMap<String, String> options; // to save short indicators
private HashMap<String, String> optionsIdx;
private HashMap<String, String> optionsLong; // to save long indicators
private HashMap<String, String> optionsLongIdx;
private HashMap<String, String> descriptions; // to save descriptions
private HashMap<String, DataType> datatypes;
private HashMap<String, Object> defaults;
private HashMap<String, Object> params; // to save parsed parameters
public int screen = 80; // screen length for showing message
/**
* Constructor
*/
public ArgumentParser() {
params = new HashMap<String, Object>();
variables = new ArrayList<String>();
necessaries = new HashMap<String, Boolean>();
options = new HashMap<String, String>();
optionsIdx = new HashMap<String, String>();
optionsLong = new HashMap<String, String>();
optionsLongIdx = new HashMap<String, String>();
descriptions = new HashMap<String, String>();
datatypes = new HashMap<String, DataType>();
defaults = new HashMap<String, Object>();
}
public void addOption(Boolean _need, String _variable, DataType _datatype, String _shortIndicator) throws Exception {
addOption(_need, _variable, _datatype, _shortIndicator, null, "", null);
}
public void addOption(Boolean _need, String _variable, DataType _datatype, String _shortIndicator, String _description) throws Exception {
addOption(_need, _variable, _datatype, _shortIndicator, null, _description, null);
}
public void addOption(Boolean _need, String _variable, DataType _datatype, String _shortIndicator, String _longIndicator, String _description) throws Exception {
addOption(_need, _variable, _datatype, _shortIndicator, _longIndicator, _description, null);
}
/**
* add a new option
* @param _need [Necessary] It represents this option is necessary or not. If true means necessary.
* @param _variable [Necessary] parameter variable name
* @param _datatype [Necessary] data type of the parameter to add
* @param _shortIndicator [Necessary] short indicator to set this parameter
* @param _longIndicator long indicator to set this parameter
* @param _description descriptions of the parameter to add
* @param _defaultValue default values of this parameter, if you don't give the value, this parameter is necessary parameter.
* @throws Exception, ParseException
*/
public void addOption(Boolean _need, String _variable, DataType _datatype, String _shortIndicator, String _longIndicator, String _description, Object _defaultValue) throws Exception
{
if (_variable == null)
throw new Exception("Variable name is necessary");
if (_need == null)
throw new Exception("Need variable is necessary");
if (_shortIndicator == null || _shortIndicator.isEmpty())
if (_longIndicator == null || _longIndicator.isEmpty())
throw new Exception("Short or long indicator is necessary");
if (_datatype == null)
throw new Exception("Data type is necessary.");
if (_defaultValue != null && _datatype != getDataType(_defaultValue)){
throw new Exception("Default value is different with data type.");
}
for(String key:variables){
if (key.compareTo(_variable) == 0) {
throw new Exception("Duplicate variable name: " + _variable);
}
}
if (_shortIndicator != null) {
for (String value : options.values()) {
if (value.compareTo(_shortIndicator) == 0) {
throw new Exception("Duplicate option name: " + _shortIndicator);
}
}
}
if (_longIndicator != null){
for(String value:optionsLong.values()){
if (value.compareTo(_longIndicator) == 0) {
throw new Exception("Duplicate option long name: " + _longIndicator);
}
}
}
variables.add(_variable);
Collections.sort(variables);
if (_need == true) necessaries.put(_variable, _need);
if (_shortIndicator != null) {
options.put(_variable, _shortIndicator);
optionsIdx.put(_shortIndicator, _variable);
}
if (_longIndicator != null) {
optionsLong.put(_variable, _longIndicator);
optionsLongIdx.put(_longIndicator, _variable);
}
if (_description == null || _description.isEmpty())
descriptions.put(_variable, "");
else
descriptions.put(_variable, _description);
datatypes.put(_variable, _datatype);
if (_defaultValue != null) {
defaults.put(_variable, _defaultValue);
}
// else{
// if (_datatype == DataType.BOOLEAN)
// defaults.put(_variable, false);
// }
}
/**
* Parsing parameters from Command-Line
* @param args
* @return
*/
public void parseArgs(String[] args) throws ParseException {
// checking each arg
for (int x=0; x<args.length; x++){
// check if the param is what we want to input
String param = findKey(args[x], x);
Object value;
// check the validation of the value
if (datatypes.get(param) != DataType.BOOLEAN) {
value = getValue(param, args[x+1], x+1);
x++;
}
else {
value = true;
}
params.put(param, value);
}
// check the variable's necessary
for (String key:necessaries.keySet()){
if (params.containsKey(key) == false)
{
throw new ParseException("Not found a necessary parameter \""+ options.get(key) + "\"", -1);
}
}
// check default value
for (String key:variables){
if (params.containsKey(key) == true) continue;
if (defaults.containsKey(key)) {
params.put(key, defaults.get(key));
}
}
}
private String findKey(String _input, int _position) throws ParseException {
String key = _input;
String param;
// check if the param is what we want to input
if (key.startsWith("--")) {
key = key.substring(2);
if (!optionsLongIdx.containsKey(key))
throw new ParseException("Not supported option: "+ _input + "Please check this option.", _position);
param = optionsLongIdx.get(key);
} else if (key.startsWith("-")) {
key = key.substring(1);
if (!optionsIdx.containsKey(key))
throw new ParseException("Not supported option: "+ _input + "Please check this option.", _position);
param = optionsIdx.get(key);
} else{
throw new ParseException("Not supported option: " + _input + "Please check this option.", _position);
}
return param;
}
/**
* check validation of the value
* @param _key
* @param _value
* @return
*/
private Object getValue(String _key, String _value, int _position) throws ParseException {
DataType expectedType = datatypes.get(_key);
if (expectedType == DataType.INTEGER){
try {
return Integer.parseInt(_value);
}
catch (NumberFormatException e){
throw new ParseException("Not proper value for " + optionsLong.get(_key) + ". This parameter should be Integer.", _position);
}
}
else if (expectedType == DataType.DOUBLE){
try {
return Double.parseDouble(_value);
}
catch (NumberFormatException e){
throw new ParseException("Not proper value for " + optionsLong.get(_key) + ". This parameter should be Double.", _position);
}
}
else if (expectedType == DataType.STRING){
return _value;
}
else if (expectedType == DataType.BOOLEAN){
return true;
}
return null;
}
public DataType getDataType(Object object) throws ParseException {
if (object instanceof Integer)
return DataType.INTEGER;
else if(object instanceof Double)
return DataType.DOUBLE;
else if(object instanceof String)
return DataType.STRING;
else if(object instanceof Boolean)
return DataType.BOOLEAN;
else
throw new ParseException("Data Type is not correct!", -1);
}
/**
* make HelpMsg
*/
public String getHelpMsg() {
String jarName = new java.io.File(Settings.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath())
.getName();
StringBuilder usages = new StringBuilder(String.format("Usage: java -jar %s [-options]\r\n\r\n", jarName) );
usages.append("where options can include:\r\n");
boolean shortFlag = false;
for (String param:variables){
shortFlag = false;
int length = 0;
if (options.containsKey(param)) {
usages.append("-");
usages.append(options.get(param));
shortFlag = true;
length += 2;
}
if (optionsLong.containsKey(param)) {
String longName = optionsLong.get(param);
usages.append((shortFlag) ? ", --" : "--");
usages.append(longName);
length += (longName.length() + ((shortFlag) ? 4 : 2));
}
if (length<4)
usages.append("\t\t\t");
else if (length<8)
usages.append("\t\t");
else
usages.append("\t");
if (descriptions.containsKey(param)){
String desc = getMultilineString(descriptions.get(param),screen-16, "\r\n\t\t\t");
usages.append(desc);
}
else{
usages.append("No description.");
}
usages.append("\r\n");
}
return usages.toString();
}
public String getMultilineString(String _text, int _size, String splitter){
StringBuilder sb = new StringBuilder();
while (true){
if (_text.length() > _size){
int idx = _text.lastIndexOf(' ', _size);
sb.append(_text.substring(0, idx));
sb.append(splitter);
_text = _text.substring(idx+1);
}
else{
sb.append(_text);
break;
}
}
return sb.toString();
}
public boolean containsParam(String key){
return params.containsKey(key);
}
public Object getParam(String key){
if (!params.containsKey(key))
return null;
return params.get(key);
}
public DataType getDataType(String key){
if (!params.containsKey(key))
return null;
return datatypes.get(key);
}
public int size(){
return params.size();
}
public Set<String> keySet(){
return params.keySet();
}
}
| 10,357 | 26.695187 | 182 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/generator/TaskSetSynthesizer.java | package lu.uni.svv.PriorityAssignment.generator;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.task.TaskType;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Time unit: millisecond
*/
public class TaskSetSynthesizer {
public static void main(String[] args)throws Exception{
// parsing args
TaskSetParams params = new TaskSetParams();
params.parse(args);
TaskSetSynthesizer synthesizer = new TaskSetSynthesizer((int)(params.SIMULATION_TIME/params.TIMEUNIT),
params.LIM_SIM,
params.GRANULARITY,
params.MIN_ARRIVAL_RANGE,
params.PRIORITY);
String targetPath = String.format("%s/%s",params.BASE_PATH, params.controlValue);
synthesizer.run(targetPath, params.N_TASKSET,
params.TIMEUNIT, params.TARGET_UTILIZATION, params.DELTA_UTILIZATION,
params.N_TASK, params.RATIO_APERIODIC, params.MAX_ARRIVAL_RANGE);
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
private long MAX_SIM_TIME = 0;
private int GRANULARITY = 0;
private boolean LIM_SIM = true;
private String PRIORITY = "RM";
private double MINIMUM_RANGE = 1.0;
private Random rand;
private int nDiscarded = 0;
public TaskSetSynthesizer(long _maxSimTime, boolean _limitSim, int _granularity){
this(_maxSimTime, _limitSim, _granularity, 1,"RM");
}
public TaskSetSynthesizer(long _maxSimTime, boolean _limitSim, int _granularity, double _minRangeAperiodic){
this(_maxSimTime, _limitSim, _granularity, _minRangeAperiodic,"RM");
}
public TaskSetSynthesizer(long _maxSimTime, boolean _limitSim, int _granularity, double _minRangeAperiodic, String _priority){
rand = new Random();
this.MAX_SIM_TIME = _maxSimTime;
this.LIM_SIM = _limitSim;
this.GRANULARITY = _granularity;
this.PRIORITY = _priority;
this.MINIMUM_RANGE = _minRangeAperiodic;
}
public void run(String targetPath, int nTaskset,
double TIMEUNIT, double targetU, double delta,
int nTask, double ratioAperiodic, int maxArrivalRange) {
// Generate result path
File path = new File(targetPath);
if (!path.exists()) path.mkdirs();
for (int x=0; x<nTaskset; x++) {
long ts = System.currentTimeMillis();
nDiscarded = 0;
OPAMTaskSet taskset = generateMultiTaskset(nTask, targetU, delta,
(int)(10/TIMEUNIT), (int)(1000/TIMEUNIT), (int)(GRANULARITY/TIMEUNIT), true,
ratioAperiodic, maxArrivalRange);
ts = System.currentTimeMillis() - ts;
// Print results
double LCM = taskset.calculateLCM(false); //taskset.calculateLCM(); // LCM of all
double maxIA = taskset.getMaxInterArrivalTime();
double sTime = Math.max(LCM, maxIA)*TIMEUNIT;
System.out.print(String.format("Time: %.3fs, Discarded: %8d, LCMp: %25.2fms || ", ts / 1000.0, nDiscarded, sTime));
System.out.println(taskset.toString());
String filename = String.format("%s/taskset_%03d.csv", path.getAbsolutePath(), x);
taskset.print(filename, TIMEUNIT);
} // for number of tast set
}
/**
* Generate a set of tasks including aperiodic and periodic tasks
* @param nTask number of tasks
* @param targetU target total utilization
* @param delta acceptable actual total utilization delta
* @param minPeriod minimum task period
* @param maxPeriod maximum task period
* @param granularity a granularity of task period (task period would be multiples of granularity)
* @param allowDuplicate allow duplicated task period to a set of periodic tasks
* @param ratioAperiodic the ratio of aperiodic tasks in the set of tasks
* @param maxArrivalRange the maximum range of inter-arrival time for aperiodic tasks
* @return
*/
public OPAMTaskSet generateMultiTaskset(int nTask, double targetU, double delta,
int minPeriod, int maxPeriod, int granularity, boolean allowDuplicate,
double ratioAperiodic, int maxArrivalRange) {
OPAMTaskSet taskset = null;
while (taskset == null) {
taskset = generatePeriodicTaskSet(nTask, targetU, minPeriod, maxPeriod, granularity, allowDuplicate);
if(!taskset.isValidWCET() || !taskset.isValidUtilization(targetU, delta)) {
nDiscarded++;
taskset = null;
continue;
}
taskset = selectAperiodicTasks(taskset, ratioAperiodic, maxArrivalRange, 0, 0, granularity);
if (LIM_SIM && !taskset.isValidSimulationTime((int)(MAX_SIM_TIME))){
nDiscarded++;
taskset=null;
continue;
}
if (this.PRIORITY.compareTo("RM")==0) {
taskset = assignPriority(taskset);
}
else{
taskset = assignPriorityEngineer(taskset);
}
}
return taskset;
}
/**
* Generate a set of periodic tasks
* @param nTask number of tasks
* @param targetU target total utilization
* @param minPeriod minimum task period
* @param maxPeriod maximum task period
* @param granularity a granularity of task period (task period would be multiples of granularity)
* @param allowDuplicate allow duplicated task period to a set of periodic tasks
* @return a set of periodic tasks
*/
public OPAMTaskSet generatePeriodicTaskSet(int nTask, double targetU, int minPeriod, int maxPeriod, int granularity, boolean allowDuplicate){
List<TaskDescriptor> tasks = new ArrayList<TaskDescriptor>();
double[] utilizations = UUniFastDiscard(nTask, targetU);
int[] periods = generatePeriods(nTask, minPeriod, maxPeriod, granularity,allowDuplicate);
int[] WCETs = generateWCETs(periods, utilizations);
TaskDescriptor.UNIQUE_ID = 1;
for (int t=0; t<nTask; t++){
TaskDescriptor task = new TaskDescriptor();
task.Name = String.format("t%02d", t+1);
task.Type = TaskType.Periodic;
task.WCET = WCETs[t];
task.MaxWCET = WCETs[t];
task.Period = periods[t];
task.Deadline = periods[t];
task.Priority = 0;
tasks.add(task);
}
return new OPAMTaskSet(tasks);
}
/**
* Select some tasks among a set of periodic tasks as the ratio _ratioAperiodic and change them to aperiodic tasks
* @param _taskset
* @param _ratioAperiodic
* @param maxArrivalRange
* @param selectRangeMin
* @param selectRangeMax
* @param _granularity
* @return
*/
public OPAMTaskSet selectAperiodicTasks(OPAMTaskSet _taskset, double _ratioAperiodic, int maxArrivalRange, int selectRangeMin, int selectRangeMax, int _granularity) {
int nTasks = _taskset.tasks.length;
int nAperiodicTasks = (int)Math.round(nTasks *_ratioAperiodic);
int cnt = 0;
while(cnt<nAperiodicTasks){
// select a task at random
int ID = (int)Math.floor(rand.nextDouble()*(nTasks)); // at random in range [0, nTasks)
if (_taskset.tasks[ID].Type!=TaskType.Periodic) continue;
// change a task to aperiodic task
int min = (int)(_taskset.tasks[ID].Period * MINIMUM_RANGE) + _granularity;
int max = _taskset.tasks[ID].Period * maxArrivalRange + _granularity;
double randVal = rand.nextDouble()*(max-min) + min;
_taskset.tasks[ID].MinIA = _taskset.tasks[ID].Period;
_taskset.tasks[ID].MaxIA = (int)(Math.floor(randVal/_granularity) * _granularity);
_taskset.tasks[ID].Type = TaskType.Aperiodic;
cnt++;
}
return _taskset;
}
/**
* Assign priority to the task set according to rate-monotonic scheduling
* The lower priority the task has, the higher priority it has
* @param _taskset
* @return
*/
public OPAMTaskSet assignPriority(OPAMTaskSet _taskset) {
for(int p=0; p<_taskset.tasks.length; p++){
int period = _taskset.tasks[p].Period;
int priority = 0;
for(int t=0; t<_taskset.tasks.length; t++){
if (p==t) continue;
int cPeriod = _taskset.tasks[t].Period;
if (cPeriod<period) priority++;
if (cPeriod==period && p>t) priority++;
}
_taskset.tasks[p].Priority = _taskset.tasks.length - priority -1;
}
return _taskset;
}
/**
* Assign priority to the task set according to engineer's desire
* Basically it follows rate-monotonic only for Periodic tasks
* For aperiodic tasks, this function makes their priorities lower.
* @param _taskset
* @return
*/
public OPAMTaskSet assignPriorityEngineer(OPAMTaskSet _taskset) {
// assign priorities to the non aperiodic tasks
int cntPeriod = 0;
for(int p=0; p<_taskset.tasks.length; p++) {
if (_taskset.tasks[p].Type == TaskType.Aperiodic) continue;
int period = _taskset.tasks[p].Period;
int priority = 0;
for (int t = 0; t < _taskset.tasks.length; t++) {
if (p==t) continue;
if (_taskset.tasks[t].Type == TaskType.Aperiodic) continue;
int cPeriod = _taskset.tasks[t].Period;
if (cPeriod<period) priority++;
if (cPeriod==period && p>t) priority++;
}
_taskset.tasks[p].Priority = _taskset.tasks.length - priority -1;
cntPeriod++;
}
// assign priorities to the aperiodic tasks
for(int p=0; p<_taskset.tasks.length; p++){
if (_taskset.tasks[p].Type != TaskType.Aperiodic) continue;
int period = _taskset.tasks[p].Period;
int priority = cntPeriod;
for(int t=0; t<_taskset.tasks.length; t++){
if (p==t) continue;
if (_taskset.tasks[t].Type != TaskType.Aperiodic) continue;
int cPeriod = _taskset.tasks[t].Period;
if (cPeriod<period) priority++;
if (cPeriod==period && p>t) priority++;
}
_taskset.tasks[p].Priority = _taskset.tasks.length - priority -1;
}
return _taskset;
}
//////////////////////////////////////////////////////////////////
// Basic task generation functions
//////////////////////////////////////////////////////////////////
/**
* UUniFast algorithm to generate utilizations (It allows to generate total utilization < 1)
* E. Bini and G. C. Buttazzo,
* “Measuring the performance of schedulability tests,”
* Real-Time Systems, vol. 30, no. 1–2, pp. 129–154, 2005.
* @param nTasks
* @param utilization
* @return
*/
public double[] UUniFast(int nTasks, double utilization){
double sumU = utilization;
double nextSumU = 0;
double[] vecU = new double[nTasks];
for (int x = 1; x < nTasks; x++) {
nextSumU = sumU * Math.pow(rand.nextDouble(), 1.0 / (nTasks - x));
vecU[x-1] = sumU - nextSumU;
sumU = nextSumU;
}
vecU[nTasks-1] = sumU;
return vecU;
}
/**
* Revised UUniFast algorithm to the multi-processor
* When a utilization of a task is over 1.0, the set of utilization is discarded and re-generates them again
* R. I. Davis and A. Burns,
* “Improved priority assignment for global fixed priority pre-emptive scheduling in multiprocessor
* real-time systems,” Real-Time Systems, vol. 47, no. 1, pp. 1–40, 2011.
* @param nTasks
* @param utilization
* @return
*/
public double[] UUniFastDiscard(int nTasks, double utilization){
double[] vecU = null;
while(vecU==null){
vecU = UUniFast(nTasks, utilization);
boolean flag = true;
for (int x=0; x<vecU.length; x++){
if(vecU[x] >= 1.0) {flag=false; break;}
}
if(!flag) vecU = null;
}
return vecU;
}
/**
* generate Periods by log-uniform
* according to paper below
* P. Emberson, R. Stafford, and R. I. Davis,
* “Techniques for the synthesis of multiprocessor tasksets,”
* Proceedings of the 1st International Workshop on Analysis Tools and Methodologies for Embedded and Real-time Systems (WATERS),
* vol. 1, no. Waters, pp. 6–11, 2010.
* @param nTasks
* @param tMin: the order of magnitude
* @param tMax: the order of magnitude
* @return
*/
public int[] generatePeriods(int nTasks, int tMin, int tMax, int granularity, boolean allowDuplicate){
//generate periods
double min = Math.log(tMin);
double max = Math.log(tMax + granularity); //Math.log(tMax);
int[] periods = new int[nTasks];
int x = 0;
while(x<nTasks){
// log distribution in range [log(min), log(max)) <- log(max) exclusive
double randVal = rand.nextDouble() * (max-min) + min; // generate random value in [log(tMin), log(tMax+granularity))
int val = (int)Math.floor(Math.exp(randVal) / granularity) * granularity;
// Check periods contains the value;
if (!allowDuplicate && checkDuplicate(periods, x, val)) continue;
periods[x] = val;
x++;
}
return periods;
}
public boolean checkDuplicate(int[] periods, int x, int val){
boolean flag = false;
for (int t = 0; t < x; t++) {
if (periods[t] == val) flag = true;
}
return flag;
}
/**
* Generate periods among divisors between tMin and tMax according to log-uniform
* @param nTasks
* @param tMin
* @param tMax
* @param granularity
* @param allowDuplicate currently always allow duplicate periods
* @return
*/
public int[] generatePeriodsDivisors(int nTasks, int tMin, int tMax, int granularity, boolean allowDuplicate){
int[] divisors = this.generateDivisors(MAX_SIM_TIME, tMin, tMax);
//generate periods
int[] periods = new int[nTasks];
int x = 0;
while(x<nTasks){
// get random value of log-uniform in range of indexes of divisors
double min = Math.log(1);
double max = Math.log(divisors.length + 1); //Math.log(tMax);
// log distribution in range [log(min), log(max)) <- log(max) exclusive
double randVal = rand.nextDouble() * (max - min) + min; // generate random value in [log(tMin), log(tMax+granularity))
int val = (int) Math.floor(Math.exp(randVal));
periods[x] = divisors[val-1];
x++;
}
return periods;
}
/**
* generate Periods by CDF based log-uniform
* Select only divisors of the MAX_SIM_TIME in range [tMin, tMax]
* the probability of maximum divisor is CDF from tMax to tMax + granularity
* @param nTasks
* @param tMin
* @param tMax
* @param granularity
* @param allowDuplicate
* @return
*/
public int[] generatePeriodsDivisorsCDF(int nTasks, int tMin, int tMax, int granularity, boolean allowDuplicate){
int[] divisors = generateDivisors(MAX_SIM_TIME, tMin, tMax);
double[] CDFs = this.generateCDFDivisors(divisors, tMin, tMax+granularity);
//generate periods
int[] periods = new int[nTasks];
int x = 0;
while(x<nTasks){
double r = rand.nextDouble();
int idx=0;
for(int c=0; c<CDFs.length; c++){
if ( CDFs[c] <= r) idx = c;
}
periods[x] = divisors[idx];
x++;
}
return periods;
}
public double[] generateCDFDivisors(int[] divisors, int tMin, int tMax){
double[] CDFs = new double[divisors.length];
for (int x=0; x<divisors.length; x++){
CDFs[x] = this.cdf(divisors[x], 1, tMax);
}
return CDFs;
}
/**
* get CDF value of x from CDF of log-uniform function
* @param x the value what you want to know its CDF from a
* @param a the minimum range of CDF of log-uniform
* @param b the maximum range of CDF of log-uniform
* @return
*/
public double cdf(int x, int a, int b){
double value = x/(double)a;
double base = b/(double)a;
return Math.log(value)/Math.log(base);
}
/**
* generate WCET values
* Note that when applying equation C=T*U,
* the worst-case execution time is usually rounded to the nearest integer
* which will affect the distribution of actual utilisations in the generated taskset.
* Changing the unit of time to use larger numeric values will decrease this loss of accuracy.
* @param periods time periods for each task with regard to a time unit
* @param utilizations utilizations for each task (the length should be the same with periods
* @return
*/
public int[] generateWCETs(int[] periods, double[] utilizations){
int[] wcets = new int[periods.length];
for (int x = 0; x < periods.length; x++) {
wcets[x] =(int) Math.round(periods[x] * utilizations[x]);
}
return wcets;
}
/**
* generate WCET values
* Note that when applying equation C=T*U,
* the worst-case execution time is usually rounded to the nearest integer
* which will affect the distribution of actual utilisations in the generated taskset.
* Changing the unit of time to use larger numeric values will decrease this loss of accuracy.
* @param periods time periods for each task with regard to a time unit
* @param utilizations utilizations for each task (the length should be the same with periods
* @return
*/
public double[] generateWCETsDouble(int[] periods, double[] utilizations){
double[] wcets = new double[periods.length];
for (int x = 0; x < periods.length; x++) {
double WCET = Math.round(periods[x] * utilizations[x]);
wcets[x]= WCET;
}
return wcets;
}
/**
* generate divisors of given value within given range
* @param num the number you want to get divisors
* @param min the min value of the given range
* @param max the max value of the given range
* @return
*/
public int[] generateDivisors(long num, int min, int max) {
List<Integer> divisors = new ArrayList<>();
for(int i = min; i<=max; i++){
if(num % i ==0){
divisors.add(i);
}
}
int[] values = new int[divisors.size()];
for (int x=0; x<divisors.size(); x++){
values[x] = divisors.get(x);
}
return values;
}
//////////////////////////////////////////////////////////////////
// Utilities
//////////////////////////////////////////////////////////////////
public String ListtoString(int[] list, String header){
StringBuilder sb = new StringBuilder();
sb.append(header);
sb.append(": [");
for(int i=0; i<list.length; i++){
sb.append(list[i]);
sb.append(", ");
}
sb.append("]");
return sb.toString();
}
public String ListtoString(double[] list, String header){
StringBuilder sb = new StringBuilder();
sb.append(header);
sb.append(": [");
for(int i=0; i<list.length; i++){
sb.append(String.format("%.4f, ", list[i]));
}
sb.append("]");
return sb.toString();
}
public double getUtilization(double[] Us) {
double util = 0;
for (double Ui : Us) {
util += Ui;
}
return util;
}
public double getUtilization(int[] periods, int[] wcets) {
double util = 0;
for (int x=0; x<periods.length; x++) {
util += (double)wcets[x]/periods[x];
}
return util;
}
public double getUtilization(int[] periods, double[] wcets) {
double util = 0;
for (int x=0; x<periods.length; x++) {
util += wcets[x]/periods[x];
}
return util;
}
//////////////////////////////////////////////////////////////////
// calculate lcm
//////////////////////////////////////////////////////////////////
/**
* Greatest Common Divisor for two int values
* @param _result
* @param _periodArray
* @return
*/
public static long gcd(long _result, long _periodArray) {
while (_periodArray > 0) {
long temp = _periodArray;
_periodArray = _result % _periodArray; // % is remainder
_result = temp;
}
return _result;
}
/**
* Least Common Multiple for two int numbers
* @param _result
* @param _periodArray
* @return
*/
public static long lcm(long _result, long _periodArray) {
return _result * (_periodArray / gcd(_result, _periodArray));
}
/**
* Least Common Multiple for int arrays
*
* @param _periodArray
* @return
*/
public static long lcm(Long[] _periodArray) {
long result = _periodArray[0];
for (int i = 1; i < _periodArray.length; i++) result = lcm(result, _periodArray[i]);
return result;
}
}
| 19,413 | 32.357388 | 167 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/generator/OPAMTaskSet.java | package lu.uni.svv.PriorityAssignment.generator;
import lu.uni.svv.PriorityAssignment.task.TaskDescriptor;
import lu.uni.svv.PriorityAssignment.task.TaskSeverity;
import lu.uni.svv.PriorityAssignment.task.TaskType;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class OPAMTaskSet {
TaskDescriptor[] tasks;
public OPAMTaskSet(){
}
public OPAMTaskSet(OPAMTaskSet taskset){
super();
tasks = new TaskDescriptor[taskset.tasks.length];
for (int t=0; t<taskset.tasks.length; t++)
this.tasks[t] = taskset.tasks[t].copy();
}
public OPAMTaskSet(TaskDescriptor[] tasks){
super();
this.tasks = tasks;
}
public OPAMTaskSet(List<TaskDescriptor> tasks){
super();
this.tasks = new TaskDescriptor[tasks.size()];
for (int t=0; t<tasks.size(); t++)
this.tasks[t] = tasks.get(t).copy();
}
public OPAMTaskSet copy(){
return new OPAMTaskSet(this);
}
//////////////////////////////////////////////////////////////////
// Print out the results
//////////////////////////////////////////////////////////////////
/**
*
* @param _filename
* @param _timeQuanta
*/
public void print(String _filename, double _timeQuanta){
PrintStream ps;
if (_filename==null)
ps = System.out;
else{
try {
ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(_filename, false)), true);
}
catch (FileNotFoundException e){
System.out.println("Cannot find the file: "+ _filename);
ps = System.out;
}
}
String text = TaskDescriptor.toString(tasks, _timeQuanta);
ps.println(text);
}
//////////////////////////////////////////////////////////////////
// get information
//////////////////////////////////////////////////////////////////
public TaskDescriptor[] getTasks() {
return tasks;
}
public int getNTasks(TaskType type){
if (type == null) return tasks.length;
int cnt = 0;
for(int t=0; t<this.tasks.length; t++){
if (tasks[t].Type == type) cnt ++;
}
return cnt;
}
public double getUtilization() {
double util = 0;
for(TaskDescriptor task : tasks){
int period = (task.Type==TaskType.Periodic)?task.Period:task.MinIA;
util += 1.0 * task.WCET / period;
}
return util;
}
public double getUtilizationLow() {
double util = 0;
for(TaskDescriptor task : tasks){
int period = (task.Type==TaskType.Periodic)?task.Period:task.MaxIA;
util += 1.0 * task.WCET / period;
}
return util;
}
public boolean isValidWCET(){
for(TaskDescriptor task : tasks){
if(task.WCET==0) return false;
}
return true;
}
public boolean isValidUtilization(double target, double delta){
double actual = getUtilization();
if (actual < target-delta || actual > target + delta) return false;
return true;
}
public boolean isValidSimulationTime(int maxSimulationTime){
double lcm = this.calculateLCM(false);
// the reason why filtering - value of lcm is that LCM is over the maximum integer value
if (lcm<0) return false;
long maxIA = this.getMaxInterArrivalTime();
double simTime = Math.max(lcm, maxIA);
if (simTime>maxSimulationTime || lcm<0) return false;
return true;
}
//////////////////////////////////////////////////////////////////
// String Utilities
//////////////////////////////////////////////////////////////////
@Override
public String toString(){
String txt = String.format("NumTasks: %d [P:%d, S:%d, A:%d], Utilization: [%.3f, %.3f], Period: [%s], WCETs: [%s]",
this.tasks.length, getNTasks(TaskType.Periodic), getNTasks(TaskType.Sporadic), getNTasks(TaskType.Aperiodic),
getUtilization(), getUtilizationLow(), periodsToString(1), wcetsToString(1)
);
return txt;
}
public String getString(double timeUnit){
String txt = String.format("NumTasks: %d [P:%d, S:%d, A:%d], Utilization: [%.3f, %.3f], Period: [%s], WCETs: [%s]",
this.tasks.length, getNTasks(TaskType.Periodic), getNTasks(TaskType.Sporadic), getNTasks(TaskType.Aperiodic),
getUtilization(), getUtilizationLow(), periodsToString(timeUnit), wcetsToString(timeUnit)
);
return txt;
}
public String periodsToString(double timeUnit){
int precision = this.getUnitPrecision(timeUnit);
String pf = String.format("%%.%df, ", precision);
StringBuilder sb = new StringBuilder();
for (int x=0; x<tasks.length; x++){
sb.append(String.format(pf, tasks[x].Period*timeUnit));
}
return sb.toString();
}
public int getUnitPrecision(double timeUnit){
int unit = 0;
double t=1.0;
while(timeUnit<t){
unit += 1;
t= t/10;
}
return unit;
}
public String wcetsToString(double timeUnit){
int precision = this.getUnitPrecision(timeUnit);
String pf = String.format("%%.%df, ", precision);
StringBuilder sb = new StringBuilder();
for (int x=0; x<tasks.length; x++){
sb.append(String.format(pf, tasks[x].WCET*timeUnit));
}
return sb.toString();
}
public String ListToString(int[] list, String header){
StringBuilder sb = new StringBuilder();
sb.append(header);
sb.append(": [");
for(int i=0; i<list.length; i++){
sb.append(list[i]);
sb.append(", ");
}
sb.append("]");
return sb.toString();
}
public String ListToString(double[] list, String header){
StringBuilder sb = new StringBuilder();
sb.append(header);
sb.append(": [");
for(int i=0; i<list.length; i++){
sb.append(String.format("%.4f, ", list[i]));
}
sb.append("]");
return sb.toString();
}
//////////////////////////////////////////////////////////////////
// calculate lcm
//////////////////////////////////////////////////////////////////
public long getMaxInterArrivalTime() {
int max=0;
for (TaskDescriptor task: tasks) {
if (task.Type != TaskType.Aperiodic) continue;
max = Math.max(max, task.MaxIA);
}
return max;
}
public long calculateLCM() {
return calculateLCM(true, false);
}
public long calculateLCM(boolean includeAperiodic) {
return calculateLCM(includeAperiodic, false);
}
public long calculateLCM(boolean includeAperiodic, boolean withMaximum) {
long[] periods = new long[tasks.length];
int x=0;
for (TaskDescriptor task: tasks) {
if (!includeAperiodic) {
if (task.Type == TaskType.Aperiodic) continue;
}
long period = (task.Type==TaskType.Periodic)?task.Period:(!withMaximum?task.MinIA:task.MaxIA);
periods[x++] = period;
}
// convert to array and get LCM
return lcm(periods, x);
}
/**
* Greatest Common Divisor for two int values
* @param _result
* @param _periodArray
* @return
*/
private long gcd(long _result, long _periodArray) {
while (_periodArray > 0) {
long temp = _periodArray;
_periodArray = _result % _periodArray; // % is remainder
_result = temp;
}
return _result;
}
/**
* Least Common Multiple for int arrays
*
* @param _periodArray
* @param _length
* @return
*/
private long lcm(long[] _periodArray, long _length) {
long result = _periodArray[0];
for (int i = 1; i < _length; i++) {
result = result * (_periodArray[i] / gcd(result, _periodArray[i]));
if (result <0) return -1;
}
return result;
}
}
| 7,228 | 25.479853 | 117 | java |
null | OPAM-main/PriorityAssignment/src/main/java/lu/uni/svv/PriorityAssignment/generator/TaskSetParams.java | package lu.uni.svv.PriorityAssignment.generator;
import lu.uni.svv.PriorityAssignment.utils.ArgumentParser;
public class TaskSetParams {
public long SIMULATION_TIME=0;
public double TIMEUNIT;
public double TARGET_UTILIZATION;
public double DELTA_UTILIZATION;
public int N_TASKSET;
public int N_TASK;
public int MAX_ARRIVAL_RANGE;
public double RATIO_APERIODIC;
public String BASE_PATH;
public String PRIORITY;
public boolean LIM_SIM;
public int GRANULARITY;
public String controlValue;
public double MIN_ARRIVAL_RANGE;
public void parse(String[] args) throws Exception{
// parsing args
ArgumentParser parser = parseArgs(args);
// set params
this.SIMULATION_TIME = (int)parser.getParam("SIMULATION_TIME");
this.TIMEUNIT = (double)parser.getParam("TIMEUNIT");
this.TARGET_UTILIZATION = (double)parser.getParam("TARGET_UTILIZATION");
this.DELTA_UTILIZATION = (double)parser.getParam("DELTA_UTILIZATION");
this.N_TASKSET = (int)parser.getParam("N_TASKSET");
this.N_TASK = (int)parser.getParam("N_TASK");
this.MAX_ARRIVAL_RANGE = (int)parser.getParam("MAX_ARRIVAL_RANGE");
this.RATIO_APERIODIC = (double)parser.getParam("RATIO_APERIODIC");
this.BASE_PATH = (String)parser.getParam("BASE_PATH");
this.PRIORITY = (String)parser.getParam("PRIORITY");
this.LIM_SIM = (boolean)parser.getParam("LIM_SIM");
this.GRANULARITY = (int)parser.getParam("GRANULARITY");
this.controlValue = (String)parser.getParam("CONTROL_VALUE");
this.MIN_ARRIVAL_RANGE = (double)parser.getParam("MIN_ARRIVAL_RANGE");
if(!this.LIM_SIM) this.SIMULATION_TIME = 0;
}
private ArgumentParser parseArgs(String[] args) throws Exception {
// Setting arguments
ArgumentParser parser = new ArgumentParser();
parser.addOption(false,"Help", ArgumentParser.DataType.BOOLEAN, "h", "help", "Show how to use this program", false);
parser.addOption(false,"SIMULATION_TIME", ArgumentParser.DataType.INTEGER, "s", null, "", 10000);
parser.addOption(false,"TIMEUNIT", ArgumentParser.DataType.DOUBLE, "t", null, "", 0.1);
parser.addOption(false,"TARGET_UTILIZATION", ArgumentParser.DataType.DOUBLE, "u", null, "", 0.7);
parser.addOption(false,"N_TASKSET", ArgumentParser.DataType.INTEGER, "n", null, "", 10);
parser.addOption(false,"DELTA_UTILIZATION", ArgumentParser.DataType.DOUBLE, "d", null, "", 0.01);
parser.addOption(false,"MAX_ARRIVAL_RANGE", ArgumentParser.DataType.INTEGER, "a", null, "", 2);
parser.addOption(false,"RATIO_APERIODIC", ArgumentParser.DataType.DOUBLE, "r", null, "", 0.4); // average industrial subjects (rounded to -1 digits, 0.37 to 0.4)
parser.addOption(false,"N_TASK", ArgumentParser.DataType.INTEGER, "m", null, "", 20); // average industrial subjects (rounded to 2 digits, 18.3 to 20)
parser.addOption(false,"BASE_PATH", ArgumentParser.DataType.STRING,"b", null, "", null);
parser.addOption(false,"GRANULARITY", ArgumentParser.DataType.INTEGER,null, "granularity", "", 10);
parser.addOption(false,"PRIORITY", ArgumentParser.DataType.STRING,null, "priority", "default rate monotonic", "RM");
parser.addOption(false,"CONTROL_VALUE", ArgumentParser.DataType.STRING,"c", null, "", null);
parser.addOption(false,"MIN_ARRIVAL_RANGE", ArgumentParser.DataType.DOUBLE,null, "minArrival", "", 1.0);
// Task set
parser.addOption(false,"LIM_SIM", ArgumentParser.DataType.BOOLEAN,"l", null, "", false);
// parsing args
try{
parser.parseArgs(args);
}
catch(Exception e) {
System.out.println("Error: " + e.getMessage());
System.out.println("");
System.out.println(parser.getHelpMsg());
System.exit(0);
}
if((Boolean)parser.getParam("Help")){
System.out.println(parser.getHelpMsg());
System.exit(1);
}
return parser;
}
}
| 3,742 | 43.559524 | 164 | java |
null | tacolens-main/web-server/src/test/dataspread/AppTest.java | package dataspread;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Unit test for simple App.
*/
public class AppTest
{
/**
* Rigorous Test :-)
*/
@Test
public void shouldAnswerWithTrue()
{
assertTrue( true );
}
}
| 282 | 12.47619 | 42 | java |
null | tacolens-main/web-server/src/main/dataspread/App.java | package dataspread;
import static spark.Spark.*;
import spark.Filter;
import dataspread.formulas.FormulasController;
import dataspread.taco.TacoController;
import dataspread.utils.Controller;
/**
* Entry point for the formula detection API.
*/
public class App {
// Add more controllers here!
public static Controller[] controllers = {
new FormulasController(),
new TacoController(),
};
public static void main(String[] args) {
port(4567);
after((Filter) (request, response) -> {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Methods", "*");
response.header("Access-Control-Allow-Headers", "*");
response.header("Content-Encoding", "gzip");
});
path("/api", () -> {
for (Controller c : App.controllers) {
path(c.getPrefix(), c.getRoutes());
}
});
}
}
| 893 | 21.35 | 59 | java |
null | tacolens-main/web-server/src/main/dataspread/formulas/FormulasController.java | package dataspread.formulas;
import static spark.Spark.*;
import dataspread.utils.Controller;
import dataspread.utils.Utils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonArray;
import com.google.gson.Gson;
import spark.RouteGroup;
import java.util.Map;
public class FormulasController implements Controller {
@Override
public String getPrefix() {
return "/formulas";
}
@Override
public RouteGroup getRoutes() {
return () -> {
post("/hash", (req, res) -> {
JsonObject body = new Gson().fromJson(req.body(), JsonObject.class);
JsonElement formulae = body.get("formulae");
if (formulae != null) {
JsonArray mtx = formulae.getAsJsonArray();
String[][] fMtx = Utils.jsonMtxToStringMtx(mtx);
String[][] hMtx = FormulasService.hashFormulae(fMtx);
return new Gson().toJson(Map.of("data", hMtx));
} else {
return new Gson().toJson(Map.of("data", new String[0]));
}
});
};
}
}
| 1,055 | 24.756098 | 76 | java |
null | tacolens-main/web-server/src/main/dataspread/formulas/FormulasService.java | package dataspread.formulas;
import dataspread.utils.ApiFormulaParser;
import org.apache.poi.ss.formula.ptg.ScalarConstantPtg;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.poi.ss.formula.ptg.OperationPtg;
import org.apache.poi.ss.formula.ptg.OperandPtg;
import org.apache.poi.ss.formula.ptg.Ptg;
import java.io.IOException;
import java.util.Arrays;
public class FormulasService {
private static String hashFormula(Ptg[] ptgs) {
StringBuilder cleanedFormula = new StringBuilder();
for (Ptg ptg : ptgs) {
if (ptg instanceof OperationPtg) {
// Include mathematical operators in the cleaned formula
OperationPtg tok = (OperationPtg) ptg;
String[] operands = new String[tok.getNumberOfOperands()];
Arrays.fill(operands, "");
cleanedFormula.append(tok.toFormulaString(operands));
} else if (ptg instanceof ScalarConstantPtg || ptg instanceof OperandPtg) {
// Only exclude constants and cells from the cleaned formula
continue;
} else {
// Include ArrayPtg, UnknownPtg, and ControlPtg in the cleaned formula
cleanedFormula.append(ptg.toFormulaString());
}
}
return DigestUtils.md5Hex(cleanedFormula.toString()).toUpperCase();
}
public static String[][] hashFormulae(String[][] formulaMtx) throws IOException {
String[][] hashes = new String[formulaMtx.length][formulaMtx[0].length];
ApiFormulaParser.parseFormulae(formulaMtx, (ptgs, i, j) -> {
if (ptgs != null) {
hashes[i][j] = FormulasService.hashFormula(ptgs);
} else {
hashes[i][j] = null;
}
});
return hashes;
}
}
| 1,663 | 33.666667 | 83 | java |
null | tacolens-main/web-server/src/main/dataspread/utils/ApiFormulaParser.java | package dataspread.utils;
import org.apache.poi.ss.formula.FormulaParsingWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.formula.FormulaParser;
import org.apache.poi.ss.formula.FormulaType;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import java.io.IOException;
public class ApiFormulaParser {
/**
* Parses an excel formula into ptg tokens.
*
* @param workbook
* @param cell
* @param formula
* @return The parsed formula.
*/
private static Ptg[] parseFormula(FormulaParsingWorkbook workbook, Cell cell, String formula) {
try {
if (formula.startsWith("=")) {
cell.setCellFormula(formula.substring(1));
return FormulaParser.parse(
cell.getCellFormula()
, workbook
, FormulaType.CELL
, cell.getSheet().getWorkbook().getSheetIndex(cell.getSheet())
, cell.getRowIndex()
);
} else {
return null;
}
} catch (Exception err) {
err.printStackTrace();
return null;
}
}
/**
* Given a matrix of Excel spreadsheet formula, iterate over the
* range row by row and perform a callback operation on each tokenized
* formula.
*
* @param formulae
* @param callback
* @throws IOException
*/
public static void parseFormulae(String[][] formulae, TriConsumer<Ptg[], Integer, Integer> callback) throws IOException {
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
Row row = workbook.createSheet().createRow(0);
for (int i = 0; i < formulae.length; i++) {
for (int j = 0; j < formulae[i].length; j++) {
Ptg[] parsed = ApiFormulaParser.parseFormula(
workbook.createEvaluationWorkbook(),
row.createCell(0),
formulae[i][j]
);
callback.accept(parsed, i, j);
}
}
}
}
}
| 1,961 | 27.852941 | 123 | java |
null | tacolens-main/web-server/src/main/dataspread/utils/TriConsumer.java | package dataspread.utils;
import java.util.Objects;
@FunctionalInterface
public interface TriConsumer<T, U, V> {
/**
* Performs this operation on the given arguments.
*
* @param t the first input argument
* @param u the second input argument
* @param u the third input argument
*/
void accept(T t, U u, V v);
/**
* Returns a composed {@code TriConsumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code TriConsumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default TriConsumer<T, U, V> andThen(TriConsumer<? super T, ? super U, ? super V> after) {
Objects.requireNonNull(after);
return (x, y, z) -> {
accept(x, y, z);
after.accept(x, y, z);
};
}
}
| 1,250 | 31.921053 | 94 | java |
null | tacolens-main/web-server/src/main/dataspread/utils/Utils.java | package dataspread.utils;
import org.apache.poi.ss.formula.ptg.AreaPtgBase;
import org.apache.poi.ss.formula.ptg.RefPtgBase;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.formula.ptg.Ptg;
import com.google.gson.JsonArray;
public class Utils {
/**
* Converts a JsonArray matrix into a string matrix.
*
* @param mtx
* @return The string matrix representation of the input
* json matrix.
*/
public static String[][] jsonMtxToStringMtx(JsonArray mtx) {
int rows = mtx.size();
int cols = mtx.get(0).getAsJsonArray().size();
String[][] strs = new String[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
strs[i][j] = mtx
.get(i).getAsJsonArray()
.get(j).getAsString();
}
}
return strs;
}
/**
* If there is exactly one cell range in the parsed formula tokens,
* returns it. Otherwise returns null.
*
* @param tokens
* @return null if there are multiple ranges found in the formula
* tokens. Otherwise return the only cell range in the formula tokens.
*/
public static CellRangeAddress hasExactlyOneCellRange(Ptg[] tokens) {
CellRangeAddress addr = null;
for (int i = 0; i < tokens.length; i++) {
if (tokens[i] instanceof AreaPtgBase) {
if (addr != null) {
return null;
} else {
addr = Utils.areaPtgToAddress((AreaPtgBase) tokens[i]);
}
}
}
return addr;
}
/**
* If there is exactly one cell reference in the parsed formula tokens,
* returns it. Otherwise returns null.
*
* @param tokens
* @return null if there are multiple cell references found in the formula
* tokens. Otherwise return the only cell reference in the formula tokens.
*/
public static CellRangeAddress hasExactlyOneCellReference(Ptg[] tokens) {
CellRangeAddress addr = null;
for (int i = 0; i < tokens.length; i++) {
if (tokens[i] instanceof RefPtgBase) {
if (addr != null) {
return null;
} else {
addr = Utils.refPtgToAddress((RefPtgBase) tokens[i]);
}
}
}
return addr;
}
/**
* Converts an AreaPtg to a CellRangeAddress object.
*
* @param area
* @return The CellRangeAddress representation of the area ptg.
*/
public static CellRangeAddress areaPtgToAddress(AreaPtgBase area) {
return new CellRangeAddress(area.getFirstRow(), area.getLastRow(), area.getFirstColumn(), area.getLastColumn());
}
/**
* Converts an RefPtg to a CellRangeAddress object.
*
* @param ref
* @return The CellRangeAddress representation of the ref ptg.
*/
public static CellRangeAddress refPtgToAddress(RefPtgBase ref) {
return new CellRangeAddress(ref.getRow(), ref.getRow(), ref.getColumn(), ref.getColumn());
}
}
| 2,860 | 28.494845 | 116 | java |
null | tacolens-main/web-server/src/main/dataspread/utils/Controller.java | package dataspread.utils;
import spark.RouteGroup;
/**
* An interface for definining API controllers.
*/
public interface Controller {
public String getPrefix();
public RouteGroup getRoutes();
}
| 203 | 16 | 47 | java |
null | tacolens-main/web-server/src/main/dataspread/taco/TacoController.java | package dataspread.taco;
import static org.dataspread.sheetanalyzer.dependency.util.RefUtils.fromStringToCell;
import static spark.Spark.post;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.dataspread.sheetanalyzer.SheetAnalyzer;
import org.dataspread.sheetanalyzer.dependency.util.RefWithMeta; //for testing
import org.dataspread.sheetanalyzer.util.Ref;
import dataspread.taco.TacoService.PatternType;
import dataspread.utils.Controller;
import dataspread.utils.Utils;
import spark.RouteGroup;
public class TacoController implements Controller {
private SheetAnalyzer sheetAnalyzer = null;
private SheetAnalyzer noCompSheetAnalyzer = null;
private String graphType = "taco";
private static String defaultSheetName = "default-sheet-name";
@Override
public String getPrefix() {
return "/taco";
}
public RouteGroup getRoutes() {
return () -> {
post("/patterns", (req, res) -> {
JsonObject body = new Gson().fromJson(req.body(), JsonObject.class);
String type = body.get("type").toString().toLowerCase();
if (type.contains("set")) {
this.graphType = body.get("graph").toString().toLowerCase();
return new Gson().toJson(Map.of("data", new String[0]));
} else {
if (type.contains("build") || type.contains("get")) {
// For building graphs, content should be [][]string
JsonElement formulae = body.get("formulae");
if (formulae != null) {
// Building the dependency graph
JsonArray mtx = formulae.getAsJsonArray();
String[][] fMtx = Utils.jsonMtxToStringMtx(mtx);
PatternType[][] hMtx = TacoService.getPatterns(fMtx);
Map<String, String[][]> spreadsheetContent = new HashMap<>();
spreadsheetContent.put(defaultSheetName, fMtx);
if (type.contains("build")) {
if (this.graphType.contains("taco")) {
sheetAnalyzer = SheetAnalyzer.createSheetAnalyzer(spreadsheetContent);
} else {
noCompSheetAnalyzer = SheetAnalyzer.createNoCompSheetAnalyzer(spreadsheetContent);
}
}
if (this.graphType.contains("taco")) {
if (sheetAnalyzer != null) {
return new Gson().toJson(Map.of("data", hMtx, "taco", sheetAnalyzer.getTACODepGraphs()));
} else {
return new Gson().toJson(Map.of("data", new String[0]));
}
} else {
if (noCompSheetAnalyzer != null) {
return new Gson().toJson(Map.of("data", hMtx, "taco", noCompSheetAnalyzer.getTACODepGraphs()));
} else {
return new Gson().toJson(Map.of("data", new String[0]));
}
}
} else {
// Return empty json
return new Gson().toJson(Map.of("data", new String[0]));
}
} else {
// For finding dependents/precedents, content should be a string indicating the range (A1:B10)
String range = body.get("range").toString();
String isDirect = body.get("isDirect").toString().toLowerCase();
range = TacoService.parseAddressString(range);
SheetAnalyzer targetSheetAnalyzer;
if (this.graphType.contains("taco")) {
targetSheetAnalyzer = sheetAnalyzer;
} else {
targetSheetAnalyzer = noCompSheetAnalyzer;
}
if (targetSheetAnalyzer != null) {
Ref target = TacoService.fromStringtoRange(range);
Map<Ref, List<RefWithMeta>> result;
if (type.contains("dep")) {
if (isDirect.contains("true")) {
result = targetSheetAnalyzer.getDependentsSubGraph(defaultSheetName, target, true);
} else {
result = targetSheetAnalyzer.getDependentsSubGraph(defaultSheetName, target, false);
}
} else {
if (isDirect.contains("true")) {
result = targetSheetAnalyzer.getPrecedentsSubGraph(defaultSheetName, target, true);
} else {
result = targetSheetAnalyzer.getPrecedentsSubGraph(defaultSheetName, target, false);
}
}
Map<String, Map<Ref, List<RefWithMeta>>> subgraph = new HashMap<>();
subgraph.put(defaultSheetName, result);
return new Gson().toJson(Map.of("data", new String[0], "taco", subgraph));
} else {
// Return empty json
return new Gson().toJson(Map.of("data", new String[0]));
}
}
}
});
};
}
private void debug(Map<String,Map<Ref,List<RefWithMeta>>> data) {
for (String r: data.keySet()) {
Map<Ref,List<RefWithMeta>> ref = data.get(r);
System.out.println(r + ": ");
for (Map.Entry<Ref,List<RefWithMeta>> deps : ref.entrySet()) {
System.out.println("\t" + deps.getKey() + ":");
for (RefWithMeta meta : deps.getValue()) {
System.out.println("\t\t" + meta.getRef() + " | " + meta.getPatternType());
}
}
}
}
}
| 5,439 | 40.212121 | 113 | java |
null | tacolens-main/web-server/src/main/dataspread/taco/TacoService.java | package dataspread.taco;
import dataspread.utils.ApiFormulaParser;
import dataspread.utils.Utils;
import org.apache.poi.ss.util.CellRangeAddress;
import org.dataspread.sheetanalyzer.util.Ref;
import org.dataspread.sheetanalyzer.util.RefImpl;
import java.io.IOException;
public class TacoService {
public enum PatternType {
RR_GAP_ONE,
RR_CHAIN,
UNKNOWN,
NO_COMP,
RR,
RF,
FR,
FF,
}
public static Ref fromStringtoRange(String cellStr) {
String[] content = cellStr.split(":");
String start = content[0];
String end;
if (content.length > 1) {
end = content[1];
} else {
end = content[0];
}
StringBuilder startRowStr = new StringBuilder();
StringBuilder endRowStr = new StringBuilder();
StringBuilder startColStr = new StringBuilder();
StringBuilder endColStr = new StringBuilder();
// Start
for (int i = 0; i < start.length(); ++i) {
char s = start.charAt(i);
if (Character.isDigit(s)) {
startRowStr.append(s);
} else {
startColStr.append(s);
}
}
String col = startColStr.toString();
int rowIdx = Integer.parseInt(startRowStr.toString()) - 1;
int colIdx = 0;
char[] colChars = col.toLowerCase().toCharArray();
for(int i = 0; i < colChars.length; ++i) {
colIdx = (int)((double)colIdx + (double)(colChars[i] - 97 + 1) * Math.pow(26.0D, (double)(colChars.length - i - 1)));
}
--colIdx;
// End
for (int i = 0; i < end.length(); ++i) {
char s = end.charAt(i);
if (Character.isDigit(s)) {
endRowStr.append(s);
} else {
endColStr.append(s);
}
}
col = endColStr.toString();
int endRowIdx = Integer.parseInt(endRowStr.toString()) - 1;
int endColIdx = 0;
colChars = col.toLowerCase().toCharArray();
for(int i = 0; i < colChars.length; ++i) {
endColIdx = (int)((double)endColIdx + (double)(colChars[i] - 97 + 1) * Math.pow(26.0D, (double)(colChars.length - i - 1)));
}
--endColIdx;
return new RefImpl(rowIdx, colIdx, endRowIdx, endColIdx);
}
public static String parseAddressString(String address) {
int startIdx = 0, endIdx = address.length() - 1;
while (startIdx < address.length()) {
char ch = address.charAt(startIdx);
if (Character.toString(ch).equals("!")) {
break;
} else {
startIdx += 1;
}
}
while (endIdx > startIdx) {
char ch = address.charAt(endIdx);
if (Character.isDigit(ch)) {
break;
} else {
endIdx -= 1;
}
}
return address.substring(startIdx+1, endIdx+1);
}
private static boolean isRRPattern(CellRangeAddress prev, CellRangeAddress curr) {
return
curr != null && prev != null &&
curr.getFirstColumn() != curr.getLastColumn() &&
curr.getFirstRow() != curr.getLastRow() &&
prev.getFirstColumn() != prev.getLastColumn() &&
prev.getFirstRow() != prev.getLastRow() &&
prev.getFirstColumn() == curr.getFirstColumn() &&
prev.getLastColumn() == curr.getLastColumn() &&
prev.getFirstRow() + 1 == curr.getFirstRow() &&
prev.getLastRow() + 1 == curr.getLastRow();
}
private static boolean isRFPattern(CellRangeAddress prev, CellRangeAddress curr) {
return
curr != null && prev != null &&
prev.getFirstColumn() == curr.getFirstColumn() &&
prev.getLastColumn() == curr.getLastColumn() &&
prev.getFirstRow() + 1 == curr.getFirstRow() &&
prev.getLastRow() == curr.getLastRow();
}
private static boolean isFRPattern(CellRangeAddress prev, CellRangeAddress curr) {
return
curr != null && prev != null &&
prev.getFirstColumn() == curr.getFirstColumn() &&
prev.getLastColumn() == curr.getLastColumn() &&
prev.getFirstRow() == curr.getFirstRow() &&
prev.getLastRow() + 1 == curr.getLastRow();
}
private static boolean isFFPattern(CellRangeAddress prev, CellRangeAddress curr) {
return
curr != null && prev != null &&
prev.getFirstColumn() == curr.getFirstColumn() &&
prev.getLastColumn() == curr.getLastColumn() &&
prev.getFirstRow() == curr.getFirstRow() &&
prev.getLastRow() == curr.getLastRow();
}
private static boolean isRRChainPattern(CellRangeAddress prev, CellRangeAddress curr) {
return
curr != null && prev != null &&
curr.getFirstColumn() == curr.getLastColumn() &&
curr.getFirstRow() == curr.getLastRow() &&
prev.getFirstColumn() == prev.getLastColumn() &&
prev.getFirstRow() == prev.getLastRow() &&
curr.getFirstColumn() == prev.getFirstColumn() &&
curr.getFirstRow() == prev.getFirstRow() + 1;
}
private static void classifyPattern(CellRangeAddress[][] ranges, PatternType[][] patterns, int r, int c) {
// The formula parser iterates over cells row by row, so when
// this function is called, the cell above the current cell
// and the cell directly to the left of the current cell have
// already been visited and we know if they have exactly one
// range or not.
CellRangeAddress top = r - 1 >= 0 ? ranges[r - 1][c] : null;
CellRangeAddress lft = c - 1 >= 0 ? ranges[r][c - 1] : null;
CellRangeAddress cur = ranges[r][c];
if (top != null && lft != null) {
// If both the left and top cells have exactly one cell range
// or cell reference, then we check if the current cell matches
// the patterns in both the top and left cells. If they do, then
// the current cell also follows the same pattern.
if (
TacoService.isRRPattern(top, cur) &&
TacoService.isRRPattern(lft, cur)
) {
patterns[r][c] = patterns[r - 1][c] = patterns[r][c - 1] = PatternType.RR;
} else if (
TacoService.isRFPattern(top, cur) &&
TacoService.isRFPattern(lft, cur)
) {
patterns[r][c] = patterns[r - 1][c] = patterns[r][c - 1] = PatternType.RF;
} else if (
TacoService.isFRPattern(top, cur)&&
TacoService.isFRPattern(lft, cur)
) {
patterns[r][c] = patterns[r - 1][c] = patterns[r][c - 1] = PatternType.FR;
} else if (
TacoService.isFFPattern(top, cur) &&
TacoService.isFFPattern(lft, cur)
) {
patterns[r][c] = patterns[r - 1][c] = patterns[r][c - 1] = PatternType.FF;
} else if (
TacoService.isRRChainPattern(top, cur) &&
TacoService.isRRChainPattern(lft, cur)
) {
patterns[r][c] = patterns[r - 1][c] = patterns[r][c - 1] = PatternType.RR_CHAIN;
} else {
// If both the top and left cells have exactly one cell range (or
// cell reference), but the current cell does not match the patterns
// in both the top and left cells, then we arbitrarily use the left
// cell for classification first. If there are no pattern matches,
// then the top cell is used next. If there are still no matches,
// then the cell is marked as incompressable.
if (TacoService.isRRPattern(lft, cur)) {
patterns[r][c] = patterns[r][c - 1] = PatternType.RR;
} else if (TacoService.isRFPattern(lft, cur)) {
patterns[r][c] = patterns[r][c - 1] = PatternType.RF;
} else if (TacoService.isFRPattern(lft, cur)) {
patterns[r][c] = patterns[r][c - 1] = PatternType.FR;
} else if (TacoService.isFFPattern(lft, cur)) {
patterns[r][c] = patterns[r][c - 1] = PatternType.FF;
} else if (TacoService.isRRChainPattern(lft, cur)) {
patterns[r][c] = patterns[r][c - 1] = PatternType.RR_CHAIN;
} else if (TacoService.isRRPattern(top, cur)) {
patterns[r][c] = patterns[r - 1][c] = PatternType.RR;
} else if (TacoService.isRFPattern(top, cur)) {
patterns[r][c] = patterns[r - 1][c] = PatternType.RF;
} else if (TacoService.isFRPattern(top, cur)) {
patterns[r][c] = patterns[r - 1][c] = PatternType.FR;
} else if (TacoService.isFFPattern(top, cur)) {
patterns[r][c] = patterns[r - 1][c] = PatternType.FF;
} else if (TacoService.isRRChainPattern(top, cur)) {
patterns[r][c] = patterns[r - 1][c] = PatternType.RR_CHAIN;
} else {
patterns[r][c] = PatternType.NO_COMP;
}
}
} else if (top != null) {
// If only the top cell has one cell range (or cell reference),
// then we simply check for a pattern between it and the current
// cell.
if (TacoService.isRRPattern(top, cur)) {
patterns[r][c] = patterns[r - 1][c] = PatternType.RR;
} else if (TacoService.isRFPattern(top, cur)) {
patterns[r][c] = patterns[r - 1][c] = PatternType.RF;
} else if (TacoService.isFRPattern(top, cur)) {
patterns[r][c] = patterns[r - 1][c] = PatternType.FR;
} else if (TacoService.isFFPattern(top, cur)) {
patterns[r][c] = patterns[r - 1][c] = PatternType.FF;
} else if (TacoService.isRRChainPattern(top, cur)) {
patterns[r][c] = patterns[r - 1][c] = PatternType.RR_CHAIN;
} else {
patterns[r][c] = PatternType.NO_COMP;
}
} else if (lft != null) {
// If only the left cell has one cell range (or cell reference),
// then we simply check for a pattern between it and the current
// cell.
if (TacoService.isRRPattern(lft, cur)) {
patterns[r][c] = patterns[r][c - 1] = PatternType.RR;
} else if (TacoService.isRFPattern(lft, cur)) {
patterns[r][c] = patterns[r][c - 1] = PatternType.RF;
} else if (TacoService.isFRPattern(lft, cur)) {
patterns[r][c] = patterns[r][c - 1] = PatternType.FR;
} else if (TacoService.isFFPattern(lft, cur)) {
patterns[r][c] = patterns[r][c - 1] = PatternType.FF;
} else if (TacoService.isRRChainPattern(lft, cur)) {
patterns[r][c] = patterns[r][c - 1] = PatternType.RR_CHAIN;
} else {
patterns[r][c] = PatternType.NO_COMP;
}
} else {
// At this point, both the top cell and left cell don't have exactly
// one cell range (or cell reference), so we don't have enough info
// to classify the current cell.
patterns[r][c] = PatternType.UNKNOWN;
}
}
/**
* Given a matrix of Excel formula strings, find all the TACO patterns
* in the matrix.
*
* @param formulaMtx
* @return A matrix of TACO patterns with the same shape as the input.
* @throws IOException
*/
public static PatternType[][] getPatterns(String[][] formulaMtx) throws IOException {
PatternType[][] patterns = new PatternType[formulaMtx.length][formulaMtx[0].length];
CellRangeAddress[][] ranges = new CellRangeAddress[formulaMtx.length][formulaMtx[0].length];
ApiFormulaParser.parseFormulae(formulaMtx, (ptgs, i, j) -> {
if (ptgs != null) {
CellRangeAddress rng = Utils.hasExactlyOneCellRange(ptgs);
CellRangeAddress ref = Utils.hasExactlyOneCellReference(ptgs);
if (rng != null) {
ranges[i][j] = rng;
} else if (ref != null) {
ranges[i][j] = ref;
}
TacoService.classifyPattern(ranges, patterns, i, j);
}
});
return patterns;
}
}
| 11,242 | 37.903114 | 129 | java |
coala | coala-master/tests/bearlib/languages/documentation/documentation_extraction_testdata/default.java | class HelloWorld {
/**
* Returns an String that says Hello with the name argument.
*
* @param name the name to which to say hello
* @raises IOException throws IOException
* @return the concatenated string
*/
public String sayHello(String name) throws IOException {
return "Hello, " + name;
}
}
| 345 | 23.714286 | 63 | java |
YCSB-CouchDB-Binding | YCSB-CouchDB-Binding-master/src/com/akhil/dbproject/couchdb/CouchClient.java | package com.akhil.dbproject.couchdb;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import org.lightcouch.CouchDbClient;
import org.lightcouch.CouchDbProperties;
import org.lightcouch.Document;
import org.lightcouch.View;
import com.google.gson.JsonObject;
import com.yahoo.ycsb.ByteArrayByteIterator;
import com.yahoo.ycsb.ByteIterator;
import com.yahoo.ycsb.DB;
import com.yahoo.ycsb.DBException;
import com.yahoo.ycsb.Status;
public class CouchClient extends DB {
private CouchDbClient dbClient;
private int batchSize;
private List<JsonObject> batchInsertList;
@Override
public void init() throws DBException {
CouchDbProperties properties = new CouchDbProperties();
//CouchDB host IP
properties.setHost("127.0.0.1");
//CouchDB port - default is 5984
properties.setPort(5984);
//CouchDB database name
properties.setDbName("testdb");
//Also set username and password here if required
properties.setCreateDbIfNotExist(true);
properties.setProtocol("http");
Properties props = getProperties();
batchInsertList = new ArrayList<JsonObject>();
//batchsize is used in case of insertions
batchSize = Integer.parseInt(props.getProperty("batchsize", "10000"));
dbClient = new CouchDbClient(properties);
super.init();
}
@Override
public Status read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) {
JsonObject found = dbClient.find(JsonObject.class, key, "stale=ok");
if (null == found)
return Status.NOT_FOUND;
if (fields != null) {
JsonObject jsonObject = new JsonObject();
jsonObject.add("_id", found.get("_id"));
jsonObject.add("_rev", found.get("_rev"));
for (String field : fields) {
jsonObject.add(field, found.get(field));
}
result.put(found.get("_id").toString(), new ByteArrayByteIterator(jsonObject.toString().getBytes()));
}
return Status.OK;
}
@Override
public Status scan(String table, String startkey, int recordcount, Set<String> fields,
Vector<HashMap<String, ByteIterator>> result) {
View view = dbClient.view("_all_docs").startKeyDocId(startkey).limit(recordcount).includeDocs(true);
HashMap<String, ByteIterator> resultMap = new HashMap<String, ByteIterator>();
List<JsonObject> list = view.query(JsonObject.class);
if (fields != null) {
for (JsonObject doc : list) {
JsonObject jsonObject = new JsonObject();
jsonObject.add("_id", doc.get("_id"));
jsonObject.add("_rev", doc.get("_rev"));
for (String field : fields) {
jsonObject.add(field, doc.get(field));
}
resultMap.put(doc.get("_id").toString(), new ByteArrayByteIterator(jsonObject.toString().getBytes()));
}
result.add(resultMap);
}
for (HashMap<String, ByteIterator> map : result) {
for (String key : map.keySet()) {
System.out.println(map.get(key).toString());
}
}
return Status.OK;
}
@Override
public Status update(String table, String key, HashMap<String, ByteIterator> values) {
JsonObject jsonObject = dbClient.find(JsonObject.class, key);
if (null == jsonObject) {
return Status.NOT_FOUND;
}
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
jsonObject.addProperty(entry.getKey(), entry.getValue().toString());
}
dbClient.update(jsonObject);
return Status.OK;
}
@Override
public Status insert(String table, String key, HashMap<String, ByteIterator> values) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("_id", key);
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
jsonObject.addProperty(entry.getKey(), entry.getValue().toString());
}
if (batchSize == 1) {
dbClient.save(jsonObject);
} else {
batchInsertList.add(jsonObject);
if (batchInsertList.size() == batchSize) {
dbClient.bulk(batchInsertList, false);
batchInsertList.clear();
}
}
return Status.OK;
}
@Override
public Status delete(String table, String key) {
dbClient.remove(dbClient.find(Document.class, key));
return Status.OK;
}
}
| 4,117 | 30.435115 | 106 | java |
pmd | pmd-master/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/RuleSetFactoryTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift;
import net.sourceforge.pmd.AbstractRuleSetFactoryTest;
class RuleSetFactoryTest extends AbstractRuleSetFactoryTest {
// no additional unit tests
}
| 282 | 22.583333 | 79 | java |
pmd | pmd-master/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/LanguageVersionTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift;
import java.util.Arrays;
import java.util.Collection;
import net.sourceforge.pmd.AbstractLanguageVersionTest;
class LanguageVersionTest extends AbstractLanguageVersionTest {
static Collection<TestDescriptor> data() {
return Arrays.asList(new TestDescriptor(SwiftLanguageModule.NAME, SwiftLanguageModule.TERSE_NAME, "5.7",
getLanguage(SwiftLanguageModule.NAME).getDefaultVersion()));
}
}
| 551 | 28.052632 | 112 | java |
pmd | pmd-master/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/ast/SwiftParsingHelper.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.ast;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper;
import net.sourceforge.pmd.lang.swift.SwiftLanguageModule;
import net.sourceforge.pmd.lang.swift.ast.SwiftParser.SwTopLevel;
public class SwiftParsingHelper extends BaseParsingHelper<SwiftParsingHelper, SwTopLevel> {
public static final SwiftParsingHelper DEFAULT = new SwiftParsingHelper(Params.getDefault());
public SwiftParsingHelper(@NonNull Params params) {
super(SwiftLanguageModule.NAME, SwTopLevel.class, params);
}
@NonNull
@Override
protected SwiftParsingHelper clone(@NonNull Params params) {
return new SwiftParsingHelper(params);
}
}
| 849 | 29.357143 | 97 | java |
pmd | pmd-master/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/ast/SwiftParserTests.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.ast;
import org.junit.jupiter.api.Test;
class SwiftParserTests extends BaseSwiftTreeDumpTest {
@Test
void testSimpleSwift() {
doTest("Simple");
}
@Test
void testBtree() {
doTest("BTree");
}
}
| 364 | 15.590909 | 79 | java |
pmd | pmd-master/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/ast/BaseSwiftTreeDumpTest.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.ast;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest;
import net.sourceforge.pmd.lang.ast.test.NodePrintersKt;
/**
*
*/
public class BaseSwiftTreeDumpTest extends BaseTreeDumpTest {
public BaseSwiftTreeDumpTest() {
super(NodePrintersKt.getSimpleNodePrinter(), ".swift");
}
@NonNull
@Override
public SwiftParsingHelper getParser() {
return SwiftParsingHelper.DEFAULT.withResourceContext(getClass(), "testdata");
}
}
| 659 | 22.571429 | 86 | java |
pmd | pmd-master/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/rule/errorprone/ForceTryTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.rule.errorprone;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ForceTryTest extends PmdRuleTst {
// no additional unit tests
}
| 274 | 21.916667 | 79 | java |
pmd | pmd-master/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/rule/errorprone/ForceCastTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.rule.errorprone;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ForceCastTest extends PmdRuleTst {
// no additional unit tests
}
| 275 | 22 | 79 | java |
pmd | pmd-master/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/rule/bestpractices/ProhibitedInterfaceBuilderTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.rule.bestpractices;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class ProhibitedInterfaceBuilderTest extends PmdRuleTst {
// no additional unit tests
}
| 295 | 23.666667 | 79 | java |
pmd | pmd-master/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/rule/bestpractices/UnavailableFunctionTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.rule.bestpractices;
import net.sourceforge.pmd.testframework.PmdRuleTst;
class UnavailableFunctionTest extends PmdRuleTst {
// no additional unit tests
}
| 288 | 23.083333 | 79 | java |
pmd | pmd-master/pmd-swift/src/test/java/net/sourceforge/pmd/cpd/SwiftTokenizerTest.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.cpd;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.cpd.test.CpdTextComparisonTest;
class SwiftTokenizerTest extends CpdTextComparisonTest {
SwiftTokenizerTest() {
super(".swift");
}
@Override
protected String getResourcePrefix() {
return "../lang/swift/cpd/testdata";
}
@Override
public Tokenizer newTokenizer(Properties properties) {
return new SwiftTokenizer();
}
@Test
void testSwift42() {
doTest("Swift4.2");
}
@Test
void testSwift50() {
doTest("Swift5.0");
}
@Test
void testSwift51() {
doTest("Swift5.1");
}
@Test
void testSwift52() {
doTest("Swift5.2");
}
@Test
void testSwift53() {
doTest("Swift5.3");
}
@Test
void testSwift55() {
doTest("Swift5.5");
}
@Test
void testSwift56() {
doTest("Swift5.6");
}
@Test
void testStackoverflowOnLongLiteral() {
doTest("Issue628");
}
@Test
void testTabWidth() {
doTest("tabWidth");
}
}
| 1,244 | 15.6 | 79 | java |
pmd | pmd-master/pmd-swift/src/main/java/net/sourceforge/pmd/lang/swift/AbstractSwiftRule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.rule.AbstractVisitorRule;
import net.sourceforge.pmd.lang.swift.ast.SwiftVisitor;
public abstract class AbstractSwiftRule extends AbstractVisitorRule {
protected AbstractSwiftRule() {
// inheritance constructor
}
@Override
public abstract SwiftVisitor<RuleContext, ?> buildVisitor();
}
| 515 | 24.8 | 79 | java |
pmd | pmd-master/pmd-swift/src/main/java/net/sourceforge/pmd/lang/swift/SwiftLanguageModule.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import java.util.List;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.lang.impl.SimpleLanguageModuleBase;
/**
* Language Module for Swift
*/
public class SwiftLanguageModule extends SimpleLanguageModuleBase {
/** The name. */
public static final String NAME = "Swift";
/** The terse name. */
public static final String TERSE_NAME = "swift";
@InternalApi
public static final List<String> EXTENSIONS = listOf("swift");
/**
* Create a new instance of Swift Language Module.
*/
public SwiftLanguageModule() {
super(LanguageMetadata.withId(TERSE_NAME).name(NAME)
.extensions(EXTENSIONS)
.addVersion("4.2")
.addVersion("5.0")
.addVersion("5.1")
.addVersion("5.2")
.addVersion("5.3")
.addVersion("5.4")
.addVersion("5.5")
.addVersion("5.6")
.addDefaultVersion("5.7"),
new SwiftHandler());
}
}
| 1,387 | 29.844444 | 79 | java |
pmd | pmd-master/pmd-swift/src/main/java/net/sourceforge/pmd/lang/swift/SwiftHandler.java | /**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift;
import net.sourceforge.pmd.lang.AbstractPmdLanguageVersionHandler;
import net.sourceforge.pmd.lang.ast.Parser;
import net.sourceforge.pmd.lang.swift.ast.PmdSwiftParser;
public class SwiftHandler extends AbstractPmdLanguageVersionHandler {
@Override
public Parser getParser() {
return new PmdSwiftParser();
}
}
| 462 | 24.722222 | 79 | java |
pmd | pmd-master/pmd-swift/src/main/java/net/sourceforge/pmd/lang/swift/ast/SwiftRootNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.ast;
import org.antlr.v4.runtime.ParserRuleContext;
import net.sourceforge.pmd.lang.ast.AstInfo;
import net.sourceforge.pmd.lang.ast.Parser.ParserTask;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.swift.ast.SwiftParser.SwTopLevel;
// package private base class
abstract class SwiftRootNode extends SwiftInnerNode implements RootNode {
private AstInfo<SwTopLevel> astInfo;
SwiftRootNode(ParserRuleContext parent, int invokingStateNumber) {
super(parent, invokingStateNumber);
}
@Override
public AstInfo<SwTopLevel> getAstInfo() {
return astInfo;
}
SwTopLevel makeAstInfo(ParserTask task) {
SwTopLevel me = (SwTopLevel) this;
this.astInfo = new AstInfo<>(task, me);
return me;
}
}
| 919 | 25.285714 | 79 | java |
pmd | pmd-master/pmd-swift/src/main/java/net/sourceforge/pmd/lang/swift/ast/SwiftVisitorBase.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.ast;
import net.sourceforge.pmd.lang.ast.AstVisitorBase;
/**
* Base class for swift visitors.
*/
public abstract class SwiftVisitorBase<P, R> extends AstVisitorBase<P, R> implements SwiftVisitor<P, R> {
}
| 337 | 21.533333 | 105 | java |
pmd | pmd-master/pmd-swift/src/main/java/net/sourceforge/pmd/lang/swift/ast/SwiftNameDictionary.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.ast;
import org.antlr.v4.runtime.Vocabulary;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrNameDictionary;
final class SwiftNameDictionary extends AntlrNameDictionary {
SwiftNameDictionary(Vocabulary vocab, String[] ruleNames) {
super(vocab, ruleNames);
}
@Override
protected @Nullable String nonAlphaNumName(String name) {
{ // limit scope of 'sup', which would be null outside of here anyway
String sup = super.nonAlphaNumName(name);
if (sup != null) {
return sup;
}
}
if (name.charAt(0) == '#' && StringUtils.isAlphanumeric(name.substring(1))) {
return "directive-" + name.substring(1);
}
switch (name) {
case "unowned(safe)": return "unowned-safe";
case "unowned(unsafe)": return "unowned-unsafe";
case "getter:": return "getter";
case "setter:": return "setter";
case "OSXApplicationExtension\u00AD": return "OSXApplicationExtension-";
default: return null;
}
}
}
| 1,304 | 29.348837 | 85 | java |
pmd | pmd-master/pmd-swift/src/main/java/net/sourceforge/pmd/lang/swift/ast/SwiftInnerNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.ast;
import org.antlr.v4.runtime.ParserRuleContext;
import net.sourceforge.pmd.lang.ast.AstVisitor;
import net.sourceforge.pmd.lang.ast.impl.antlr4.BaseAntlrInnerNode;
// package private base class
abstract class SwiftInnerNode
extends BaseAntlrInnerNode<SwiftNode> implements SwiftNode {
SwiftInnerNode() {
super();
}
SwiftInnerNode(ParserRuleContext parent, int invokingStateNumber) {
super(parent, invokingStateNumber);
}
@Override
public <P, R> R acceptVisitor(AstVisitor<? super P, ? extends R> visitor, P data) {
if (visitor instanceof SwiftVisitor) {
// some of the generated antlr nodes have no accept method...
return ((SwiftVisitor<? super P, ? extends R>) visitor).visitSwiftNode(this, data);
}
return visitor.visitNode(this, data);
}
@Override // override to make visible in package
protected PmdAsAntlrInnerNode<SwiftNode> asAntlrNode() {
return super.asAntlrNode();
}
@Override
public String getXPathNodeName() {
return SwiftParser.DICO.getXPathNameOfRule(getRuleIndex());
}
}
| 1,263 | 27.727273 | 95 | java |
pmd | pmd-master/pmd-swift/src/main/java/net/sourceforge/pmd/lang/swift/ast/PmdSwiftParser.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.ast;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Lexer;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrBaseParser;
import net.sourceforge.pmd.lang.swift.ast.SwiftParser.SwTopLevel;
/**
* Adapter for the SwiftParser.
*/
public final class PmdSwiftParser extends AntlrBaseParser<SwiftNode, SwTopLevel> {
@Override
protected SwTopLevel parse(final Lexer lexer, ParserTask task) {
SwiftParser parser = new SwiftParser(new CommonTokenStream(lexer));
return parser.topLevel().makeAstInfo(task);
}
@Override
protected Lexer getLexer(final CharStream source) {
return new SwiftLexer(source);
}
}
| 847 | 27.266667 | 82 | java |
pmd | pmd-master/pmd-swift/src/main/java/net/sourceforge/pmd/lang/swift/ast/SwiftNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.ast;
import net.sourceforge.pmd.lang.ast.impl.antlr4.AntlrNode;
/**
* Supertype of all swift nodes.
*/
public interface SwiftNode extends AntlrNode<SwiftNode> {
}
| 297 | 16.529412 | 79 | java |
pmd | pmd-master/pmd-swift/src/main/java/net/sourceforge/pmd/lang/swift/ast/SwiftTerminalNode.java | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.swift.ast;
import org.antlr.v4.runtime.Token;
import org.checkerframework.checker.nullness.qual.NonNull;
import net.sourceforge.pmd.lang.ast.impl.antlr4.BaseAntlrTerminalNode;
public final class SwiftTerminalNode extends BaseAntlrTerminalNode<SwiftNode> implements SwiftNode {
SwiftTerminalNode(Token token) {
super(token);
}
@Override
public @NonNull String getText() {
String constImage = SwiftParser.DICO.getConstantImageOfToken(getFirstAntlrToken());
return constImage == null ? getFirstAntlrToken().getText()
: constImage;
}
@Override
public String getXPathNodeName() {
return SwiftParser.DICO.getXPathNameOfToken(getFirstAntlrToken().getType());
}
}
| 882 | 27.483871 | 100 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.