def run(self, data): try: if self.config.verbose: print('Creating Problem Instance...') instance = Instance(self.config, data) if self.config.verbose: print('Solving the Problem...') if instance.checkInstance(): initialSolution = None if self.config.solver == 'Greedy' or self.config.solver == 'Random': solver = Solver_Greedy(self.config, instance) elif self.config.solver == 'GRASP': solver = Solver_GRASP(self.config, instance) else: raise AMMMException('Solver %s not supported.' % str(self.config.solver)) solution = solver.solve(solution=initialSolution) if solution.feasible: print(str(solution)) solution.saveToFile(self.config.solutionFile) else: print('Instance is infeasible.') solution = instance.createSolution() solution.makeInfeasible() solution.saveToFile(self.config.solutionFile) return 0 except AMMMException as e: print('Exception:', e) return 1
def run(self, data): try: if self.config.verbose: print('Creating Problem Instance...') instance = Instance(self.config, data) if self.config.verbose: print('Solving the Problem...') if instance.checkInstance(): initialSolution = None if self.config.solver == 'Greedy' or self.config.solver == 'Random': solver = Solver_Greedy(self.config, instance) elif self.config.solver == 'GRASP': solver = Solver_GRASP(self.config, instance) elif self.config.solver == 'BRKGA': verbose = self.config.verbose self.config.verbose = False greedy = Solver_Greedy(self.config, instance) initialSolution = greedy.solve(solver='Greedy', localSearch=False) self.config.verbose = verbose decoder = Decoder(self.config, instance) solver = Solver_BRKGA(decoder, instance) else: raise AMMMException('Solver %s not supported.' % str(self.config.solver)) solution = solver.solve(solution=initialSolution) print('Solution (CPUid: [TasksId]): %s' % str(solution.cpuIdToListTaskId)) solution.saveToFile(self.config.solutionFile) else: print('Instance is infeasible.') solution = instance.createSolution() solution.makeInfeasible() solution.saveToFile(self.config.solutionFile) return 0 except AMMMException as e: print('Exception:', e) return 1
def construction(self): # get an empty solution for the problem solution = self.instance.createSolution() assignment = 0 complete = False while not complete: # get feasible assignments candidates = solution.findFeasibleAssignments() # no candidate assignments => no feasible assignment found if not candidates: solution.makeInfeasible() raise AMMMException('Greedy construction is infeasible. Please try again!') # break # assign the assignment with min cost candidate_with_min_cost = self._selectCandidate(candidates) pc_or_sc = 'primary' if candidate_with_min_cost.is_primary is True else 'secondary' solution.assign(candidate_with_min_cost.city, candidate_with_min_cost.location, candidate_with_min_cost.type, pc_or_sc, check_completeness=True) # print(f'City {candidate_with_min_cost.city.getId()}, Location {candidate_with_min_cost.location.getId()}, # Type {candidate_with_min_cost.type.get_id()}, Cost {solution.cost}, {pc_or_sc}') complete = solution.complete assignment += 1 return solution
def solve(self, **kwargs): initialSolution = kwargs.get('solution', None) if initialSolution is None: raise AMMMException( '[local search] No solution could be retrieved') if not initialSolution.isFeasible(): return initialSolution self.startTime = kwargs.get('startTime', None) endTime = kwargs.get('endTime', None) incumbent = initialSolution incumbentFitness = incumbent.getFitness() iterations = 0 # keep iterating while improvements are found while time.time() < endTime: iterations += 1 neighbor = self.exploreNeighborhood(incumbent) if neighbor is None: break neighborFitness = neighbor.getFitness() if incumbentFitness <= neighborFitness: break incumbent = neighbor incumbentFitness = neighborFitness return incumbent
def exploreNeighborhood(self, solution): if self.nhStrategy == 'TaskExchange': return self.exploreExchange(solution) elif self.nhStrategy == 'Reassignment': return self.exploreReassignment(solution) else: raise AMMMException('Unsupported NeighborhoodStrategy(%s)' % self.nhStrategy)
def printValues(self, fieldValues): if type(fieldValues) != dict: raise AMMMException('[Logger.printValues] Attribute "fieldValues" must be a dictionary indexed by field id ' 'and the field value as value') values = [] for field in self._fields: fieldId = field['id'] fieldFormat = field['format'] if fieldId not in fieldValues: raise AMMMException('[Logger.printValues] No value has not been provided for field "%s"' % fieldId) value = fieldValues[fieldId] value = fieldFormat.format(value) values.append(value) print(' '.join(values)) sys.stdout.flush() self._fieldValues.append(values)
def __init__(self, fields): self._fields = [] self._fieldNames = [] self._fieldValues = [] if type(fields) != list: raise AMMMException('[Logger.__init__] Attribute "fields" must be a list and each entry should contain a ' 'dictionary with attributes "id", "name", "headerformat" and "valueformat"') for field in fields: if type(field['id']) != str: raise AMMMException('[Logger.__init__] Field "id" must be a string') if type(field['name']) != str: raise AMMMException('[Logger.__init__] Field "name" must be a string') if type(field['headerformat']) != str: raise AMMMException('[Logger.__init__] Field "headerformat" must be a string') if type(field['valueformat']) != str: raise AMMMException('[Logger.__init__] Field "valueformat" must be a string') fieldName = field['headerformat'].format(field['name']) self._fields.append({'id': field['id'], 'name': fieldName, 'format': field['valueformat']}) self._fieldNames.append(fieldName)
def exploreExchange(self, solution): curHighestLoad = solution.getFitness() bestNeighbor = solution # For the Exchange neighborhood and first improvement policy, try exchanging # two tasks assigned to two different CPUs. cpusWithAssignments = self.getCPUswithAssignemnts(solution) nCPUs = len(cpusWithAssignments) for h in range(0, nCPUs - 1): # i = 0..(nCPUs-2) CPUPair_h = cpusWithAssignments[h] availCapacityCPU_h = CPUPair_h[2] for th in range(0, len(CPUPair_h[3])): taskPair_h = CPUPair_h[3][th] for l in range(1, nCPUs): # i = 1..(nCPUs-1) CPUPair_l = cpusWithAssignments[l] availCapacityCPU_l = CPUPair_l[2] for tl in range(0, len(CPUPair_l[3])): taskPair_l = CPUPair_l[3][tl] if (taskPair_l[1] - taskPair_h[1]) <= availCapacityCPU_h and\ (taskPair_h[1] - taskPair_l[1]) <= availCapacityCPU_l and \ (taskPair_l[1] != taskPair_h[1]) and \ (availCapacityCPU_l + taskPair_l[1] - taskPair_h[1]) != availCapacityCPU_h : moves = [ Move(taskPair_h[0], CPUPair_h[0], CPUPair_l[0]), Move(taskPair_l[0], CPUPair_l[0], CPUPair_h[0]) ] neighborHighestLoad = self.evaluateNeighbor( solution, moves) if neighborHighestLoad <= curHighestLoad: neighbor = self.createNeighborSolution( solution, moves) if neighbor is None: raise AMMMException( '[exploreExchange] No neighbouring solution could be created' ) if self.policy == 'FirstImprovement': return neighbor else: bestNeighbor = neighbor curHighestLoad = neighborHighestLoad return bestNeighbor
def validate(data): # Validate that all input parameters were found for paramName in ['nTasks', 'nCPUs', 'rt', 'rc']: if paramName not in data.__dict__: raise AMMMException( 'Parameter/Set(%s) not contained in Input Data' % str(paramName)) # Validate nTasks nTasks = data.nTasks if not isinstance(nTasks, int) or (nTasks <= 0): raise AMMMException( 'nTasks(%s) has to be a positive integer value.' % str(nTasks)) # Validate nCPUs nCPUs = data.nCPUs if not isinstance(nCPUs, int) or (nCPUs <= 0): raise AMMMException( 'nCPUs(%s) has to be a positive integer value.' % str(nCPUs)) # Validate rt data.rt = list(data.rt) rt = data.rt if len(rt) != nTasks: raise AMMMException( 'Size of rt(%d) does not match with value of nTasks(%d).' % (len(rt), nTasks)) for value in rt: if not isinstance(value, (int, float)) or (value < 0): raise AMMMException( 'Invalid parameter value(%s) in rt. Should be a float greater or equal than zero.' % str(value)) # Validate rc data.rc = list(data.rc) rc = data.rc if len(rc) != nCPUs: raise AMMMException( 'Size of rc(%d) does not match with value of nCPUs(%d).' % (len(rc), nCPUs)) for value in rc: if not isinstance(value, (int, float)) or (value < 0): raise AMMMException( 'Invalid parameter value(%s) in rc. Should be a float greater or equal than zero.' % str(value))
def generate(self): instancesDirectory = self.config.instancesDirectory fileNamePrefix = self.config.fileNamePrefix fileNameExtension = self.config.fileNameExtension numInstances = self.config.numInstances numCPUs = self.config.numCPUs minCapacityPerCPU = self.config.minCapacityPerCPU maxCapacityPerCPU = self.config.maxCapacityPerCPU numTasks = self.config.numTasks minResourcesPerTask = self.config.minResourcesPerTask maxResourcesPerTask = self.config.maxResourcesPerTask if not os.path.isdir(instancesDirectory): raise AMMMException('Directory(%s) does not exist' % instancesDirectory) for i in range(numInstances): instancePath = os.path.join( instancesDirectory, '%s_cpu_%d_task_%d_%d.%s' % (fileNamePrefix, numCPUs, numTasks, i, fileNameExtension)) fInstance = open(instancePath, 'w') cpuCapacity = [0] * numCPUs for c in range(numCPUs): cpuCapacity[c] = random.uniform(minCapacityPerCPU, maxCapacityPerCPU) taskResources = [0] * numTasks for t in range(numTasks): taskResources[t] = random.uniform(minResourcesPerTask, maxResourcesPerTask) fInstance.write('nTasks=%d;\n' % numTasks) fInstance.write('nCPUs=%d;\n' % numCPUs) # translate vector of floats into vector of strings and concatenate that strings separating them by a single space character fInstance.write('rt=[%s];\n' % (' '.join(map(str, taskResources)))) fInstance.write('rc=[%s];\n' % (' '.join(map(str, cpuCapacity)))) fInstance.close()
def decodeIndividual(self, chromosome): if len(chromosome) != self.instance.getNumTasks(): raise AMMMException( "Error: the length of the chromosome does not fits the number of tasks" ) # get an empty solution for the problem solution = self.instance.createSolution() # get tasks and sort them by their total required resources in descending order tasks = self.instance.getTasks() for tId in range(len(tasks)): tasks[tId].gene = chromosome[tId] sortedTasks = sorted(tasks, key=lambda t: t.getWeightedResources(), reverse=True) # for each task taken in sorted order for task in sortedTasks: taskId = task.getId() # compute feasible assignments candidateList = solution.findFeasibleAssignments(taskId) # no candidate assignments => no feasible assignment found if not candidateList: solution.makeInfeasible() break # select the best assignment bestCandidate = self.selectCandidate(candidateList) # assign the current task to the CPU that resulted in a minimum highest load solution.assign(task.getId(), bestCandidate.cpuId) return solution, solution.getFitness()
def setGeneration(self, newGeneration): if newGeneration is None or len( newGeneration) != self.config.numIndividuals: raise AMMMException( "ERROR: trying to set store a wrong generation vector") self.currentGeneration = newGeneration
def validate(data): # Validate that mandatory input parameters were found paramList = ['instancesDirectory', 'fileNamePrefix', 'fileNameExtension', 'numInstances', 'nLocations', 'nCities', 'nTypes', 'min_d_city', 'max_d_city', 'min_cap', 'max_cap', 'min_cost', 'max_cost'] for paramName in paramList: if paramName not in data.__dict__: raise AMMMException('Parameter(%s) has not been not specified in Configuration' % str(paramName)) instancesDirectory = data.instancesDirectory if len(instancesDirectory) == 0: raise AMMMException('Value for instancesDirectory is empty') fileNamePrefix = data.fileNamePrefix if len(fileNamePrefix) == 0: raise AMMMException('Value for fileNamePrefix is empty') fileNameExtension = data.fileNameExtension if len(fileNameExtension) == 0: raise AMMMException('Value for fileNameExtension is empty') numInstances = data.numInstances if not isinstance(numInstances, int) or (numInstances <= 0): raise AMMMException('numInstances(%s) has to be a positive integer value.' % str(numInstances)) nLocations = data.nLocations if not isinstance(nLocations, int) or (nLocations <= 0): raise AMMMException('nLocations(%s) has to be a positive integer value.' % str(nLocations)) nCities = data.nCities if not isinstance(nCities, int) or (nCities <= 0): raise AMMMException('nCities(%s) has to be a positive integer value.' % str(nCities)) nTypes = data.nTypes if not isinstance(nTypes, int) or (nTypes <= 0): raise AMMMException('nTypes(%s) has to be a positive integer value.' % str(nTypes)) min_d_city = data.min_d_city if not isinstance(min_d_city, int) or (min_d_city <= 0): raise AMMMException('min_d_city(%s) has to be a positive integer value.' % str(min_d_city)) max_d_city = data.max_d_city if not isinstance(max_d_city, int) or (max_d_city <= 0): raise AMMMException('max_d_city(%s) has to be a positive integer value.' % str(max_d_city)) min_cap = data.min_cap if not isinstance(min_cap, (int, float)) or (min_cap <= 0): raise AMMMException('min_cap(%s) has to be a positive float value.' % str(min_cap)) max_cap = data.max_cap if not isinstance(max_cap, (int, float)) or (max_cap <= 0): raise AMMMException('min_d_city(%s) has to be a positive float value.' % str(max_cap)) min_cost = data.min_cost if not isinstance(min_cost, (int, float)) or (min_cost <= 0): raise AMMMException('min_d_city(%s) has to be a positive float value.' % str(min_cost)) max_cost = data.max_cost if not isinstance(max_cost, (int, float)) or (max_cost <= 0): raise AMMMException('max_cost(%s) has to be a positive float value.' % str(max_cost)) if max_cost < min_cost: raise AMMMException('max_cost(%s) has to be >= min_cost(%s).' % (str(max_cost), str(min_cost))) if max_cap < min_cap: raise AMMMException('max_cap(%s) has to be >= min_cap(%s).' % (str(max_cap), str(max_cap))) if max_d_city < min_d_city: raise AMMMException('max_d_city(%s) has to be >= min_d_city(%s).' % (str(max_d_city), str(min_d_city)))
def setVerbose(self, verbose): if not isinstance(verbose, bool) or (verbose not in [True, False]): raise AMMMException('verbose(%s) has to be a boolean value.' % str(verbose)) self.verbose = verbose
def validate(data): # Validate that mandatory input parameters were found paramList = [ 'instancesDirectory', 'fileNamePrefix', 'fileNameExtension', 'numInstances', 'numCPUs', 'minNumCoresPerCPU', 'maxNumCoresPerCPU', 'minCapacityPerCore', 'maxCapacityPerCore', 'numTasks', 'minNumThreadsPerTask', 'maxNumThreadsPerTask', 'minResourcesPerThread', 'maxResourcesPerThread' ] for paramName in paramList: if paramName not in data.__dict__: raise AMMMException( 'Parameter(%s) has not been not specified in Configuration' % str(paramName)) instancesDirectory = data.instancesDirectory if len(instancesDirectory) == 0: raise AMMMException('Value for instancesDirectory is empty') fileNamePrefix = data.fileNamePrefix if len(fileNamePrefix) == 0: raise AMMMException('Value for fileNamePrefix is empty') fileNameExtension = data.fileNameExtension if len(fileNameExtension) == 0: raise AMMMException('Value for fileNameExtension is empty') numInstances = data.numInstances if not isinstance(numInstances, int) or (numInstances <= 0): raise AMMMException( 'numInstances(%s) has to be a positive integer value.' % str(numInstances)) numCPUs = data.numCPUs if not isinstance(numCPUs, int) or (numCPUs <= 0): raise AMMMException( 'numCPUs(%s) has to be a positive integer value.' % str(numCPUs)) minNumCoresPerCPU = data.minNumCoresPerCPU if not isinstance(minNumCoresPerCPU, int) or (minNumCoresPerCPU <= 0): raise AMMMException( 'minNumCoresPerCPU(%s) has to be a positive integer value.' % str(minNumCoresPerCPU)) maxNumCoresPerCPU = data.maxNumCoresPerCPU if not isinstance(maxNumCoresPerCPU, int) or (maxNumCoresPerCPU <= 0): raise AMMMException( 'maxNumCoresPerCPU(%s) has to be a positive integer value.' % str(maxNumCoresPerCPU)) if maxNumCoresPerCPU < minNumCoresPerCPU: raise AMMMException( 'maxNumCoresPerCPU(%s) has to be >= minNumCoresPerCPU(%s).' % (str(maxNumCoresPerCPU), str(minNumCoresPerCPU))) minCapacityPerCore = data.minCapacityPerCore if not isinstance(minCapacityPerCore, (int, float)) or (minCapacityPerCore <= 0): raise AMMMException( 'minCapacityPerCore(%s) has to be a positive float value.' % str(minCapacityPerCore)) maxCapacityPerCore = data.maxCapacityPerCore if not isinstance(maxCapacityPerCore, (int, float)) or (maxCapacityPerCore <= 0): raise AMMMException( 'maxCapacityPerCore(%s) has to be a positive float value.' % str(maxCapacityPerCore)) if maxCapacityPerCore < minCapacityPerCore: raise AMMMException( 'maxCapacityPerCore(%s) has to be >= minCapacityPerCore(%s).' % (str(maxCapacityPerCore), str(minCapacityPerCore))) numTasks = data.numTasks if not isinstance(numTasks, int) or (numTasks <= 0): raise AMMMException( 'numTasks(%s) has to be a positive integer value.' % str(numTasks)) minNumThreadsPerTask = data.minNumThreadsPerTask if not isinstance(minNumThreadsPerTask, int) or (minNumThreadsPerTask <= 0): raise AMMMException( 'minNumThreadsPerTask(%s) has to be a positive integer value.' % str(minNumThreadsPerTask)) maxNumThreadsPerTask = data.maxNumThreadsPerTask if not isinstance(maxNumThreadsPerTask, int) or (maxNumThreadsPerTask <= 0): raise AMMMException( 'maxNumThreadsPerTask(%s) has to be a positive integer value.' % str(maxNumThreadsPerTask)) if maxNumThreadsPerTask < minNumThreadsPerTask: raise AMMMException( 'maxNumThreadsPerTask(%s) has to be >= minNumThreadsPerTask(%s).' % (str(maxNumThreadsPerTask), str(minNumThreadsPerTask))) minResourcesPerThread = data.minResourcesPerThread if not isinstance(minResourcesPerThread, (int, float)) or (minResourcesPerThread <= 0): raise AMMMException( 'minResourcesPerThread(%s) has to be a positive float value.' % str(minResourcesPerThread)) maxResourcesPerThread = data.maxResourcesPerThread if not isinstance(maxResourcesPerThread, (int, float)) or (maxResourcesPerThread <= 0): raise AMMMException( 'maxResourcesPerThread(%s) has to be a positive float value.' % str(maxResourcesPerThread)) if maxResourcesPerThread < minResourcesPerThread: raise AMMMException( 'maxResourcesPerThread(%s) has to be >= minResourcesPerThread(%s).' % (str(maxResourcesPerThread), str(minResourcesPerThread)))
def _openFile(filePath): if not os.path.exists(filePath): raise AMMMException('The file (%s) does not exist' % filePath) return open(filePath, 'r')
def validate(data): # Validate that mandatory input parameters were found for paramName in ['inputDataFile', 'solutionFile', 'solver']: if paramName not in data.__dict__: raise AMMMException( 'Parameter/Set(%s) not contained in Configuration' % str(paramName)) # Validate input data file inputDataFile = data.inputDataFile if len(inputDataFile) == 0: raise AMMMException('Value for inputDataFile is empty') if not os.path.exists(inputDataFile): raise AMMMException('inputDataFile(%s) does not exist' % inputDataFile) # Validate solution file solutionFile = data.solutionFile if len(solutionFile) == 0: raise AMMMException('Value for solutionFile is empty') # Validate verbose verbose = False if 'verbose' in data.__dict__: verbose = data.verbose if not isinstance(verbose, bool) or (verbose not in [True, False]): raise AMMMException('verbose(%s) has to be a boolean value.' % str(verbose)) else: data.verbose = verbose # Validate solver and per-solver parameters solver = data.solver if solver == 'Greedy' or solver == 'Random': # Validate that mandatory input parameters for Greedy solver were found pass elif solver == 'GRASP': # Validate that mandatory input parameters for GRASP solver were found for paramName in ['maxExecTime', 'alpha']: if not paramName in data.__dict__: raise AMMMException( 'Parameter/Set(%s) not contained in Configuration. Required by GRASP solver.' % str(paramName)) # Validate maxExecTime maxExecTime = data.maxExecTime if not isinstance(maxExecTime, (int, float)) or (maxExecTime <= 0): raise AMMMException( 'maxExecTime(%s) has to be a positive real value.' % str(maxExecTime)) # Validate alpha alpha = data.alpha if not isinstance(alpha, (int, float)) or (alpha < 0) or (alpha > 1): raise AMMMException( 'alpha(%s) has to be a real value in range [0, 1].' % str(alpha)) elif solver == 'BRKGA': # Validate that mandatory input parameters for GRASP solver were found for paramName in [ 'maxExecTime', 'eliteProp', 'mutantProp', 'inheritanceProb', 'IndividualsMultiplier' ]: if not paramName in data.__dict__: raise AMMMException( 'Parameter/Set(%s) not contained in Configuration. Required by BRKGA solver.' % str(paramName)) # Validate maxExecTime maxExecTime = data.maxExecTime if not isinstance(maxExecTime, (int, float)) or (maxExecTime <= 0): raise AMMMException( 'maxExecTime(%s) has to be a positive real value.' % str(maxExecTime)) # Validate eliteProp eliteProp = data.eliteProp if not isinstance( eliteProp, (int, float)) or (eliteProp < 0) or (eliteProp > 1): raise AMMMException( 'eliteProp(%s) has to be a real value in range [0, 1].' % str(eliteProp)) # Validate mutantProp mutantProp = data.mutantProp if not isinstance( mutantProp, (int, float)) or (mutantProp < 0) or (mutantProp > 1): raise AMMMException( 'mutantProp(%s) has to be a real value in range [0, 1].' % str(mutantProp)) # Validate inheritanceProb inheritanceProb = data.inheritanceProb if not isinstance(inheritanceProb, (int, float)) or (inheritanceProb < 0) or (inheritanceProb > 1): raise AMMMException( 'inheritanceProb(%s) has to be a real value in range [0, 1].' % str(inheritanceProb)) # Validate IndividualsMultiplier IndividualsMultiplier = data.IndividualsMultiplier if not isinstance(IndividualsMultiplier, (int, float)) or (IndividualsMultiplier <= 0): raise AMMMException( 'IndividualsMultiplier(%s) has to be a positive real value.' % str(IndividualsMultiplier)) else: raise AMMMException( 'Unsupported solver specified(%s) in Configuration.' % str(solver)) if data.localSearch: # Validate that mandatory input parameters for local search were found for paramName in ['neighborhoodStrategy', 'policy']: if paramName not in data.__dict__: raise AMMMException( 'Parameter/Set(%s) not contained in Configuration. Required by Local Search.' % str(paramName)) # Validate neighborhoodStrategy neighborhoodStrategy = data.neighborhoodStrategy if neighborhoodStrategy not in ['TaskExchange', 'Reassignment']: raise AMMMException( 'neighborhoodStrategy(%s) has to be one of [Reassignment, Exchange].' % str(neighborhoodStrategy)) # Validate policy policy = data.policy if policy not in ['FirstImprovement', 'BestImprovement']: raise AMMMException( 'policy(%s) has to be one of [BestImprovement, FirstImprovement].' % str(policy))
def generate(self): instancesDirectory = self.config.instancesDirectory fileNamePrefix = self.config.fileNamePrefix fileNameExtension = self.config.fileNameExtension numInstances = self.config.numInstances numCPUs = self.config.numCPUs minNumCoresPerCPU = self.config.minNumCoresPerCPU maxNumCoresPerCPU = self.config.maxNumCoresPerCPU minCapacityPerCore = self.config.minCapacityPerCore maxCapacityPerCore = self.config.maxCapacityPerCore numTasks = self.config.numTasks minNumThreadsPerTask = self.config.minNumThreadsPerTask maxNumThreadsPerTask = self.config.maxNumThreadsPerTask minResourcesPerThread = self.config.minResourcesPerThread maxResourcesPerThread = self.config.maxResourcesPerThread if not os.path.isdir(instancesDirectory): raise AMMMException('Directory(%s) does not exist' % instancesDirectory) for i in range(numInstances): instancePath = os.path.join( instancesDirectory, '%s_%d.%s' % (fileNamePrefix, i, fileNameExtension)) fInstance = open(instancePath, 'w') numCores = 0 firstCoreIdPerCPU = [] numCoresPerCPU = [] coreCapacityPerCPU = [] for c in range(numCPUs): numCPUCores = random.randint(minNumCoresPerCPU, maxNumCoresPerCPU) coreCapacity = random.uniform(minCapacityPerCore, maxCapacityPerCore) firstCoreId = numCores firstCoreIdPerCPU.append(firstCoreId) numCoresPerCPU.append(numCPUCores) coreCapacityPerCPU.append(coreCapacity) numCores += numCPUCores numThreads = 0 firstThreadIdPerTask = [] numThreadsPerTask = [] resourcesPerThread = [] for t in range(numTasks): numTaskThreads = random.randint(minNumThreadsPerTask, maxNumThreadsPerTask) firstThreadId = numThreads firstThreadIdPerTask.append(firstThreadId) numThreadsPerTask.append(numTaskThreads) for h in range(numTaskThreads): resources = random.uniform(minResourcesPerThread, maxResourcesPerThread) resourcesPerThread.append(resources) numThreads += numTaskThreads fInstance.write('nTasks=%d;\n' % numTasks) fInstance.write('nThreads=%d;\n' % numThreads) fInstance.write('nCPUs=%d;\n' % numCPUs) fInstance.write('nCores=%d;\n' % numCores) # translate vector of floats into vector of strings and concatenate that strings separating them by a single space character fInstance.write('rh=[%s];\n' % (' '.join(map(str, resourcesPerThread)))) fInstance.write('rc=[%s];\n' % (' '.join(map(str, coreCapacityPerCPU)))) fInstance.write('CK=[\n') for c in range(numCPUs): cores = [ 0 ] * numCores # create a vector of 0's with numCores elements firstCoreId = firstCoreIdPerCPU[c] numCPUCores = numCoresPerCPU[c] # fill appropriate positions with 1's for k in range(firstCoreId, firstCoreId + numCPUCores): cores[k] = 1 # translate vector of integers into vector of strings and concatenate that strings separating them by a single space character fInstance.write('\t[%s]\n' % (' '.join(map(str, cores)))) fInstance.write('];\n') fInstance.write('TH=[\n') for t in range(numTasks): threads = [ 0 ] * numThreads # create a vector of 0's with numThreads elements firstThreadId = firstThreadIdPerTask[t] numTaskThreads = numThreadsPerTask[t] # fill appropriate positions with 1's for h in range(firstThreadId, firstThreadId + numTaskThreads): threads[h] = 1 # translate vector of integers into vector of strings and concatenate that strings separating them by a single space character fInstance.write('\t[%s]\n' % (' '.join(map(str, threads)))) fInstance.write('];\n') fInstance.close()
def validate(data): # Validate that all input parameters were found for paramName in [ 'nLocations', 'nCities', 'nTypes', 'p', 'posCities', 'posLocations', 'd_city', 'cap', 'cost', 'd_center' ]: if paramName not in data.__dict__: raise AMMMException( 'Parameter/Set(%s) not contained in Input Data' % str(paramName)) # Validate nLocations nLocations = data.nLocations if not isinstance(nLocations, int) or (nLocations <= 0): raise AMMMException( 'nLocations(%s) has to be a positive integer value.' % str(nLocations)) # Validate nCities nCities = data.nCities if not isinstance(nCities, int) or (nCities <= 0): raise AMMMException( 'nCities(%s) has to be a positive integer value.' % str(nCities)) # Validate nTypes nTypes = data.nTypes if not isinstance(nTypes, int) or (nTypes <= 0): raise AMMMException( 'nTypes(%s) has to be a positive integer value.' % str(nTypes)) # Validate p data.p = list(data.p) p = data.p if len(p) != nCities: raise AMMMException( 'Size of p(%d) does not match with value of nCities(%d).' % (len(p), nCities)) for value in p: if not isinstance(value, (int, float)) or (value < 0): raise AMMMException( 'Invalid parameter value(%s) in p. Should be a float greater or equal than zero.' % str(value)) # Validate posCities data.posCities = list(data.posCities) for i, v in enumerate(data.posCities): data.posCities[i] = list(data.posCities[i]) posCities = data.posCities if len(posCities) != nCities: raise AMMMException( 'Size of posCities(%d) does not match with value of nCities(%d).' % (len(p), nCities)) for value in posCities: for value2 in value: if not isinstance(value2, (int, float)) or (value2 < 0): raise AMMMException( 'Invalid parameter value(%s) in posCities. Should be a float greater or equal than zero.' % str(value2)) # Validate posLocations data.posLocations = list(data.posLocations) for i, v in enumerate(data.posLocations): data.posLocations[i] = list(data.posLocations[i]) posLocations = data.posLocations if len(posLocations) != nLocations: raise AMMMException( 'Size of posLocations(%d) does not match with value of nLocations(%d).' % (len(p), nLocations)) for value in posLocations: for value2 in value: if not isinstance(value2, (int, float)) or (value2 < 0): raise AMMMException( 'Invalid parameter value(%s) in posLocations. Should be a float greater or equal than zero.' % str(value)) # Validate d_city data.d_city = list(data.d_city) d_city = data.d_city if len(d_city) != nTypes: raise AMMMException( 'Size of d_city(%d) does not match with value of nTypes(%d).' % (len(d_city), nTypes)) for value in d_city: if not isinstance(value, (int, float)) or (value < 0): raise AMMMException( 'Invalid parameter value(%s) in d_city. Should be a float greater or equal than zero.' % str(value)) # Validate cap data.cap = list(data.cap) cap = data.cap if len(cap) != nTypes: raise AMMMException( 'Size of cap(%d) does not match with value of nTypes(%d).' % (len(cap), nTypes)) for value in cap: if not isinstance(value, (int, float)) or (value < 0): raise AMMMException( 'Invalid parameter value(%s) in cap. Should be a float greater or equal than zero.' % str(value)) # Validate cost data.cost = list(data.cost) cost = data.cost if len(cost) != nTypes: raise AMMMException( 'Size of cost(%d) does not match with value of nTypes(%d).' % (len(cost), nTypes)) for value in cost: if not isinstance(value, (int, float)) or (value < 0): raise AMMMException( 'Invalid parameter value(%s) in cost. Should be a float greater or equal than zero.' % str(value)) # Validate d_center d_center = data.d_center if not isinstance(d_center, (int, float)) or (d_center < 0): raise AMMMException( 'Invalid parameter value(%s) in d_center. Should be a float greater or equal than zero.' % str(d_center))
def setIndividual(self, individual, idx): if 0 > idx >= self.config.numIndividuals: raise AMMMException( "ERROR: trying to set an individual in index: %s" % idx) self.currentGeneration[idx] = individual
def generate(self): # Read ./config/config.dat with tune parameters instancesDirectory = self.config.instancesDirectory fileNamePrefix = self.config.fileNamePrefix fileNameExtension = self.config.fileNameExtension numInstances = self.config.numInstances nLocations = self.config.nLocations nCities = self.config.nCities nTypes = self.config.nTypes min_d_city = self.config.min_d_city max_d_city = self.config.max_d_city min_cap = self.config.min_cap max_cap = self.config.max_cap min_cost = self.config.min_cost max_cost = self.config.max_cost min_pos = 0 max_pos = (nLocations + nCities) // 4 if not os.path.isdir(instancesDirectory): raise AMMMException('Directory(%s) does not exist' % instancesDirectory) for i in range(numInstances): instancePath = os.path.join( instancesDirectory, '%s_%d.%s' % (fileNamePrefix, i, fileNameExtension)) fInstance = open(instancePath, 'w') p = [0] * nCities for c in range(nCities): p[c] = random.randint(min_cap, max_cap) posCities = [''] * nCities for idy, x in enumerate(posCities): newValue = self.create_locations(min_pos, max_pos, posCities) posCities[idy] = newValue posLocations = [''] * nLocations for idx, x in enumerate(posLocations): newValue = self.create_locations(min_pos, max_pos, posLocations) posLocations[idx] = newValue d_city = [0] * nTypes cap = [0] * nTypes cost = [0] * nTypes maxPopulationCity = max(p) min_population = min(p) avg_population = sum(p) // len(p) total_population = sum(p) avg_population_per_location = sum(p) // nLocations for t in range(nTypes): d_city[t] = random.randint(min_d_city, max_d_city) cap[t] = random.randint(avg_population * (t + 4), maxPopulationCity * (t + 6)) cost[t] = random.randint(min_cost, max_cost) # d_center = random.uniform(max_pos // 4, max_pos // 3) d_center = self.mean_distance(posLocations) # Order arrays in order to get type with sense # The more cost, the better capacity and working distance d_city.sort() cap.sort() cost.sort() fInstance.write('nLocations = %d;\n' % nLocations) fInstance.write('nCities = %d;\n' % nCities) fInstance.write('nTypes = %d;\n' % nTypes) fInstance.write('\n') # translate vector of integers into vector of strings and # concatenate that strings separating them by a single space character # in order to keep the data file characteristics fInstance.write('p = [%s];\n' % (' '.join(map(str, p)))) fInstance.write('posCities = [%s];\n' % (' '.join(map(str, posCities)))) fInstance.write('posLocations = [%s];\n' % (' '.join(map(str, posLocations)))) fInstance.write('\n') fInstance.write('d_city = [%s];\n' % (' '.join(map(str, d_city)))) fInstance.write('cap = [%s];\n' % (' '.join(map(str, cap)))) fInstance.write('cost = [%s];\n' % (' '.join(map(str, cost)))) fInstance.write('\n') fInstance.write('d_center = %s;\n' % "{:.1f}".format(d_center)) fInstance.close()