Skip to content

Commit

Permalink
Merge branch 'TP2' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
juaniq99 committed Apr 5, 2022
2 parents 74c6547 + 8c429a7 commit a7299c2
Show file tree
Hide file tree
Showing 20 changed files with 1,894 additions and 1 deletion.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,7 @@ dmypy.json
.pyre/

# IDE
.idea/
.idea/

#Output
*.csv
290 changes: 290 additions & 0 deletions TP2/README.md

Large diffs are not rendered by default.

Binary file added TP2/TP2-Presentación.pdf
Binary file not shown.
28 changes: 28 additions & 0 deletions TP2/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"initial_values": [[4.4793,-4.0765,-4.0765],[-4.1793,-4.9218,1.7664],[-3.9429,-0.7689,4.8830]],
"initial_results": [0,1,1],
"limit_first_generation": 10,
"population_size": 50,
"generations": 1000,
"output_path": "resources/output1",
"crossbreeding" : {
"method": "simple",
"multiple_point_n": 3
},
"mutation" : {
"method": "uniform",
"probability": 0.05,
"sigma" : 2,
"a" : 0.1
},
"selection": {
"method": "boltzmann",
"tournament_threshold": 0.8,
"truncation_k": 10,
"boltzmann_t0": 20,
"boltzmann_tc": 10,
"boltzmann_k": 0.1
}


}
1 change: 1 addition & 0 deletions TP2/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
MIN_GENERATIONS = 500
97 changes: 97 additions & 0 deletions TP2/crossbreeding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import random
from models import Crossbreeding, Individual

def simple_crossbreeding(population):
chrom_length = len(population[0].chromosome)
random.shuffle(population) #Shuffle in case it is ordered from another step and improve diversity of children
children = []
for i in range(0, len(population)-1, 2):
parent1 = population[i]
parent2 = population[i+1]
index = random.randint(1, chrom_length-1) #Between 1 and len-1 so as to not create a child equal to parent
chromosome1 = []
chromosome2 = []
for j in range(0, index):
chromosome1.append(parent1.chromosome[j])
chromosome2.append(parent2.chromosome[j])
for j in range(index, chrom_length):
chromosome1.append(parent2.chromosome[j])
chromosome2.append(parent1.chromosome[j])
children.append(Individual(chromosome1))
children.append(Individual(chromosome2))
return children


def multiple_crossbreeding(population):
chrom_length = len(population[0].chromosome)
random.shuffle(population) #Shuffle in case it is ordered from another step and imrpove diversity of children
children = []

points_number = Crossbreeding.points_number
try:
indexes = random.sample(range(0, chrom_length-1), points_number) #Here between 0 and len-1 because there are more points afterwards so the children wont equal parent
except ValueError:
print('Number of points exceed chromosome length for multiple point crossbreeding')
exit(-1)

switched = False
for i in range(0, len(population)-1, 2):
parent1 = population[i]
parent2 = population[i+1]
chromosome1 = []
chromosome2 = []
for j in range(0, chrom_length):
if j in indexes:
switched = not switched
if not switched:
chromosome1.append(parent1.chromosome[j])
chromosome2.append(parent2.chromosome[j])
else:
chromosome1.append(parent2.chromosome[j])
chromosome2.append(parent1.chromosome[j])
children.append(Individual(chromosome1))
children.append(Individual(chromosome2))
return children


def uniform_crossbreeding(population):
chrom_length = len(population[0].chromosome)
random.shuffle(population) #Shuffle in case it is ordered from another step and imrpove diversity of children
children = []
for i in range(0, len(population)-1, 2):
parent1 = population[i]
parent2 = population[i+1]
chromosome1 = []
chromosome2 = []
for j in range(0, chrom_length):
if random.random() >= 0.5:
chromosome1.append(parent1.chromosome[j])
chromosome2.append(parent2.chromosome[j])
else:
chromosome1.append(parent2.chromosome[j])
chromosome2.append(parent1.chromosome[j])
children.append(Individual(chromosome1))
children.append(Individual(chromosome2))
return children

def crossbreeding_chooser(crossbreeding_param):
if crossbreeding_param == None or crossbreeding_param.get("method") == None:
print("Crossbreeding method required")
exit(-1)

method = crossbreeding_param.get("method")

if(method == "simple"):
return Crossbreeding(method, simple_crossbreeding)
if(method == "multiple"):
points = crossbreeding_param.get("multiple_point_n")
if points == None or points <=0:
print("Specify a positive quantity of points for mutiple crossbreeding")
exit(-1)
Crossbreeding.points_number = crossbreeding_param.get("multiple_point_n")
return Crossbreeding(method, multiple_crossbreeding)
if(method == "uniform"):
return Crossbreeding(method, uniform_crossbreeding)
else:
print("Incorrect crossbreeding algorithm")
exit(-1)
180 changes: 180 additions & 0 deletions TP2/experiment1_fitness.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
from main import __main__ as genetic_algorithm
import sys
import json

mutation = [[0.05,0.1], [0.1,1], [0.2,2]]
simple_algorithms = ["elite", "roulette", "rank"]
complex_algorithm_names=["tournament_wr", "tournament_nr","truncation"]
complex_algorithm_param_names=["tournament_threshold","tournament_threshold","truncation_k"]
complex_algorithm_params_values = [[0.5,0.65,0.80],[0.5,0.65,0.80],[10,25,50]]
boltzmann_param_names=["boltzmann_tc","boltzmann_t0","boltzmann_k"]
boltzmann_param_values = [[10,70,0.01],[10,140,0.01],[10,70,0.05],[10,140,0.05]]
variability = ["Low", "Medium", "High"]

def simple_algs(total_runs,output_path,avg_output_path):
simple_header="Selection,Variability,Step,Min,Max\n"
lines = []

with open("config.json", "r") as file:
json_values = json.load(file)
json_values.update({"crossbreeding" : {"method": "simple"}})
json_values.pop("error_threshold",-1)
json_values["generations"] = 1000
json_values["limit_first_generation"] = 10
json_values["population_size"] = 50
with open("config.json", "w") as file:
json.dump(json_values,file,indent=4)

for (index_alg,algorithm) in enumerate(simple_algorithms):
lines.append([])
for (index_var,args) in enumerate(mutation):
lines[index_alg].append([])
for i in range(1, total_runs+1):
with open("config.json", "r") as file:
json_values = json.load(file)
json_values.get("selection").update({"method": algorithm})
json_values.update({"output_path":(output_path + str(i))})
json_values.update({"mutation": {"method": "uniform","probability": args[0],"a": args[1]}})
with open("config.json", "w") as file:
json.dump(json_values,file,indent=4)
print('------------------------------------------------------')
print('RUN NUMBER '+ str(i))
genetic_algorithm()
for i in range(1,total_runs+1):
file = open("{0}{1}.csv".format(output_path,i))
lines[index_alg][index_var].append(file.readlines())
file.close()

with open(avg_output_path, 'w') as f:
f.write(simple_header)

line_len = len(lines[0][0][0])

for (index_alg, line_alg) in enumerate(lines):
for (index_var,line_var) in enumerate(line_alg):
for i in range(0,line_len):
current_max_sum = 0
current_min_sum = 0
for j in range(0,total_runs):
line_values = line_var[j][i].split(',')
current_min_sum += float(line_values[0])
current_max_sum += float(line_values[1])
f.write("{0},{1},{2},{3},{4}\n".format(simple_algorithms[index_alg],variability[index_var],i+1,current_min_sum / total_runs, current_max_sum / total_runs))

def complex_algs(total_runs,output_path,avg_output_path):
complex_header="Selection,Param_Name,Param_Value,Variability,Step,Min,Max\n"
lines = []

with open("config.json", "r") as file:
json_values = json.load(file)
json_values.update({"crossbreeding" : {"method": "simple"}})
json_values.pop("error_threshold",-1)
json_values["generations"] = 1000
json_values["limit_first_generation"] = 10
json_values["population_size"] = 50
with open("config.json", "w") as file:
json.dump(json_values,file,indent=4)

for (index_alg,algorithm) in enumerate(complex_algorithm_names):
lines.append([])
for (index_param,algorithm_param) in enumerate(complex_algorithm_params_values[index_alg]):
lines[index_alg].append([])
for (index_var,args) in enumerate(mutation):
lines[index_alg][index_param].append([])
for i in range(1, total_runs+1):
with open("config.json", "r") as file:
json_values = json.load(file)
json_values.get("selection").update({"method": algorithm, complex_algorithm_param_names[index_alg] : algorithm_param})
json_values.update({"output_path":(output_path + str(i))})
json_values.update({"mutation": {"method": "uniform","probability": args[0],"a": args[1]}})
with open("config.json", "w") as file:
json.dump(json_values,file,indent=4)
print('------------------------------------------------------')
print('RUN NUMBER '+ str(i))
genetic_algorithm()
for i in range(1,total_runs+1):
file = open("{0}{1}.csv".format(output_path,i))
lines[index_alg][index_param][index_var].append(file.readlines())
file.close()

with open(avg_output_path, 'w') as f:
f.write(complex_header)

line_len = len(lines[0][0][0][0])

for (index_alg, line_alg) in enumerate(lines):
for(index_param,line_param) in enumerate(line_alg):
for (index_var,line_var) in enumerate(line_param):
for i in range(0,line_len):
current_max_sum = 0
current_min_sum = 0
for j in range(0,total_runs):
line_values = line_var[j][i].split(',')
current_min_sum += float(line_values[0])
current_max_sum += float(line_values[1])
f.write("{0},{1},{2},{3},{4},{5},{6}\n".format(complex_algorithm_names[index_alg], complex_algorithm_param_names[index_alg], complex_algorithm_params_values[index_alg][index_param],variability[index_var],i+1,current_min_sum / total_runs, current_max_sum / total_runs))

def boltzmann_alg(total_runs,output_path,avg_output_path):
boltzmann_header="Selection,Tc,T0,k,Variability,Step,Min,Max\n"
lines = []

with open("config.json", "r") as file:
json_values = json.load(file)
json_values.update({"crossbreeding" : {"method": "simple"}})
json_values.pop("error_threshold",-1)
json_values["generations"] = 1000
json_values["limit_first_generation"] = 10
json_values["population_size"] = 50
with open("config.json", "w") as file:
json.dump(json_values,file,indent=4)

for (index_param_comb, params) in enumerate(boltzmann_param_values):
lines.append([])
for (index_var,args) in enumerate(mutation):
lines[index_param_comb].append([])
for i in range(1, total_runs+1):
with open("config.json", "r") as file:
json_values = json.load(file)
json_values.get("selection").update({"method": "boltzmann",boltzmann_param_names[0]:params[0],boltzmann_param_names[1]:params[1],boltzmann_param_names[2]:params[2]})
json_values.update({"output_path":(output_path + str(i))})
json_values.update({"mutation": {"method": "uniform","probability": args[0],"a": args[1]}})
with open("config.json", "w") as file:
json.dump(json_values,file,indent=4)
print('------------------------------------------------------')
print('RUN NUMBER '+ str(i))
genetic_algorithm()
for i in range(1,total_runs+1):
file = open("{0}{1}.csv".format(output_path,i))
lines[index_param_comb][index_var].append(file.readlines())
file.close()

with open(avg_output_path, 'w') as f:
f.write(boltzmann_header)

line_len = len(lines[0][0][0])

for (index_param_comb, line_param_comb) in enumerate(lines):
for (index_var,line_var) in enumerate(line_param_comb):
for i in range(0,line_len):
current_max_sum = 0
current_min_sum = 0
for j in range(0,total_runs):
line_values = line_var[j][i].split(',')
current_min_sum += float(line_values[0])
current_max_sum += float(line_values[1])
f.write("{0},{1},{2},{3},{4},{5},{6},{7}\n".format("boltzmann",boltzmann_param_values[index_param_comb][0],boltzmann_param_values[index_param_comb][1],boltzmann_param_values[index_param_comb][2],variability[index_var],i+1,current_min_sum / total_runs, current_max_sum / total_runs))


def __main__(total_runs,type,output_path,avg_output_path):
if(type == "simple"):
simple_algs(int(total_runs),output_path,avg_output_path)
elif(type=="complex"):
complex_algs(int(total_runs),output_path,avg_output_path)
elif(type=="boltzmann"):
boltzmann_alg(int(total_runs),output_path,avg_output_path)
else:
print("Wrong type")
exit(-1)

if __name__ == "__main__":
__main__(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])
Loading

0 comments on commit a7299c2

Please sign in to comment.