def main(): """ plots a distribution using random_solve. The distribution gives a good indication to the statespace and its density. Increasing the amount of batteries will significantly increase runtime. """ house_path = '../../Data/wijk1_huizen.csv' battery_path = '../../Data/wijk1_batterijen.txt' battery_path = '../../Results/Battery_configurations/lucas_1137_nice_sigma10.csv' battery_path = '../../Results/Battery_configurations/BESTSCORE_SIGMA_relative.csv' houses, batteries = read_data(house_path, battery_path) wijk1 = SmartGrid(51, 51) wijk1.add_house_dictionaries(houses) wijk1.add_battery_dictionaries(batteries) for element in houses: wijk1.create_house(element['position'], element['output']) for element in batteries: wijk1.create_battery(element['position'], element['capacity']) random_solve(wijk1) print("klaar")
def main(): # Paths to the houses and batteries compositions house_path = '../../Data/wijk1_huizen.csv' # battery_path = '../../Data/wijk1_batterijen.txt' # battery_path = '../../Results/Battery_configurations/SCORE:4486_SIGMA:10.csv' battery_path = '../../Results/Battery_configurations/1137_nice_sigma10.csv' # Gets the houses and batteries houses, batteries = read_data(house_path, battery_path) # Creates and fills the smartgrid so that we can use the functionality wijk = SmartGrid(51,51) wijk.add_house_dictionaries(houses) wijk.add_battery_dictionaries(batteries) for element in houses: wijk.create_house(element['position'], element['output']) for element in batteries: wijk.create_battery(element['position'], element['capacity']) count = 0 best_score = 1000000000 # runs the Hillclimber a 100 times while count < 100: count += 1 # Gets the start position from a certain result solution_reader(wijk_brabo, "../../Results/best_brabo_solution_1337.json") # Initializes the hillclimber hillclimberke = hillclimber(wijk.house_dict_with_manhattan_distances, wijk_brabo.batteries) # Creates a list of the combs to be able to call shuffle combs = [] comb = combinations(range(150), 2) for i in comb: combs.append(i) # Keeps hillclimbing untill no better option is found (ploep = false) ploep = True while ploep: ploep = hillclimberke.run(combs) # If no hillclimber is in optimum, check if best score, if so print it. if hillclimberke.calc_cost() < best_score: with open("../../Results/best_hc_1337.json", 'w') as jsonfile: json.dump({"META": {"DATA": hillclimberke.houses, "BATTERIES": hillclimberke.batteries}}, jsonfile) with open("../../Results/best_hc_1337.csv1", "w") as f: writer = csv.writer(f) writer.writerow(["score", "configuration"]) writer.writerow([hillclimberke.calc_cost(), {"DATA": hillclimberke.houses}]) print(best_score)
def brabo_starter(): house_path = '../../Data/wijk1_huizen.csv' # battery_path = '../../Data/wijk1_batterijen.txt' # battery_path = '../../Results/Battery_configurations/SCORE:4486_SIGMA:10.csv' # battery_path = '../../Results/Battery_configurations/leuknaampjes.csv' battery_path = '../../Results/Battery_configurations/1137_nice_sigma10.csv' houses, batteries = read_data(house_path, battery_path, True) max_x = max([dic['position'][0] for dic in houses] + [dic['position'][0] for dic in batteries]) + 1 max_y = max([dic['position'][1] for dic in houses] + [dic['position'][1] for dic in batteries]) + 1 wijk1 = SmartGrid(max_x,max_y) wijk1.add_house_dictionaries(houses) wijk1.add_battery_dictionaries(batteries) houses = wijk1.house_dict_with_manhattan_distances() print(houses) root = node(batteries, houses, 5000000) start = time.time() try: root.solve() except KeyboardInterrupt: run_time = time.time() - start print(run_time) print("klaar")
def main(): """ fixed, you can now use this as both a function and as script""" house_path = '../../Data/wijk1_huizen.csv' battery_path = '../../Data/wijk1_batterijen.txt' houses, batteries = read_data(house_path, battery_path) smart_wijk = SmartGrid(51,51) smart_wijk.add_house_dictionaries(houses) smart_wijk.add_battery_dictionaries(batteries) for element in houses: smart_wijk.create_house(element['position'], element['output']) for element in batteries: smart_wijk.create_battery(element['position'], element['capacity']) solution_reader(smart_wijk, '../../Results/best_brabo_solution.csv')
def main(): """ Creates a scatterplot of the heatmap. Creates 2 subplots, one comparing the heatmaps_scores with grid_scores from simulated annealing the other comparing grid_lowerbounds with grid_scores from simulated annealing """ house_path = '../../Data/wijk1_huizen.csv' battery_path = '../../Data/wijk1_batterijen.txt' houses, unused = read_data(house_path, battery_path) # print(unused) best_score = 999999 with open( "../../Results/Battery_configurations/scatterplotdata_sigma_relative.json" ) as f: parsed_data = json.load(f) for i, batter_positions in enumerate(parsed_data['DATAMETA']['DATA']): batteries = batter_positions['battery_dict'] scatterwijk = SmartGrid(51, 51) for element in houses: scatterwijk.create_house(element['position'], element['output']) for element in batteries: scatterwijk.create_battery(element['position'], element['capacity']) # pretty sure some houses and batteries overlap each other @.@ so much to do scatterwijk.add_house_dictionaries(houses) scatterwijk.add_battery_dictionaries(batteries) scatterwijk.house_dict_with_manhattan_distances() # print(scatterwijk.house_data) scatterwijk.get_lower_bound() # print(type(scatterwijk.lower_bound)) parsed_data['DATAMETA']['DATA'][i][ 'lowerbound'] = scatterwijk.lower_bound for _ in range(10): scatterwijk.grid = random_solve(scatterwijk) if scatterwijk.grid is False: print("Skipping due to random taking too long") continue for _ in range(2): scatterwijk.house_dict_with_manhattan_distances() hillclimber = Hillclimber(scatterwijk.house_data, scatterwijk.battery_dict) while hillclimber.run(): pass for _ in range(1): siman = Simulated_annealing(hillclimber.houses, hillclimber.batteries, hillclimber.combs) siman.run() print("Simulated Annealing: {}".format(siman.calc_cost())) if (siman.calc_cost()) < best_score: best_score = siman.calc_cost() # # scatterwijk.prettify() # total_cost = scatterwijk.calc_cost() # print("Simulated Annealing: {}".format(siman.calc_cost())) print("Best score: {}".format(best_score)) # print("price of wijk random{}".format(total_cost)) # DO SIMANNEALING HERE parsed_data['DATAMETA']['DATA'][i]['siman_gridscore'] = best_score heat = [] lower = [] simanscore = [] for datapoint in parsed_data['DATAMETA']['DATA']: heat.append(int(datapoint['heatscore'])) lower.append(int(datapoint['lowerbound'])) simanscore.append( int(datapoint['siman_gridscore']) + parsed_data['DATAMETA']['battery_price']) slope, intercept, r_value, p_value, std_err = stats.linregress( heat, simanscore) print(slope, intercept, r_value, p_value, std_err) fit = np.polyfit(heat, simanscore, deg=1) parsed_data['DATAMETA']['regression'] = fit parsed_data['DATAMETA']['R2'] = r_value # print(heat, lower) regresion = [] for datapointo in heat: regresion.append(float(fit[0]) * datapointo + fit[1]) title = "correlation between heatmap and Simulated Annealing \n R^2 = " + str( r_value) + "\n sigma =" + str(parsed_data['DATAMETA']['SIGMA']) plt.figure(1) plt.subplot(121) plt.title(title) plt.plot(heat, regresion, color='red') plt.scatter(heat, simanscore, marker='+') plt.xlabel('Heatmap Score') plt.ylabel('Simulated Annealing') slope, intercept, r_value, p_value, std_err = stats.linregress( lower, simanscore) fit = np.polyfit(lower, simanscore, deg=1) regresion = [] for datapointo in lower: regresion.append(float(fit[0]) * datapointo + fit[1]) plt.subplot(122) title = "correlation between lower bound and Simulated Annealing \n R^2 = " + str( r_value) plt.title(title) plt.plot(lower, regresion, color='red') plt.scatter(lower, simanscore, marker='+') plt.xlabel('Lower Bound') plt.ylabel('Simulated Annealing') plt.show()
# battery_path = 'Data/wijk1_batterijen.txt' # battery_path = 'Results/Battery_configurations/SCORE_4486_SIGMA_10.csv' battery_path = 'Results/Battery_configurations/BESTSCORE_SIGMA_5.csv' houses, batteries = read_data(house_path, battery_path) max_x = max([dic['position'][0] for dic in houses] + [dic['position'][0] for dic in batteries]) + 1 max_y = max([dic['position'][1] for dic in houses] + [dic['position'][1] for dic in batteries]) + 1 outputs = [dic['output'] for dic in houses] wijk1 = SmartGrid(max_x, max_y) for element in houses: wijk1.create_house(element['position'], element['output']) # populate the batteries in the smart_grid for element in batteries: wijk1.create_battery(element['position'], element['capacity']) wijk1.add_house_dictionaries(houses) wijk1.add_battery_dictionaries(batteries) wijk1.prettify() # solution_reader_new(wijk1, 'Results/best_hillclimber.json')
def create_smart_grid(houses, comp): compwijk = SmartGrid(51, 51) battery_dict = [] for element in houses: compwijk.create_house(element['position'], element['output']) for i, element in enumerate(comp["batteries"]): compwijk.create_battery(comp['bat_positions'][i], element) battery_dict.append({ "position": comp["bat_positions"][i], "capacity": element }) compwijk.battery_dict = battery_dict compwijk.add_house_dictionaries(houses) compwijk.add_battery_dictionaries(battery_dict) return compwijk
def random_solve(the_grid): """ """ print('\n\n\n') print('You are now using random_solve!') # cap_limit telling the iterator to stop when battery_cap below this value # get number of batteries n_bat = len(the_grid.battery_dict) # count to keep looping through batteries, keep count to keep track of number of failures bat_pos = [dic['position'] for dic in the_grid.battery_dict] solutions_list = [] # best_score = 80000 limit = 10000 invalids = 0 i = 0 while i < limit: # Iterates through nearest houses until cap full keepcount = 0 count = 0 for house_pos in shuffle(the_grid): if keepcount is n_bat: break while not the_grid.connect(bat_pos[count], house_pos): #print("Failed to connect") count += 1 keepcount += 1 if count is n_bat: count = 0 if keepcount is n_bat: break else: #print("connected battery: {} with house {}".format(bat_pos, house_pos)) continue if the_grid.check_validity(): i += 1 # print(i) score = the_grid.calc_cost() solutions_list.append(score) # the_grid.house_dict_with_manhattan_distances() # the_grid.get_lower_bound() # print(the_grid.lower_bound) else: invalids += 1 house_path = '../../Data/wijk1_huizen.csv' battery_path = '../../Data/wijk1_batterijen.txt' battery_path = '../../Results/Battery_configurations/lucas_1137_nice_sigma10.csv' battery_path = '../../Results/Battery_configurations/BESTSCORE_SIGMA_relative.csv' houses, batteries = read_data(house_path, battery_path) the_grid = SmartGrid(51, 51) the_grid.add_house_dictionaries(houses) the_grid.add_battery_dictionaries(batteries) for element in houses: the_grid.create_house(element['position'], element['output']) for element in batteries: # print(element['capacity']) the_grid.create_battery(element['position'], int(element['capacity'])) # if score < best_score: # best_score = score # best_list = house_pos with open("../../Results/random_solutions.csv", "w") as f: writer = csv.writer(f) writer.writerow(solutions_list) # print(solutions_list) title_string = 'Random solve distribution n = ' + str( limit) + '\n' + 'Invalid solutions: ' + str(invalids) plt.hist(solutions_list, 50, facecolor='blue') plt.xlabel('Grid Score') plt.ylabel('Count') plt.title(title_string) # plt.xlim(xmin = 30000) plt.show()
def main(): """ Simulated annealing By using a solved grid simulated annealing tries to randomly make swaps. Depending on the cooling scheme used different results will follow. heatscheme: linear exponential sigmoid The Simulated_annealing object takes as input a battery dictionary and a houses dictionary (new format) The Simulated_annealing object has the method calc_cost() which returns the cost """ heatscheme = "linear" # Sets paths to house and battery compositions house_path = '../../Data/wijk1_huizen.csv' # battery_path = '../../Data/wijk1_batterijen.txt' # battery_path = '../../Results/Battery_configurations/SCORE:4486_SIGMA:10.csv' battery_path = '../../Results/Battery_configurations/lucas_1137_nice_sigma10.csv' # Reads the data and puts it in a smartgrid for functinonality houses, batteries = read_data(house_path, battery_path) wijk_brabo = SmartGrid(51,51) wijk_brabo.add_house_dictionaries(houses) wijk_brabo.add_battery_dictionaries(batteries) for element in houses: wijk_brabo.create_house(element['position'], element['output']) for element in batteries: wijk_brabo.create_battery(element['position'], element['capacity']) count = 0 best_score = 1000000000 # Runs the simulated annealing 100 times while count < 1: count += 1 # Gets the startposition from a certain result and intializes the simulated annealing # solution_reader(wijk_brabo, "../../Results/best_brabo_solution_marco.json") solution_reader(wijk_brabo, "../../Results/Do_not_write_in_this_map_results/best_brabo_solution_1337.json") siman = Simulated_annealing(wijk_brabo.house_dict_with_manhattan_distances, wijk_brabo.batteries, heatscheme) # makes a list of all possible legal and illegal swaps combs = [] comb = combinations(range(150), 2) for i in comb: combs.append(i) # print(combs) # Runs the simulated annealing untill max iterations are reached while siman.iterations < siman.maxiterations: siman.run(random.choice(combs)) # If better score is found, save it if best_score > siman.calc_cost(): best_score = siman.calc_cost() # with open("../../Results/best_siman_hc_1.json", 'w') as jsonfile: # json.dump({"META": {"DATA": siman.houses, "BATTERIES": siman.batteries}}, jsonfile) # with open("../../Results/best_siman_hc_1.csv1", "w") as f: # writer = csv.writer(f) # writer.writerow(["score", "configuration"]) # writer.writerow([siman.calc_cost(), {"DATA": siman.houses}]) print(best_score)
def main(): colorama.init() house_path = 'Data/wijk1_huizen.csv' battery_path = 'Data/wijk1_batterijen.txt' houses, batteries = read_data(house_path, battery_path) # find ranges for the grid matrix max_x = max([dic['position'][0] for dic in houses] + [dic['position'][0] for dic in batteries]) + 1 max_y = max([dic['position'][1] for dic in houses] + [dic['position'][1] for dic in batteries]) + 1 # outputs = [dic['output'] for dic in houses] # print(outputs) # plt.hist(outputs) # plt.ylabel('count') # plt.xlabel('max output') # plt.show() # creates our very own smart_grid object! yay wijk1 = SmartGrid(max_x,max_y) # Populate the houses in the smart_grid, should I make this a method? for element in houses: wijk1.create_house(element['position'], element['output']) # populate the batteries in the smart_grid # for element in batteries: # wijk1.create_battery(element['position'], element['capacity']) # adds dictionaries to the SmartGrid object wijk1.add_house_dictionaries(houses) # wijk1.add_battery_dictionaries(batteries) # pretty display # wijk1.prettify() print("The cost of this grid is: {}".format(wijk1.calc_cost())) # solution_reader(wijk1, 'Results/best_brabo_solution.csv') # wijk1.solve("simple_solve3") # wijk1.prettify() print("The cost of this grid is: {}".format(wijk1.calc_cost())) # wijk1.cap_left() # print("The remaining capacity of batteries are: {}".format(wijk1.bat_cap_left)) # heat_map(wijk1) # wijk1.house_dict_with_manhattan_distances() # wijk1.disconnect(houses[1]["position"]) # house_coordinatesx = [dic['position'][0] for dic in houses] # house_coordinatesy = [dic['position'][1] for dic in houses] # # plt.scatter(house_coordinatesx, house_coordinatesy) # plt.show() # wijk1.get_lower_bound() # print("Lower bound of grid is: {}".format(wijk1.lower_bound)) bat_comp_path = "Results/battery_compositions.json" with open(bat_comp_path, "r") as f: parsed_data = json.load(f) battery_configuration = parsed_data["ALL_CONFIGURATIONS"][3] print(battery_configuration) battery_configuration, matrices_for_vis = battery_placer(wijk1, battery_configuration) print(battery_configuration) visuale_2d(matrices_for_vis[0], matrices_for_vis[1], matrices_for_vis[2], matrices_for_vis[3],) # print(x) # battery_path = 'Results/Battery_configurations/test.csv' battery_path = 'Results/Battery_configurations/BESTSCORE_SIGMA_relative.csv' # battery_path = 'Results/Battery_configurations/lucas_1137_nice_sigma10.csv' # battery_path = 'Results/Battery_configurations/leuknaampjes.csv' houses, batteries = read_data(house_path, battery_path) for element in batteries: wijk1.create_battery(element['position'], element['capacity']) wijk1.add_battery_dictionaries(batteries) wijk1.house_dict_with_manhattan_distances() # heat_map(wijk1) wijk1.prettify() print(len(wijk1.house_data)) wijk1.get_lower_bound() print("Lower bound of grid is: {}".format(wijk1.lower_bound))