def main(path_name='./zad3/input2.txt', temp=ann.gen_temp(10, 10e-2, 0.99999), save=True, name='', display=True): sud = [[['x', True] for _ in range(9)] for _ in range(9)] read_sud(path_name, sud) if display: print_board(sud) print("\n") fill_sud(sud) if display: print_board(sud) print("\nFirst solution cost: %d\n" % calc_cost(sud)) best_sol, best_cost, energy = ann.anneal(sud, swap_digits, calc_cost, ann.acceptance_probability, temp) if display: print_board(best_sol) print("\nBest solution cost: %d\nIs sudoku solved: %s\n" % (best_cost, best_cost == 0)) plt.plot(range(len(energy)), energy) plt.xlabel('Iteration') plt.ylabel('Cost') if save: plt.savefig('./zad3/' + name + '_s_' if best_cost == 0 else '_ns' + 'e') if display: plt.show()
def sort_paths(paths, iterations=100000, reversable=True): ''' This function re-orders a set of 2D paths (polylines) to minimize the distance required to visit each path. This is useful for 2D plotting to reduce wasted movements where the instrument is not drawing. If allowed, the algorithm will also reverse some paths if doing so reduces the total distance. The code uses simulated annealing as its optimization algorithm. The number of iterations can be increased to improve the chances of finding a perfect solution. However, a perfect solution isn't necessarily required - we just want to find something good enough. With randomly generated paths, the algorithm can quickly find a solution that reduces the extra distance to ~25 percent of its original value. ''' state = Model(list(paths), reversable) max_temp = anneal.get_max_temp(state, 10000) min_temp = max_temp / 1000.0 state = anneal.anneal(state, max_temp, min_temp, iterations) for path, reverse in zip(state.paths, state.reverse): if reverse: path.reverse() return state.paths
def run(): return anneal.anneal(rosen, [-1.2, 1], schedule='cauchy', maxiter=100000, maxeval=100000, T0=10.0, feps=0, disp=True)
def main(input_data): best_solution = None for i in range(0, config.num_tries): solution = build_guess(input_data.people, input_data.groups, input_data.days) print_init_cost(solution.cost) if config.anneal: for (solution, T) in anneal(solution): print_progress(solution, T) if best_solution == None or solution.cost < best_solution.cost: best_solution = deepcopy(solution) yield best_solution, T
def run(): # start off with rows as planning units # and cols as features (maps to GIS data) thelist = [] costs_list = [] for huc in hucs: punit_data = watersheds[huc] huclist = [] for s in species: huclist.append(punit_data[s]) thelist.append(huclist) huc_cost = 0 for c in cost_fields: huc_cost += punit_data[c] costs_list.append(huc_cost) features = np.array(thelist, np.double) # then transpose so that we've got features as rows features = features.transpose() num_features, num_punits = features.shape targets = np.array(target_list, np.double) penalties = np.array(penalty_list, np.double) costs = np.array(costs_list, np.double) #np.ones( (num_punits), np.float) * 100 #print "\n--------\n".join(str(x) for x in [features, targets, penalties, costs]) #state = np.random.randint(0,2,(num_punits,)) #schedule = auto(state, features, targets, penalties, costs) #print schedule #sys.exit() for i in range(NUMREPS): #state = np.zeros( (num_punits), np.int0) state = np.random.randint(0, 2, (num_punits, )) result = anneal(state, features, targets, penalties, costs, TMAX, TMIN, NUMITER) chosen = [hucs[x] for x in np.flatnonzero(state).tolist()] chosen.sort() print chosen, result[1] for ch in chosen: hist[ch] += 1 hists = hist.keys() hists.sort() for k in hists: v = hist[k] if v > 0: print k, "*" * v, v
def test_anneal(self): """ Test that after annealing the solution has the correct number of people/groups """ # TODO: figure out how to change settings in config.py for testing purposes input_data = InputData(self.ppl_file, 5, None, 2, None) init_solution = build_guess(input_data.people, input_data.groups, input_data.days) gen = anneal(init_solution) for (solution, T) in gen: best_solution = solution print best_solution.cost self._validate_solution(input_data.people, input_data.days, input_data.num_groups, best_solution)
def test_anneal_with_head(self): """ Test that after annealing the correct people are still at the head table every day (on top of test_anneal) """ input_data = (self.tiny_people_with_head, self.tiny_tables_with_head, self.days_with_head) init_solution = build_guess(*input_data) expected_people_at_head = set(['Rosemary', 'Francine']) gen = anneal(init_solution) for (solution, T) in gen: best_solution = solution self._validate_solution(input_data, best_solution) self._validate_head_table(expected_people_at_head, best_solution) nose.tools.assert_true(best_solution.cost < 2200)
def run(): # start off with rows as planning units # and cols as features (maps to GIS data) thelist = [] costs_list = [] for huc in hucs: punit_data = watersheds[huc] huclist = [] for s in species: huclist.append(punit_data[s]) thelist.append(huclist) huc_cost = 0 for c in cost_fields: huc_cost += punit_data[c] costs_list.append(huc_cost) features = np.array(thelist, np.double) # then transpose so that we've got features as rows features = features.transpose() num_features, num_punits = features.shape targets = np.array(target_list, np.double) penalties = np.array(penalty_list, np.double) costs = np.array(costs_list, np.double) # np.ones( (num_punits), np.float) * 100 # print "\n--------\n".join(str(x) for x in [features, targets, penalties, costs]) # state = np.random.randint(0,2,(num_punits,)) # schedule = auto(state, features, targets, penalties, costs) # print schedule # sys.exit() for i in range(NUMREPS): # state = np.zeros( (num_punits), np.int0) state = np.random.randint(0, 2, (num_punits,)) result = anneal(state, features, targets, penalties, costs, TMAX, TMIN, NUMITER) chosen = [hucs[x] for x in np.flatnonzero(state).tolist()] chosen.sort() print chosen, result[1] for ch in chosen: hist[ch] += 1 hists = hist.keys() hists.sort() for k in hists: v = hist[k] if v > 0: print k, "*" * v, v
def test_anneal(self): """ Test that after annealing the solution has the correct number of people/tables """ # TODO: figure out how to change settings in config.py for testing purposes input_data = (self.tiny_people, self.tiny_tables, self.days) init_solution = build_guess(*input_data) gen = anneal(init_solution) for (solution, T) in gen: best_solution = solution print best_solution.cost self._validate_solution(input_data, best_solution) # final cost should be zero, because it's possible to create perfect # seating charts from these input files nose.tools.assert_true(best_solution.cost <= 2118)
def anneal_testeiteracoes(n): global DADOS_EXECUCAO global ITERACOES DADOS_EXECUCAO = [] ITERACOES = 0 x0 = rand(1,n)[0] return anneal(rastrigin, x0, maxiter=1e4, maxeval=1e4, maxaccept=1e4, feps=-inf, lower=-5.12, upper=5.12, T0=1e5, Tf=1e-10, learn_rate=0.995, full_output=True, disp=False, schedule='boltzmann')
def anneal_teste20s(n): global DADOS_EXECUCAO global ITERACOES DADOS_EXECUCAO = [] ITERACOES = 0 x0 = rand(1,n)[0] r = anneal(rastrigin, x0, maxiter=inf, maxeval=inf, maxaccept=inf, feps=-inf, lower=-5.12, upper=5.12, T0=1e5, Tf=1e-10, learn_rate=0.995, full_output=True, disp=False, max_execution_time=20, schedule='boltzmann', ) return r
def main(n=100, x_max=300, y_max=300, gen=gen3, swap_cities=swap_cities_cons, temp=ann.gen_temp(1000, 10e-1, 0.99999), save=False, name='', display=True): cities = gen(n, x_max, y_max) first_cost = calc_path(cities) print("First cost: %d" % first_cost) gen_name = 'gen1' if gen == gen2: gen_name = 'gen2' elif gen == gen3: gen_name = 'gen3' name += str(x_max) + 'x' + str(y_max) + '_n' + str( n) + '_' + gen_name + '_' draw_path(cities, save, name + 'b', display) best_sol, best_cost, energy = ann.anneal(cities, swap_cities, first_cost, ann.acceptance_probability, temp) draw_path(best_sol, save, name + 'a', display) print("Best solution cost: %d" % best_cost) plt.plot(range(len(energy)), energy) plt.xlabel('Iteration') plt.ylabel('Cost') if save: plt.savefig('./zad1/' + name + 'e') if display: plt.show()
def main(n=200, d=0.5, r=2, cost=twelve_neighbours, temp=ann.gen_temp(10e4, 10e-2, 0.99996)): bitmap = (gen_board(n, int(d * (n**2))), n, r, cost) first_cost = 0 for point in bitmap[0]: first_cost += cost(bitmap[0], point[0], point[1]) print("First cost: %d" % first_cost) draw_bitmap(bitmap, save=False, display=True) best_sol, best_cost, energy = ann.anneal(bitmap, swap_points, first_cost, ann.acceptance_probability, temp) draw_bitmap(best_sol, save=False, display=True) print("Best solution cost: %d" % best_cost) plt.plot(range(len(energy)), energy) plt.xlabel('Iteration') plt.ylabel('Cost') plt.show()
total_distance = hp.getTotalDistance(listOfCities, route) # laczny dystans dla pierwszej, losowej trasy for i in range(len(listOfCities) - 1): hp.setLineBetween(listOfCities[route[i]], listOfCities[route[i + 1]]) # trasa pokazana na wykresie print('Random distance: ', "%.2f" % total_distance) # dobor parametrow poczatkowych temperature_begin = 10000000 cooling_factor = 0.99999 temperature_end = 1e-05 start_time = time.clock() # wyzarzanie best_route, iterations = an.anneal(listOfCities, route, total_distance, temperature_begin, cooling_factor, temperature_end) time = time.clock() - start_time # wyniki computed_distance = hp.getTotalDistance(listOfCities, best_route) print('Computed distance: ', "%.2f" % computed_distance) print('\tStatistics:') improvment = total_distance / computed_distance * 100 print('Improvment: ', "%.2f" % improvment, '%') hp.getTime(time) ratio = improvment / time print('%/sec', "%.2f" % ratio) print('Number of iterations: ', iterations)
parinfo[7]['limits']=[100,300] parinfo[8]['limits']=[100,300] fa = {'y':y, 'err':yerr, 'qx':X, 'qy':Y} if 0: print 'annealing' myschedule='fast' #myschedule='simple' lowerm=[1e3,-1e5,1e3, .49,.475,.49,.475,100,100] upperm=[1e5,1e5,1e5,.51,.485,.51,.485,300,300] h_args=(y,yerr,X,Y) p1,jmin=anneal(max_wrap,p0,args=h_args,\ schedule=myschedule,lower=lowerm,upper=upperm,\ maxeval=1000, maxaccept=None,dwell=200,maxiter=200,feps=1e-2,full_output = 0) else: p1 = p0 dof=len(y)-len(p1) fake_dof=len(y) chimin=(cost_func(p1,X,Y,y,yerr)**2).sum() chimin=chimin/dof if dof>0 else chimin/fake_dof ycalc=calc_struct(p1,X,Y) print 'chimin',chimin print 'p1',p1 if 1: print 'linearizing'
def annealFit(session, spinwave_domain, spinwave_range, spinwave_range_Err, size=3, k = 100, tMin = .001, tMax = 15, tFactor = .95, MCeveryTime = True, recordKeeperCallback = None): # Create fitter fitter = PM.Fitter(session, spinwave_domain, size, k, tMin, tMax, tFactor, MCeveryTime) #testFile = open("/home/tom/Desktop/annealOutput1.txt", 'w') #testFile = open("C:\\annealOutput1.txt", 'w') # Helper function for GetResult def myfunc(p, y=None, err=None, callback = None): """returns Chi Squared to be minimized.""" if callback: callback(p) #testFile.write('\np: ' + str(p)) #testFile.flush() fitter.fit_list = p model = fitter.GetResult() #print 'y:\n', y, '\n\nmodel:\n', model #for i in range(len(y)): # testFile.write(" p: p %3.5f y %3.5f model %3.5f err %3.5f"%(p,y[i],model[i],err[i]) ) result = (y-model)/err chi_sq = 0 for entry in result: #print "entry: ", entry chi_sq += math.pow(entry, 2) #print '\n\nresult:\n', result #print "\nchi_sq: " + str(chi_sq) #testFile.write("\nchi_sq: " + str(chi_sq)) #testFile.flush() return chi_sq # Function Keywords y = spinwave_range err = spinwave_range_Err p0 = fitter.fit_list #testFile.write("initial p: " + str(p0)) #_______________________ Testing _____________________________ #START = -10 #STOP = 10 #step = .01 #FILE = "C:\\CHISQ_points3.txt" ##plot #handle = open(FILE, 'w') ##handle.write("data: "+ str(y)) ##handle.flush() #for i in range((STOP-START)/step): #x = START + i*step #val = myfunc([x], y, err) #if i != 0: #handle.write("\n") #handle.write(str(x) + " " + str(val)) #handle.close() #sys.exit() #_____________________________________________________________________ result=anneal(myfunc,p0,args=(y,err, recordKeeperCallback), schedule='simple',lower=fitter.min_range_list,upper=fitter.max_range_list, maxeval=None, maxaccept=None,dwell=50, maxiter=2000, full_output=1) print "annealing result: ", result p = result[0] myfunc(p, y, err)#To propogate final value #----Now Localy optimize with mpfit to fine tune the answer ----------- def mpfitfunc(p, fjac=None, y=None, err=None, callback = None): if callback: callback(p) #testFile.write("mpfit: " + str(p)) fitter.fit_list = p model = fitter.GetResult() status = 0 print 'y:\n', y, '\n\nmodel:\n', model #print '\n\ny-model:\n', (y-model) #print '\n\nerr:\n', err result = (y-model)/err print '\n\nresult:\n', result return [status, result] fa = {'y':y, 'err':err, 'callback':recordKeeperCallback} # Set parinfo with the limits and such. Probably don't need parbase={'value':0., 'limited':[0,0], 'limits':[0.,0.]} parinfo=[] p0 = fitter.fit_list for i in range(len(p0)): parinfo.append(copy.deepcopy(parbase)) for i in range(len(p0)): parinfo[i]['value']=p0[i] if(fitter.min_range_list[i] != np.NINF): parinfo[i]['limits'][0]=fitter.min_range_list[i] parinfo[i]['limited'][0] = 1 else: parinfo[i]['limited'][0] = 0 if fitter.max_range_list[i] != np.PINF: parinfo[i]['limits'][1] = fitter.max_range_list[i] parinfo[i]['limited'][1] = 1 else: parinfo[i]['limited'][1] = 0 # Run mpfit on fitlist with all the jazz. print "params: ", p0 print "parinfo: ", parinfo m = mpfit(mpfitfunc, p0, parinfo=parinfo, functkw = fa) #testFile.write("\nresult: " + str(result)) #testFile.write("\nm: " + str(m)) #testFile.close() return (m.status, m.params, m.perror)
best = [] years = data.groupby('Year') for year in years: weeks = year[1].groupby('Week') if year[0] > 2014: for week in weeks: buffExpected, buffActual = [], [] # time.append(year[0] + (float(week[0]) / 18)) # runs anneal X times per week and collects the best runs for i in range(10): time.append(year[0] + (float(week[0]) / 18)) print time[-1] # run anneal ans = anneal(week[1], 5000, 'FFPG') print ans # save the results of the run # buffExpected.append(ans[8]) # buffActual.append(ans[9]) expected.append(ans[8]) actual.append(ans[9]) # save the best run of the group # bestExpected = 0 # for i in buffExpected: # if i > bestExpected: # bestExpected = i # idx = buffExpected.index(bestExpected) # expected.append(buffExpected[idx])
import pandas as pd import numpy as np import os import random as r from anneal import anneal import time data = pd.read_csv(os.getcwd() + '/2015week3guru.csv',sep=';') tests = [] for i in range(100): res = anneal(data, 100) for i in range(8): res[i] = data.loc[res[i]]['Name'] tests.append(res) data = pd.DataFrame(tests) data = data.sort([8],ascending=False) timestamp = int(time.time()) data.to_csv(os.getcwd() + '/test%d.csv' %timestamp)
def mix(input_path,target_path,output_path,algorithm='sort',animate=False, \ anneal_options=None,animate_options=None,verbose=True): if animate_options is None: animate_options = {} for option in animate_options: if option in ['fps', 'n_frames', 'start_duration', 'end_duration']: if animate_options[option] <= 0: raise ValueError('%s must be positive' % option) if 'n_frames' in animate_options and animate_options['n_frames'] < 0: raise ValueError('n_frames must be non-negative') if anneal_options is None: anneal_options = {} if 'n_steps' in anneal_options and 'stop_limit' in anneal_options: raise ValueError( 'At most one of n_steps and stop_limit can be specified.') input_img = Image.open(input_path).convert(mode='RGB') target_img = Image.open(target_path).convert(mode='RGB') new_input_dims = adaptive_resize(input_img.size[0],input_img.size[1], \ target_img.size[0]*target_img.size[1]) input_img = input_img.resize(new_input_dims) input_img = np.array(input_img) target_img = np.array(target_img) base_input_img = np.copy(input_img) input_img = np.reshape(input_img, target_img.shape) start_time = time.time() if algorithm.lower() == 'sort': output_img = pixel_sort(input_img, target_img) if verbose: print('Elapsed time: %.2fs' % (time.time() - start_time)) start_time = time.time() elif algorithm.lower() == 'anneal': output_img = anneal(input_img, target_img, verbose, **anneal_options) if verbose: print('Elapsed time: %.2fs' % (time.time() - start_time)) start_time = time.time() elif algorithm.lower() == 'hybrid': sorted_img = pixel_sort(input_img, target_img, verbose) if verbose: print('Elapsed time: %.2fs' % (time.time() - start_time)) start_time = time.time() output_img = anneal(sorted_img, target_img, verbose, **anneal_options) if verbose: print('Elapsed time: %.2fs' % (time.time() - start_time)) start_time = time.time() else: raise ValueError('Invalid algorithm type: %s' % algorithm) if output_path.endswith('.gif') or animate: frames = generate_frames(base_input_img, output_img, verbose, **animate_options) if verbose: print('Elapsed time: %.2fs' % (time.time() - start_time)) print('Saving frames to %s' % output_path) imageio.mimsave(output_path,frames,duration=1/animate_options['fps'] \ if 'fps' in animate_options else 1/30) else: if verbose: print('Saving image to %s' % output_path) Image.fromarray(output_img).save(output_path)
import sys import marisa_trie from anneal import anneal if __name__ == '__main__': text = sys.argv[1] segs = sys.argv[2] trie = marisa_trie.Trie() trie.load('dict.marisa') anneal(text, segs, 100, 1.1, trie)
import anneal import inputData if __name__ == '__main__': inputData.inputData() totalDistanceAnneal, pathAnneal = anneal.anneal() #print("Stimulated Annealing Results - ") #print("The path to be taken is:\n") print(" ".join(str(x) for x in pathAnneal)) #print("\nThe total distance covered will be: "+str(totalDistanceAnneal)+" units\n")