def test_peak_hillclimb(): # check we hit the peak value (and don't iterate more than we need to) def move_operator(i): if i < 100: yield i + 1 def init_function(): return 1 num_evaluations, best_score, best = \ hillclimb.hillclimb(init_function, move_operator, objective_function, max_evaluations) assert num_evaluations <= max_evaluations assert num_evaluations == 100 assert best == 100 assert best_score == 100
def test_peak_hillclimb(): ''' check we hit the peak value (and don't iterate more than we need to) ''' def move_operator(i): if i < 100: yield i + 1 def init_function(): return 1 num_evaluations, best_score, best = hillclimb.hillclimb( init_function, move_operator, objective_function, max_evaluations) assert num_evaluations <= max_evaluations assert num_evaluations == 100 assert best == 100 assert best_score == 100
def test_simple_hillclimb(): # test whether given a really simple move # operator that just increments the number given # we always end up with with largest number # we can get after the number of evaluations # we specify def move_operator(i): yield i + 1 def init_function(): return 1 num_evaluations, best_score, best = \ hillclimb.hillclimb(init_function, move_operator, objective_function, max_evaluations) assert num_evaluations == max_evaluations assert best == max_evaluations assert best_score == max_evaluations
def test_simple_hillclimb(): ''' test whether given a really simple move operator that just increments the number given we always end up with with largest number we can get after the number of evaluations we specify ''' def move_operator(i): yield i + 1 def init_function(): return 1 num_evaluations, best_score, best = hillclimb.hillclimb( init_function, move_operator, objective_function, max_evaluations) assert num_evaluations == max_evaluations assert best == max_evaluations assert best_score == max_evaluations
from hillclimb import hillclimb from simulated_annealing import simulated_annealing from genetic import genetic_algorithm print("Daftar algoritma yang akan digunakan:\n" + \ "1. Hill Climbing\n" + \ "2. Simulated Annealing\n" + \ "3. Genetic Algorithm\n") input_algorithm = int(input("Pilih Algoritma yang diinginkan: ")) while input_algorithm < 0 and input_algorithm > 3: print("Algoritma tidak ada dalam pilihan.") input_algorithm = input("Pilih Algoritma yang diinginkan: ") input_file = input("Masukkan nama file input: ") if input_algorithm == 1: hillclimb(input_file) elif input_algorithm == 2: simulated_annealing(input_file) elif input_algorithm == 3: init_pop = input( "Masukkan jumlah Initial Population. Harus power of 2 (4096): ") epoch_length = input("Masukkan jumlah Epoch Length (1000): ") if init_pop == "" and epoch_length == "": genetic_algorithm(input_file) else: if init_pop == "": genetic_algorithm(input_file, int(epoch_length)) elif epoch_length == "": genetic_algorithm(input_file, int(init_pop)) else: genetic_algorithm(input_file, int(init_pop), int(epoch_length))
def main(): """ Gets sequence and molecule object from load functions. Then waits for command from user. Executes specified command if valid. """ sequence = load_sequence() molecule = load_molecuel(sequence) directions = ["Left", "Right"] while True: # prompt user for command command = input("command: ").split() if not command: continue elif command[0] == "quit": break elif command[0] == "spiral": spiralfold(molecule) print(f"stability: {molecule.stability()}") elif command[0] == "stoch_climb": iterations = '' save_data = False # check for errors and convert variables to proper format try: iterations = int(command[1]) except ValueError: print(f"Error: {command[1]} is not a number") continue except IndexError: print("Usage: stoch_climb iterations (save)") continue # check if the save command was given, if so save data try: if command[2] == "save": save_data = True else: print(f"Error: {command[2]} is not accepted." \ "\nUsage: stoch_climb iterations (save)") continue except IndexError: pass hillclimb(molecule, iterations, save_data) molecule.draw() elif command[0] == "anneal": reheat_times = '' reheat_temp = '' save_data = False # check for errors and convert variables to proper format try: reheat_temp = int(command[2]) except ValueError: print(f"Error: {command[2]} is not a number") continue except IndexError: print("Usage: anneal reheat_times reheat_temp (save)") continue try: reheat_times = int(command[1]) except ValueError: print(f"Error: {command[1]} is not a number") continue # check if the save command was given, if so let anneal save data try: if command[3] == "save": save_data = True else: print(f"Error: {command[3]} is not accepted." \ "\nUsage: anneal reheat_times reheat_temp (save)") continue except IndexError: pass molecule = anneal(molecule, reheat_times, reheat_temp, save_data) molecule.draw() elif command[0] == "population": popsize = '' gens = '' save_data = False # check for errors and convert variables to proper format try: gens = int(command[2]) except ValueError: print(f"Error: {command[2]} is not a number") continue except IndexError: print("Usage: population popsize generations (save)") continue try: popsize = int(command[1]) except ValueError: print(f"Error: {command[1]} is not a number") continue # check if the save command was given, if so let pop save data try: if command[3] == "save": save_data = True else: print(f"Error: {command[3]} is not accepted." "Usage: population popsize generations (save)") except IndexError: pass molecule = populationbased(sequence, popsize, gens, save_data) molecule.draw() elif command[0] == "sample": iterations = '' save_data = False # check for errors and convert to convert variables to proper format try: iterations = int(command[1]) except ValueError: print(f"Error: {command[1]} is not a number") continue except IndexError: print("use: random iterations (save)") continue # check if save command was given, if so let randomsaple save data try: if command[2] == "save": save_data = True else: print(f"Error: {command[2]} is not accepted." "Usage: random iterations (save)") except IndexError: pass molecule = randomsample(molecule, iterations, save_data) molecule.draw() # plot a graph to visualize protein elif command[0] == "draw": molecule.draw() elif command[0] == "turn": # check for errors and convert to convert variables to proper format try: position = int(command[2]) - 1 except ValueError: print(f"Error: {command[2]} is not a number") continue except IndexError: print("use: turn direction number") continue direction = command[1].lower().capitalize() # turn molecule at given position towards direction 'direction' if direction in directions: if position < len(sequence) and position > -1: molecule.turn(position, direction) print(f"stability: {molecule.stability()}") print(f"valid?: {molecule.check_vadility()}") else: print("invalid number") else: print("direction can only be left or right") elif command[0] == "force_vadil": molecule.force_vadil() molecule.draw() elif command[0] == 'help': print("turn: turns the molecule (usage: turn Left 2)" \ "\nrandom: turns the molecule randomly (usage: random 10)" \ "\ndraw: draws the molecule (usage: draw)" \ "\nspiral: turns the molecule into a spiral (usage: spiral)" \ "\nstoch_climb: performs a 'stochastic hill climber " \ "algorithm' on the molecule (usage: stoch_climb iterations "\ "(save))" "\nanneal: performs the 'simulated annealing' algorithm on " \ "the molecule (usage: anneal (save))" \ "\nsample: get best out of given number of samples" \ "\npopulation: run a population based algorithm on the " \ "molecule (usage: population popsize generations (save))" \ "\nquit: quits the application") else: print("invalid command")
def populationbased(sequence, popsize, gen, save_data=False): """ Population based algorithmself. Usage: (sequence, populationsize, generationsize) """ # constant for hillclimber iterations HILLCLIMBITER = 10 # prints the current time print(datetime.datetime.now()) # Make a data holder for the write_csv data = [] # iteration and function-call counters iterations = 0 call = 0 # make the population pop = [] for i in range(popsize): molecule = Molecule(sequence, "random") pop.append([molecule, 0]) # while stopcondition is not reached (amount of generations made) while iterations < gen: # list for new population newpop = [] # get all the molecules in generation list = [list[0] for list in pop] # iterate over every molecule in generation for molecule in list: # perform stochastic hillclimber twice molecule1 = hillclimb(molecule, HILLCLIMBITER) molecule2 = hillclimb(molecule, HILLCLIMBITER) # append the created molecules to the new population newpop.append([molecule1, molecule1.stability()]) newpop.append([molecule2, molecule2.stability()]) # update function-calls call += HILLCLIMBITER * 2 + 2 # new population consists of the best half molecule created pop = newpop pop = sorted(pop, key=itemgetter(1)) pop = pop[:int(len(pop) / 2)] # save all the stabilities and average them for results datalist = [item[1] for item in pop] data.append([call, sum(datalist) / len(datalist)]) # increase the iterations iterations += 1 # print end time print(datetime.datetime.now()) # save the data in a csv if need be if save_data: header = [ 'function evaluations', 'stability', datetime.datetime.now(), f'sequence = {molecule.sequence}', f'population size = {popsize}', f'generations = {gen}' ] write_csv("population", header, data) # return the best molecule found return pop[0][0]