class TestAlgorithm(unittest.TestCase): def setUp(self): self.alg = Algorithm() self.alg._exe_relative_path = "..\\algorithms_exe\\1.exe" self.alg.config_file = "..\\algorithms_exe\\config.json" @patch("subprocess.Popen") @patch("time.time") def test_run(self, no_time, no_popen): result_file_name = "..\\algorithms_exe\\res.json" file_test_func = "\\examples_tf\\func5.json" no_popen.return_value = None no_time.return_value = None path = self.alg.run(result_file_name, file_test_func) args = list(no_popen.call_args_list[0])[0][0] assert args[0].find(self.alg._exe_relative_path) != -1 assert args[1] == "" assert args[2].find(self.alg.config_file) != -1 assert args[3].find(file_test_func) != -1 assert args[-1] == path def test_run_negative(self): self.alg._process = 1 path = self.alg.run("", "") assert path == ""
def calculate_action_incremental(self, action="insert_edge", attempt=2): calculate = Algorithm() calculate.set_graph(self.graph) if not self.check_action_exist(action): self.graph.action_incremental(action, set_action_to_graph=True) else: action_incremental = self.import_action_incremental(action) self.use_action_incremental(action_incremental) list_algorithms = ['dijkstra-apsp'] for algorithm_name in list_algorithms: results = [] calculate.attempt = attempt calculate.attempt = 1 times = calculate.run_algorithm(algorithm_name) for time_insta in times: results.append({ "algorithm": algorithm_name, "time": time_insta, "nodes": len(calculate.graph.nodes), "edges": len(calculate.graph.source), "density": self.density, "type": action }) self.export_results(results, algorithm_name, action)
def main(): startTime = time.time() parser = argparse.ArgumentParser() parser.add_argument('-a', '--algo', default=DEFAULT_ALGORITHM) parser.add_argument('-hb', '--isHybrid', default=DEFAULT_IS_HYBRID) parser.add_argument('-ps', '--popSize', type=int, default=GA_POP_SIZE) parser.add_argument('-t', '--target', default=DEFAULT_TARGET) args = parser.parse_args() # validate input if args.algo not in ALLOWED_ALGO_NAMES: print("invalid algo!\n") exit(1) # get params algoName = args.algo isHybrid = args.isHybrid popSize = args.popSize target = args.target if algoName == 'GeneticAlgorithm': problem = GeneticEdgeColoring(target) else: problem = EdgeColoring(target) algo = Algorithm.factory(algoName=algoName, popSize=popSize, problem=problem, isHybrid=isHybrid) # declare the run parameters print('\nRun parameters:\n' f'Algorithm: {algoName}') if algoName == 'TabuSearch': print(f'is hybrid function: {isHybrid}') if algoName == 'GeneticAlgorithm': print(f'Population Size: {popSize}') # find a solution and print it solVec, numOfStates = algo.findSolution(GA_MAX_ITER) print(f'\nSolution = {problem.translateVec(solVec)}') print(f'Number of searched states: {numOfStates}\n') # print summery of run endTime = time.time() elapsedTime = endTime - startTime print(f'Total elapsed time in seconds: {elapsedTime}') print(f'This process took {elapsedTime * CLOCK_RATE} clock ticks')
def calculate_action_incremental(self, action="insert_edge", attempt=2): calculate = Algorithm() calculate.set_graph(self.graph) if not self.check_action_exist(action): return action_incremental = self.import_action_incremental(action) self.use_action_incremental(action_incremental) list_algorithms = calculate.list()['incremental_accelerate'] if self.cmd == "calculate-dist": list_algorithms = ['dijkstra-apsp'] print("******************************") print(self.cmd) print("******************************") for algorithm_name in list_algorithms: results = [] calculate.attempt = attempt if algorithm_name == 'dijkstra-apsp': calculate.attempt = 1 if action != "insert_edge": continue times = calculate.run_algorithm(algorithm_name, np.array(self.dist)) for time_insta in times: results.append({ "algorithm": algorithm_name, "time": time_insta, "nodes": len(calculate.graph.nodes), "edges": len(calculate.graph.source), "density": self.density, "type": action }) self.export_results(results, algorithm_name, action)
def __init__(self): Algorithm.__init__(self) self.name = "Kamishima"
def __init__(self, algorithm, metric): Algorithm.__init__(self) self.algorithm = algorithm self.name = algorithm.get_name() + "-" + metric.get_name() # The single metric that will be optimized to for each run of this grid search self.metric = metric
def __init__(self, algorithm): Algorithm.__init__(self) self.model = algorithm self.name = 'SDB-' + self.model.get_name()
def main(): startTime = time.time() parser = argparse.ArgumentParser() parser.add_argument('-a', '--algo', default=DEFAULT_ALGORITHM) parser.add_argument('-ps', '--popSize', type=int, default=GA_POP_SIZE) parser.add_argument('-t', '--target', type=int, default=DEFAULT_TARGET) parser.add_argument('-ts', '--tabuSize', type=int, default=MAX_TABU_SIZE) parser.add_argument('-it', '--initialTemp', type=int, default=DEFAULT_INITIAL_TEMP) parser.add_argument('-heu', '--heuristicIntensity', type=float, default=DEFAULT_HEUR_INTEN) parser.add_argument('-his', '--historyIntensity', type=float, default=DEFAULT_HIST_INTEN) parser.add_argument('-dr', '--decayRate', type=float, default=DEFAULT_DECAY_RATE) parser.add_argument('-lf', '--localPheRate', type=float, default=DEFAULT_LOCAL_PHE_RATE) args = parser.parse_args() # validate input if args.algo not in ALLOWED_ALGO_NAMES: print("invalid algo!\n") exit(1) # get params algoName = args.algo popSize = args.popSize target = args.target tabuSize = args.tabuSize initialTemp = args.initialTemp historyIntensity = args.historyIntensity heuristicIntensity = args.heuristicIntensity decayRate = args.decayRate localPheRate = args.localPheRate if algoName == 'GeneticAlgorithm': cvrpName = 'GeneticCVRP' else: cvrpName = 'CVRP' cvrp = CVRP.factory(cvrpName, target) algo = Algorithm.factory(algoName=algoName, popSize=popSize, eliteRate=GA_ELITE_RATE, problem=cvrp, mutationRate=GA_MUTATION_RATE, maxTabuSize=tabuSize, initialTemp=initialTemp, heuristicIntensity=heuristicIntensity, historyIntensity=historyIntensity, decayRate=decayRate, localPheRate=localPheRate) # declare the run parameters print('\nRun parameters:\n' f'Target: {target}\n' f'Algo: {algoName}\n' f'Pop size: {popSize}\n') if algoName == 'TabuSearchAlgorithm': print(f'Tabu size: {tabuSize}\n') # find a solution and print it solVec = algo.findSolution(GA_MAX_ITER) print(f'Solution = {cvrp.translateVec(solVec)}\n') # print summery of run endTime = time.time() elapsedTime = endTime - startTime print(f'Total elapsed time in seconds: {elapsedTime}') print(f'This process took {elapsedTime * CLOCK_RATE} clock ticks')
def run(type_incremental, num_nodes, probability_edges, num_try=30, attempt=10, saveFileExec=True, labExec=True, printer=True): ## Define params labExec = bool(labExec) saveFileExec = bool(saveFileExec) num_nodes = int(num_nodes) num_try = int(num_try) attempt = int(attempt) probability_edges = float(probability_edges) results = [] dirGraphs = get_folder("synthetics", type_incremental, num_nodes, probability_edges) dirResults = get_folder("results", type_incremental, num_nodes, probability_edges) if printer: print("=============================================") print("Num nodes: ", num_nodes) print("Probability Edge: ", probability_edges) print("Graph count: ", num_try) print("Try algorithms: ", num_try) print("Exporting graphs: ", saveFileExec) print("Exec algorithms: ", labExec) print("\n") ### Define lab for exec for i in range(num_try): print( "Loading graph [" + str(num_nodes) + ", " + str(probability_edges) + "]", i, " of ", num_try) graph = Graph.creategraph(num_nodes, probability_edges) t = time() dist_before = Dijkstra_apsp(graph) #dist_before = Dijkstpython3 lab.py decrease_edge 1000 0.5ra_apsp(graph) if probability_edges < 0.1 else Floyd_Warshall(graph) time_seconds = (time() - t) * 1000 print(time_seconds) if type_incremental == "decrease_worst_edge": graph.decrease_worst_weight() elif type_incremental == "insert_worst_edge": graph.insert_worst_edge() elif type_incremental == "decrease_edge": graph.decrease_random_weight() else: graph.insert_random_edge(weights=[1]) calculate = Algorithm(graph.export_values()) calculate.attempt = attempt ### Save graph if saveFileExec: graph_values = { "graph": graph.export_values(), "dist": export_matrix(dist_before) } filename = dirGraphs + "g_" + str(i) + ".json" with open(filename, 'w') as outfile: json.dump(graph_values, outfile) ### Exec lab and save on results[] if labExec: for algorithm_name in calculate.list()['incremental']: times = calculate.run_algorithm(algorithm_name, dist_before) for timee in times: results.append({ "algorithm": algorithm_name, "time": timee, "nodes": len(calculate.graph.nodes), "edges": len(calculate.graph.source), "density": probability_edges, "type": type_incremental }) ### Set Data Frame df = pd.DataFrame(results) filename = dirResults + "result.csv" if labExec: if printer: print("To export: ", filename) df.to_csv(filename, index=False, header=True) print("END") return {"dataframe": df, "filename": filename}
def setUp(self): self.alg = Algorithm() self.alg._exe_relative_path = "..\\algorithms_exe\\1.exe" self.alg.config_file = "..\\algorithms_exe\\config.json"
def main(): startTime = time.time() parser = argparse.ArgumentParser() # set cmd flags parser.add_argument('-p', '--problem', default=DEFAULT_PROBLEM) parser.add_argument('-ps', '--popsize', default=GA_POP_SIZE) parser.add_argument('-c', '--cross') parser.add_argument('-f', '--fitness') parser.add_argument('-m', '--mutation') parser.add_argument('-a', '--algo', default=DEFAULT_ALGORITHM) parser.add_argument('-s', '--parentSelection', default=DEFAULT_PARENT_SELECTION_FUNC) parser.add_argument('-r', '--continuationRule', default=DEFAULT_CONTINUATION_RULE) parser.add_argument('-t', '--target') args = parser.parse_args() # validate input if args.problem not in ALLOWED_PROBLEM_NAMES: print("invalid problem!\n") exit(1) paramsDict, allowedDict = getParamsDict(args.problem) if args.fitness: if args.fitness in allowedDict[FITNESS]: paramsDict[FITNESS] = args.fitness else: print("Input Error: This problem can't work with this fitness function") exit(1) if args.cross: if args.cross in allowedDict[CROSSOVER]: paramsDict[CROSSOVER] = args.cross else: print("Input Error: This problem can't work with this crossover") exit(1) if args.mutation: if args.mutation in allowedDict[MUTATION]: paramsDict[MUTATION] = args.mutation else: print("Input Error: This problem can't work with this mutation") exit(1) if args.target: validateTarget(args.problem, args.target) paramsDict[TARGET] = args.target if args.algo not in ALLOWED_ALGO_NAMES: print("invalid algo!\n") return if args.parentSelection not in ALLOWED_PARENT_SELECTION_FUNC_NAMES: print("invalid parent selection function!\n") return if args.continuationRule not in ALLOWED_CONTINUATION_RULE_NAMES: print("invalid continuation rule function!\n") return if type(args.popsize) != int and not args.popsize.isdigit(): print('Invalid population size, must be an int') return algoName = args.algo fitnessFuncName = paramsDict[FITNESS] parentSelectionName = args.parentSelection continuationRuleName = args.continuationRule target = paramsDict[TARGET] # init objects based on input fitnessFunction = FitnessFunction.factory(fitnessFuncName).calculate problem = Problem.factory(problemName=args.problem, fitnessFunction=fitnessFunction, target=target) crossoverFunction = Crossover.factory(paramsDict[CROSSOVER]).makeNewChild parentSelectionFunction = ParentSelection.factory(parentSelectionName).getCandidates continuationRuleFunction = ContinuationRule.factory(continuationRuleName).getNextGenAndPotentialParents mutationFunction = Mutation.factory(paramsDict[MUTATION]).mutate # init algo algo = Algorithm.factory(algoName=algoName, popSize=int(args.popsize), eliteRate=GA_ELITE_RATE, crossoverFunc=crossoverFunction, mutationRate=GA_MUTATION_RATE, mutationFunction=mutationFunction, parentSelectionFunction=parentSelectionFunction, continuationRuleFunction=continuationRuleFunction, problem=problem ) # declare the run parameters print( '\nRun parameters:\n' f'Problem: {args.problem}\n' f'Target: {target}\n' f'Algo: {args.algo}\n' f'Pop size: {args.popsize}\n' ) if algoName == 'GeneticAlgorithm': print( f'Fitness: {fitnessFuncName}\n' f'Parent Selection: {parentSelectionName}\n' f'Crossover: {paramsDict[CROSSOVER]}\n' f'ContinuationRule: {continuationRuleName}\n' f'Mutation: {paramsDict[MUTATION]}\n' ) # find a solution and print it solVec = algo.findSolution(GA_MAX_ITER) print(f'Solution = {problem.translateVec(solVec)}\n') # print summery of run endTime = time.time() elapsedTime = endTime - startTime print(f'Total elapsed time in seconds: {elapsedTime}') print(f'This process took {elapsedTime * CLOCK_RATE} clock ticks')
def __init__(self): Algorithm.__init__(self) self.name = "Calders"
def __init__(self): Algorithm.__init__(self) self.name = "SDB-AdaBoost"
def __init__(self): Algorithm.__init__(self)
type_incremental = "insert_edge" if len(sys.argv) >= 2: type_incremental = sys.argv[1] files = [] if len(sys.argv) < 3: for f in os.listdir(basePath): if os.path.isfile(os.path.join(basePath, f)) and f.endswith(".json"): files.append(f) if len(sys.argv) >= 3: filename = sys.argv[2] files.append(filename) print("Load ", len(files), "files") print("================== Init LAB =======================") for filename in files: data_import = import_file(filename) dist_before = import_matrix(data_import['dist']) calculate = Algorithm(data_import['graph']) calculate.graph.stats() calculate_and_export(calculate, type_incremental, dist_before) print("----------------------------------------")
def __init__(self): Algorithm.__init__(self) self.name = "SDBSVM"