creating children on Genetic Algorithm - python

I am writing Python code for the implementation of the Genetic Algorithm.
I am stuck on creating children. I need this for my research. I have implemented the code to the best of my ability.
def initialise_city(num_dim, limit = 100):
X = np.random.randint(0,limit,size=num_dim)
return X
def initialise_cities(num_cities):
cities = []
for i in range(num_cities):
cities.append(initialise_city(2))
return cities
num_cities = 5
cities = initialise_cities(num_cities)
print("City Positions: ", cities)
def distance_function(cities, visit_order):
distance = 0.0
visit_pos = 0
next_pos = 0
for i, txt in enumerate(visit_order):
if (i < len(visit_order)-1):
visit_pos = visit_order[i]
next_pos = visit_order[i+1]
distance = distance + np.sqrt((cities[visit_pos][0]-cities[next_pos][0])**2 +(cities[visit_pos][1]-cities[next_pos][1])**2)
#raise NotImplementedError()
return -1.0*distance
def initialise_chromosome(chromosome_size):
# YOUR CODE HERE
chromosome = np.random.permutation(chromosome_size)
#raise NotImplementedError()
return chromosome
def initialise_population(population_size, chromosome_size):
population = []
# YOUR CODE HERE
for i in range(population_size):
population.append(initialise_chromosome(chromosome_size))
#raise NotImplementedError()
return population
def calculate_fitness(population, cities, fitness_function):
fitness_list = []
# YOUR CODE HERE
d = 0.0
for i,ix in enumerate(population):
d = fitness_function(cities,ix)
fitness_list.append(fitness_function(cities,ix))
#raise NotImplementedError()
return fitness_list
def selection(population, fitness_list):
## Select the top half of the best of the population
population = np.array(population)
sorted_indices = np.argsort(fitness_list)
selection_point = int(1+ len(fitness_list)/2)
# Randomply permute this top half of the poulation
indices = np.random.choice(sorted_indices[:selection_point], len(population))
best_population = population[indices]
return best_population
def pairing(selected_population):
## pair up parents that will be used to reproduce
count = 0
pairs = []
while count < len(selected_population)-1:
index = count
pairs.append([selected_population[index],selected_population[index+1]])
count +=2
return pairs
I am stuck on this part where children are supposed to be created.
def create_child(a,b):
child = []
# YOUR CODE HERE
point = random.randint(1,len(pairs))
#raise NotImplementedError()
return child
def cross_over(pairs):
final_population = []
for a,b in pairs:
child = create_child(a,b)
final_population.append(child)
child = create_child(b,a)
final_population.append(child)
return final_population

Related

How to get python variable within class and method

I am currently creating my genetic algorithm and want to print the number of generations at the very end of the program when it finishes. However I am unsure how to access the counter variable that is the number of generations when it is outside of the class and method. So for example, at the end it would be like
Generation 100, average fit 18966, best fit 18947
Your best chromosone at generation 100
'\x06pzÂ\x8cYÆr¯n0q\x07l¿M8\x93Þ\x19\x87"\x01\x85\x1er\x89[F_VyER\x9b\x0bm=)\x9a\x9a¿¥\x10F\x12A\x84\x0fZ^\x14\x99\x8a4®\x9f¿*\\\xa0yi\x19E\x8aÇ+6(_<¾£cO~\x9c\x99\x932\x06\x0f\x82\x7f¤\x808xǸñA\x13\x0e<%\x06ÿ#í\x91Pô\x98 ®\r\x1b}\x89y¦\x0cqAK\tp\x95\x99ÔNj=Wn\x16\x94\x0cu!¯ñ\x13Qü[e8_ÂóU\x10\x1av_+%Q_¡ù\x87=\x08~ciÎ_Ï[\x8f#AëT\x14©qG\x89#Z«L\x9b¢\x94WL\x1dV¶R03\x84æ^ßr\x1fÃÈ\x1d\x8e Læª&®x\x94?TAÒD\x14£i\x82J\x15=w~\x03\x0c\xa0¾5\x02f5T\x91ol¢bIÞfk¬¡27W16(}6\x92\x87\n®xm0\x1a\n<8(à}ñ\x88̾\x17g\x9bj6\x8fI&\x12\x9aÂ\x9a_F\x1a\r[\x1dK\x15<.±DjcIy`98d>\x197Z\x91£%tIJ\x820\x93|\x07\x8dnÚ QÂ!Pf\x1d\nåòf\x91\x1d#S¾|\x9ff[d>O=T$ݶI\x9e»QÛÂ\x1d"¿U=û´F÷\x83C}wA\xa0É\x8aD\x93x»\x85\x7f\x14^\x0eL'
done:
100 generations
How do I exactly access the 100 from the method in the class?
import random
class GeneticAlgorithm(object):
def __init__(self, genetics):
self.genetics = genetics
pass
def run(self):
population = self.genetics.initial()
while True:
fits_pops = [(self.genetics.fitness(ch), ch) for ch in population]
if self.genetics.check_stop(fits_pops): break
population = self.next(fits_pops)
pass
return population
def next(self, fits):
parents_generator = self.genetics.parents(fits)
size = len(fits)
nexts = []
while len(nexts) < size:
parents = next(parents_generator)
cross = random.random() < self.genetics.probability_crossover()
children = self.genetics.crossover(parents) if cross else parents
for ch in children:
mutate = random.random() < self.genetics.probability_mutation()
nexts.append(self.genetics.mutation(ch) if mutate else ch)
pass
pass
return nexts[0:size]
pass
class GeneticFunctions(object):
def probability_crossover(self):
r"""returns rate of occur crossover(0.0-1.0)"""
return 1.0
def probability_mutation(self):
r"""returns rate of occur mutation(0.0-1.0)"""
return 0.0
def initial(self):
r"""returns list of initial population
"""
return []
def fitness(self, chromosome):
r"""returns domain fitness value of chromosome
"""
return len(chromosome)
def check_stop(self, fits_populations):
r"""stop run if returns True
- fits_populations: list of (fitness_value, chromosome)
"""
return False
def parents(self, fits_populations):
r"""generator of selected parents
"""
gen = iter(sorted(fits_populations))
while True:
f1, ch1 = next(gen)
f2, ch2 = next(gen)
yield (ch1, ch2)
pass
return
def crossover(self, parents):
r"""breed children
"""
return parents
def mutation(self, chromosome):
r"""mutate chromosome
"""
return chromosome
pass
if __name__ == "__main__":
"""
example: Mapped guess prepared Text
"""
class GuessText(GeneticFunctions):
def __init__(self, target_text,
limit=100, size=100,
prob_crossover=0.9, prob_mutation=0.2):
self.target = self.text2chromo(target_text)
self.counter = 0
self.limit = limit
self.size = size
self.prob_crossover = prob_crossover
self.prob_mutation = prob_mutation
pass
# GeneticFunctions interface impls
def probability_crossover(self):
return self.prob_crossover
def probability_mutation(self):
return self.prob_mutation
def initial(self):
return [self.random_chromo() for j in range(self.size)]
def fitness(self, chromo):
# larger is better, matched == 0
return -sum(abs(c - t) for c, t in zip(chromo, self.target))
def check_stop(self, fits_populations):
self.counter += 1
if self.counter % 100 == 0:
best_match = list(sorted(fits_populations))[-1][1]
fits = [f for f, ch in fits_populations]
best = -(max(fits))
ave = -(sum(fits) / len(fits))
print(
"Generation %3d, average fit %4d, best fit %4d" %
(self.counter, ave, best,
))
print("Your best chromosone at generation %3d" % self.counter)
print("%r" % self.chromo2text(best_match))
pass
return self.counter >= self.limit
def parents(self, fits_populations):
while True:
father = self.tournament(fits_populations)
mother = self.tournament(fits_populations)
yield (father, mother)
pass
pass
def crossover(self, parents):
father, mother = parents
index1 = random.randint(1, len(self.target) - 2)
index2 = random.randint(1, len(self.target) - 2)
if index1 > index2: index1, index2 = index2, index1
child1 = father[:index1] + mother[index1:index2] + father[index2:]
child2 = mother[:index1] + father[index1:index2] + mother[index2:]
return (child1, child2)
def mutation(self, chromosome):
index = random.randint(0, len(self.target) - 1)
vary = random.randint(-5, 5)
mutated = list(chromosome)
mutated[index] += vary
return mutated
# internals
def tournament(self, fits_populations):
alicef, alice = self.select_random(fits_populations)
bobf, bob = self.select_random(fits_populations)
return alice if alicef > bobf else bob
def select_random(self, fits_populations):
return fits_populations[random.randint(0, len(fits_populations)-1)]
def text2chromo(self, text):
return [ord(ch) for ch in text]
def chromo2text(self, chromo):
return "".join(chr(max(1, min(ch, 255))) for ch in chromo)
def random_chromo(self):
return [random.randint(1, 255) for i in range(len(self.target))]
pass
GeneticAlgorithm(GuessText("""The smartest and fastest Pixel yet.
Google Tensor: Our first custom-built processor.
The first processor designed by Google and made for Pixel, Tensor makes the new Pixel phones our most powerful yet.
The most advanced Pixel Camera ever.
Capture brilliant color and vivid detail with Pixels best-in-class computational photography and new pro-level lenses.""")).run()
print('done:')
print("%3d " 'generations' % counter)
pass
Define the GuessText first. Then access the counter.
gt = GuessText("""The smartest and fastest Pixel yet.
Google Tensor: Our first custom-built processor.
The first processor designed by Google and made for Pixel, Tensor makes the new Pixel phones our most powerful yet.
The most advanced Pixel Camera ever.
Capture brilliant color and vivid detail with Pixels best-in-class computational photography and new pro-level lenses.""")
GeneticAlgorithm(gt).run()
print('done:')
print("%3d " 'generations' % gt.counter)

An algorithmic task with triangles

I have a problem with an algorithmic task. There is content of it: "You have ten points on a plane and none three of them are collinear, each pair of different points is connected by line segment, which is green or blue. Calculate how many triangles have sides only in one colour." I tried a solution with n-ary trees but I get repeated triangles with cyclic permutations of integers on the result list.
Patryk, the problem is solvable with n-trees. However, to avoid cyclic permutations you need to skip symmetric line segments. If you create a line segment from 0 -> 1 you do not need to create a segment from 1 -> 0. Below is a complete code which solves the problem with n-trees with the recursive depth-first search. Excuse for Polish names of classes and methods. The interface is in English however. If you analyze the code you will get the point surely.
from random import choice
import copy
class Punkt:
def __init__(self, numer):
self.__numer = numer
self.__odcinki = {}
def dodaj_odcinek_wychodzący(self, punkt_docelowy, kolor):
self.__odcinki[punkt_docelowy] = Odcinek(self.__numer, punkt_docelowy, kolor)
def wez_odcinek_do_punktu_docelowego(self, punkt_docelowy):
return (punkt_docelowy, self.__odcinki[punkt_docelowy].wez_kolor())
def liczba_odcinkow(self):
return len(self.__odcinki)
def wez_kolor_punktu_docelowego(self, punkt_docelowy):
return self.__odcinki[punkt_docelowy].wez_kolor()
def lista_punktow_docelowych(self):
return self.__odcinki.keys()
class Odcinek:
def __init__(self, punkt_zrodlowy, punkt_docelowy, kolor):
self.__punkt_zrodlowy = punkt_zrodlowy
self.__punkt_docelowy = punkt_docelowy
self.__kolor = kolor
def wez_kolor(self):
return self.__kolor
class Structure:
def __init__(self, liczba_punktow=10):
self.__punkty = [Punkt(i)
for i in range(liczba_punktow)]
for i in range(liczba_punktow):
for j in range(i + 1, liczba_punktow):
self.__punkty[i].dodaj_odcinek_wychodzący(j, choice(["green", "blue"]))
# for j in range(liczba_punktow):
# for i in range (j + 1, liczba_punktow):
# self.__punkty[j].dodaj_odcinek_wychodzący(*(self.__punkty[j].wez_odcinek_do_punktu_docelowego(i)))
def wez_punkt(self, numer):
return self.__punkty[numer]
def wez_liczbe_punktow(self):
return len(self.__punkty)
class Search:
def __init__(self, struktura):
self.__s = struktura
def wez_liczbe_punktow(self):
return self.__s.wez_liczbe_punktow()
def wez_punkt(self, numer):
return self.__s.wez_punkt(numer)
def szukaj(self, kolor="green"):
self.__szukany_kolor = kolor
lista_trojkatow = []
liczba_trojkatow = 0
wszystkie_trojkaty = []
for i in range(self.wez_liczbe_punktow()):
lista_odwiedzonych_punktow = [i]
lista_trojkatow = self.szukaj_z_punktu(i,lista_odwiedzonych_punktow,lista_trojkatow)
return len(lista_trojkatow), lista_trojkatow
def wez_szukany_kolor(self):
return self.__szukany_kolor
def szukaj_z_punktu(self, numer, trojkat, lista_trojkatow):
if len(trojkat) == 3: # jeżeli zebraliśmy już trzy punkty to brakuje tylko zamykającego, czwartego
if self.wez_punkt(trojkat[0]).wez_kolor_punktu_docelowego(
trojkat[-1]) == self.wez_szukany_kolor(): # sprawdź czy do punktu zamykającego prowadzi odcinek o szukanym kolorze
trojkat.append(trojkat[0]) # dodaj punkt zamykajacy do trójkąta
lista_trojkatow.append(trojkat) # dodaj trojkąt do listy trójkątów
# return lista_trojkatow # zwróć liste trójkątów obliczonych dotychczas
else:
potomkowie = []
for punkt_docelowy in self.wez_punkt(numer).lista_punktow_docelowych():
if self.wez_punkt(numer).wez_kolor_punktu_docelowego(punkt_docelowy) == self.wez_szukany_kolor():
potomkowie.append(punkt_docelowy)
for potomek in potomkowie:
trojkat_kopia = copy.copy(trojkat)
trojkat_kopia.append(potomek)
lista_trojkatow = self.szukaj_z_punktu(potomek, trojkat_kopia, lista_trojkatow)
return lista_trojkatow
if __name__ == "__main__":
s = Structure()
for source_point in range(s.wez_liczbe_punktow()):
for destination_point in s.wez_punkt(source_point).lista_punktow_docelowych():
print(f"{source_point} -> {destination_point} = {s.wez_punkt(source_point).wez_kolor_punktu_docelowego(destination_point)}")
color = "green"
searching = Search(s)
number_of_triangles, all_triangles = searching.szukaj("green")
print(f"Number of triangles of color {color} = {number_of_triangles}")
print(f"List of all triangles: {all_triangles}")

How to handle the TypeError: 'int' object is not callable?

I want to implements a-star algorithm and the function (from Route_Algorithm.py) extends the nodes to get the next layor of f_value in the tree . The node can be regard as the station. And the self.settings.station_matrix is the numpy.matrix.
def voluation_station(self, successor, dest_location,bus_stations):
'''initilize all the f(g+h) to the specific nodes'''
length = len(self.settings.station_matrix[successor])
for end_element in range(length):
for station in bus_stations:
if int(station.name) == end_element:
station.get_g(self.settings.station_matrix[successor][end_element])
length_station = len(self.settings.station_matrix[end_element])
for element_station in range(length_station):
if element_station == dest_location:
station.get_h(self.settings.station_matrix[end_element][dest_location])
for element in bus_stations:
element.result_f()
return bus_stations
However, when I run the part of code. It reports the error like this:
Traceback (most recent call last):
File "/home/surface/Final-Year-Project/FYP/Main.py", line 4, in <module>
class main():
File "/home/surface/Final-Year-Project/FYP/Main.py", line 13, in main
new_route.busy_route_matrix()
File "/home/surface/Final-Year-Project/FYP/oop_objects/Route.py", line 87, in busy_route_matrix
self.route_algorithm.A_STAR_Algorithm(start_location,dest_location,self.bus_stations)
File "/home/surface/Final-Year-Project/FYP/Util/Route_Algorithm.py", line 40, in A_STAR_Algorithm
self.voluation_station(successor, dest_location,bus_stations)
File "/home/surface/Final-Year-Project/FYP/Util/Route_Algorithm.py", line 73, in voluation_station
station.get_g(self.settings.station_matrix[successor][end_element])
TypeError: 'int' object is not callable
I search the solution in the Internet, I think the problem may be in the end_element, maybe some inherient problem but I'm not sure. Can some one help me! Please!
Additional codes for other classes:
These classes are Util classes, which helps for handle oop_objects!
The class is for the Route_Algorithm:
from Util.Mergesort_algorithm import mergesort_algorithm
class route_algorithm():
'''generate the route to optimise the profiles'''
def __init__(self,settings):
# a* algorithm
self.open_list = []
self.close_list = []
self.route = []
self.settings = settings
self.flag_find = False
self.lines = []
# merge_sort algorithm
self.mergesort_algorithm = mergesort_algorithm()
def A_STAR_Algorithm(self, start_location, dest_location,bus_stations):
'''search the best route for each passenger to the destination'''
#self.clean_f(bus_stations)
# initial the value of f in start_location
for item in bus_stations:
if int(item.name) == start_location:
item.get_g = 0
for key, value in item.adjacent_station.items():
if int(key.name) == dest_location:
item.get_h = value
self.open_list.append(start_location)
#start_location is the name of station
while self.flag_find == False:
successor = self.open_list[0]
self.open_list.remove(successor)
self.route.append(successor)
self.voluation_station(successor, dest_location,bus_stations)
self.a_brain_judge_1(dest_location,bus_stations)
print(self.flag_find)
if self.flag_find == True:
#end the location
self.route.append(dest_location)
#add the line to the self.line
self.print_lines()
self.flag_find = False
self.open_list = []
else:
#continue to search the minimize
list = self.sort(bus_stations)
for item in list:
print(item.name)
print(item.f)
#疑问如果前两个的预估值一样该如何处理
self.open_list.append(int(list[0].name))
def voluation_station(self, successor, dest_location,bus_stations):
'''initilize all the f(g+h) to the specific nodes'''
length = len(self.settings.station_matrix[successor])
for end_element in range(length):
for station in bus_stations:
if int(station.name) == end_element:
station.get_g(self.settings.station_matrix[successor][end_element])
length_station = len(self.settings.station_matrix[end_element])
for element_station in range(length_station):
if element_station == dest_location:
station.get_h(self.settings.station_matrix[end_element][dest_location])
for element in bus_stations:
element.result_f()
return bus_stations
def a_brain_judge_1(self, dest_location,bus_stations):
'''whether the direct_line is the optimize'''
tmp_dest = bus_stations[0]
self.tmp_nodes = []
self.flag_find = True
for element in bus_stations:
if int(element.name) == dest_location:
tmp_dest = element
for element in bus_stations:
if element == tmp_dest:
pass
else:
if element.f < tmp_dest.f:
self.tmp_nodes.append(element)
self.flag_find = False
if self.flag_find == True:
self.route.append(tmp_dest.name)
return None
else:
return self.tmp_nodes
def sort(self,bus_stations):
'''sort all the f in the next stations'''
return self.mergesort_algorithm.Merge_Sort(bus_stations)
def print_lines(self):
#print(len(self.route))
for item in self.route:
print(item)
print("NEXT PASSENGER!---------")
def clean_f(self,stations):
for item in stations:
item.clean_data()
The class is Random_Algorithm, which helps for generate the random passengers.
import random
from Data.Settings import settings
from oop_objects.Bus_Station import bus_station
from oop_objects.Passenger import passenger
class random_algorithm():
'''generate the random bus-stations and passengers'''
def __init__(self):
self.setting = settings()
def random_passenger(self,number):
'''generate random passengers for bus-station,
and assumes there are 6 stations now. Furthermore, the data will be crawled by the creeper'''
passengers = []
for i in range(number):
new_passenger = passenger()
random.seed(self.setting.seed)
new_passenger.Change_Name(random.randint(1,self.setting.bus_station_number))
# generate the start-location
self.setting.seed +=1
end_location = random.randint(1,self.setting.bus_station_number)
# generate the end-location
while new_passenger.name == end_location:
self.setting.seed += 1
end_location = random.randint(1,self.setting.bus_station_number)
#judge whether the start-location same as the end-location
new_passenger.change_end_location(end_location)
passengers.append(new_passenger)
return passengers
def random_station(self,number):
'''generate the name of random stations '''
bus_stations = []
for i in range(number):
new_bus_station = bus_station()
new_bus_station.Name(str(i))
bus_stations.append(new_bus_station)
return bus_stations
def random_edge(self,bus_stations):
'''generate the edge information for the stations'''
for location1 in bus_stations:
#print("The information add in "+location1.name)
for location2 in bus_stations:
if location1 != location2:
#print("the "+location2.name+" was added in the "+location1.name)
if location2 not in location1.adjacent_station and location1 not in location2.adjacent_station:
random.seed(self.setting.seed)
edge = random.randint(1,self.setting.edge_distance)
location1.add_adjacent_station(location2,edge)
#print("the edge is "+str(edge))
self.setting.seed += 1
return bus_stations
The class is the mergesort_algorithm, which compare the f for different stations
class mergesort_algorithm():
def Merge_Sort(self,stations):
length = len(stations)
middle = int(length/2)
if length<=1:
return stations
else:
list1 = self.Merge_Sort(stations[:middle])
list2 = self.Merge_Sort(stations[middle:])
return self.Merge(list1,list2)
def Merge(self,list1,list2):
list3 = []
length1 = len(list1)
length2 = len(list2)
point1 = 0
point2 = 0
while point1<=length1-1 and point2<=length2-1:
if list1[point1].f<list2[point2].f:
list3.append(list1[point1])
point1 += 1
else:
list3.append(list2[point2])
point2 += 1
if point1>=length1:
for i in range(length2):
if i>=point2:
list3.append(list2[point2])
if point2>=length2:
for i in range(length1):
if i>=point1:
list3.append(list1[point1])
return list3
#def print_sort_result(self):
The following class are oop.classes
The class is for the Route:
from Util.Random_Algorithm import random_algorithm
from Data.Settings import settings
from Util.Route_Algorithm import route_algorithm
import numpy as np
class route():
def __init__(self):
self.bus_stations = []
self.passengers = []
self.settings = settings()
#random algorithm
self.random_algorithm = random_algorithm()
#route_algorithm
self.route_algorithm = route_algorithm(self.settings)
def start_route(self):
'''The raw route Information(TEXT) for bus_stations '''
stations = self.random_algorithm.random_station(self.settings.bus_station_number)
finsih_edge_stations = self.random_algorithm.random_edge(stations)
'''
for item in finsih_edge_stations:
print("\nthe information for " + item.name + " is: \t")
for key, value in item.adjacent_station.items():
print("the station is " + key.name)
print(" the distace is " + str(value))
'''
self.bus_stations = finsih_edge_stations
'''The raw route Information(Text) for passengers'''
self.passengers = self.random_algorithm.random_passenger(self.settings.passengers_number)
def bus_stations_matrix(self):
'''trasfer the raw text to the matrix'''
#create zero_matrix
length = len(self.bus_stations)
tmp_matrix = np.zeros(length*length)
station_matrix = tmp_matrix.reshape(length,length)
for item in self.bus_stations:
for key,value in item.adjacent_station.items():
station_matrix[int(item.name)][int(key.name)] = value
station_matrix[int(key.name)][int(item.name)] = value
print(station_matrix)
self.settings.station_matrix = station_matrix
def passengers_matrix(self):
'''trasfer the raw text to the matrix'''
length = len(self.bus_stations)
tmp_matrix = np.zeros(length*length)
passenger_matrix = tmp_matrix.reshape(length,length)
for item in self.passengers:
#print("the start location of passenger is "+str(item.name))
#print("the end location of passenger is "+str(item.end_location))
#print(" ")
passenger_matrix[item.name-1][item.end_location-1]+=1;
print(passenger_matrix)
self.settings.passenger_matrix = passenger_matrix
def busy_route_matrix(self):
'''generate the bus_busy_route matrix'''
#read the requirements of passengers
length = self.settings.bus_station_number
for start_location in range(length):
for dest_location in range(length):
if self.settings.passenger_matrix[start_location][dest_location] == 0:
pass
else:
magnitude = self.settings.passenger_matrix[start_location][dest_location]
#运行a*算法去寻找最短路径/run the a* algorithm to search the path
self.route_algorithm.A_STAR_Algorithm(start_location,dest_location,self.bus_stations)
print("------------------------------------")
def practice(self):
'''practice some programming'''
for element in self.bus_stations:
print((element.f))
The class is for the Passenger
class passenger():
def __init__(self):
self.name = 0
self.end_location = "null"
def Change_Name(self,name):
'''change the name of passenger'''
self.name = name
def change_end_location(self,location):
'''generate the end_location'''
self.end_location = location
The class for the bus_station
class bus_station():
'''the class represents the bus station'''
def __init__(self):
'''the attribute of name means the name of bus-station
the attribute of passenger means the passenger now in the bus-station'''
self.name = "null"
self.passenger = []
self.adjacent_station = {}
#A* algorithm
self.g = 0
self.h = 0
self.f = 0
def Name(self,name):
'''change the name of the station'''
self.name = name
def add_passengers(self,*passenger):
'''add the passenger in the bus-station'''
self.passenger.append(passenger)
def add_adjacent_station(self,station,edge):
'''add the adjacent station in the this station'''
self.adjacent_station[station] = edge
def get_g(self,value):
'''get the value of g (线路值)'''
self.g =self.g+ value
def get_h(self,value):
'''get the value of f (预估值)'''
self.h = value
def result_f(self):
'''print the value of f (实际值)'''
self.f = self.g+self.h
def add_self_cost(self):
self.add_adjacent_station()
The following class is storing the data.
The class is for the setting:
class settings():
def __init__(self):
self.seed = 5
self.bus_station_number = 10
self.passengers_number = 10
self.edge_distance = 50
self.station_matrix = None
self.passenger_matrix = None
And the main class to run the whole project:
from oop_objects.Route import route
class main():
new_route = route()
new_route.start_route()
print("The distance between different bus station :")
new_route.bus_stations_matrix()
print("The location information for passengers :")
new_route.passengers_matrix()
new_route.busy_route_matrix()
#new_route.practice()practice
#new_route.sort()bus_stations
You should avoid the station of successor because you have assigned the value by using the get_g
The result should be:
def voluation_station(self, successor, dest_location,bus_stations):
'''initilize all the f(g+h) to the specific nodes'''
length = len(self.settings.station_matrix[successor])
for end_element in range(length):
if end_element == successor:
pass
else:
for station in bus_stations:
if int(station.name) == end_element:
station.get_g(self.settings.station_matrix[successor][end_element])
length_station = len(self.settings.station_matrix[end_element])
for element_station in range(length_station):
if element_station == dest_location:
station.get_h(self.settings.station_matrix[end_element][dest_location])
for element in bus_stations:
element.result_f()
return bus_stations

Class method for merge sort recursively

I am trying to create a method for merge sort recursively. I am not so familiar with objects and i am trying to get this right. I know the algorithm works as a stand alone function, but when trying to implement as a class method, i get error.
The problem lies in this two lines of code:
left_list = left_list.merge_sort()
right_list = right_list.merge_sort()
class Lists(object):
def __init__(self):
self.capacity = 8
self.arr = [None] * capacity
self.size = 0
def merge_sort(self):
if self.size <= 1:
return self.arr
middle = self.size // 2
left_list = self.arr[:middle]
right_list = self.arr[middle:]
left_list = left_list.merge_sort()
right_list = right_list.merge_sort()
return list(self.merge(left_list, right_list))
def merge(self, left_half, right_half):
res = []
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
res.append(left_half[0])
left_half.remove(left_half[0])
else:
res.append(right_half[0])
right_half.remove(right_half[0])
if len(left_half) == 0:
res = res + right_half
else:
res = res + left_half
return res
And of course is another function append, that appends each time at the self.arr and increases the size by 1 each time an element is appended.

Python, takes 1 positional argument but 2 were given [duplicate]

This question already has answers here:
Overloaded functions in Python
(6 answers)
Closed 5 years ago.
Im to trying run a Python script in Spyder IDE (Python 3.6) and as I progress Im starting to refactor it to more of OOP (Object Oriented) and hopefully a mature package.
I have a class titled (Epoch), see below:
class Epoch:
def __init__(self):
self.Epoch_Counter = 0
self.Timings = []
self.Timings_millisec_ticks = []
self.Duration_milli_secs = 0
self.Raw = []
self.Stimulia = []
self.Majority_stimulia = "NA"
self.epoch = datetime.datetime.utcfromtimestamp(0)
#median, positive area, negative area, geometric,max,ratio positive vs negative
self._median = 0
self._mean = 0
self._positive_area = 0
self._negative_area = 0
self._geometric_area = 0
self._max = 0
self._min = 0
self._max_amplitude = 0
self._integral = 0
self._variance= 0
self._positive_to_negative_ratio = 0
self._skew = 0
self._kurtosis = 0
self.Components = []
#mean
def mean(self,value):
self._mean = value
def mean(self):
return self._mean
#median
def median(self,value):
self._median = value
def median(self):
return self._median
#positive_area
def positive_area(self,value):
self._positive_area = value
def positive_area(self):
return self._positive_area
#negative_area
def negative_area(self,value):
self._negative_area = value
def negative_area(self):
return self._negative_area
#geometric_area
def geometric_area(self,value):
self._geometric_area = value
def geometric_area(self):
return self._geometric_area
def integral(self,value):
self.integral = value
def integral(self):
return self.integral
def max_amplitude(self,value):
self._max_amplitude = value
def max_amplitude(self):
return self._max_amplitude
def max_(self,value):
self._max = value
def max_(self):
return self._max
#min
def min_(self,value):
self.min = value
def min_(self):
return self._min
def positive_to_negative_ratio(self,value):
self.positive_to_negative_ratio = value
def positive_to_negative_ratio(self,value):
return self._positive_to_negative_ratio
#Timings_millisec_ticks
def timings_millisec_ticks(self):
return self.Timings_millisec_ticks
def timings_millisec_ticks_append(self,value):
self.Timings_millisec_ticks.append(value)
#start_time
def timings(self):
return self.Timings
def timings_append(self,value):
self.Timings.append(value)
#end_time
def end_time(self):
return self.Timings[len(self.Timings)-1]
#start_time
def start_time(self):
return self.Timings[0]
#duration
def duration_milli_secs(self):
return self.Duration_milli_secs
def duration_milli_secs(self):
return self.unix_time_millis(self.str_to_datetime_(self.end_time())) - self.unix_time_millis(self.str_to_datetime_(self.start_time()))
#raw
def raw(self):
return self.Raw
def raw_append(self,value):
self.Raw.append(value)
#components
def components(self):
return self.Components
def components_append(self,value):
self.Components.append(value)
#stimulia
def stimulia_append(self,value):
self.Stimulia.append(value)
def stimulia(self):
return self.Stimulia
#variance
def variance(self):
return self.variance
def variance(self,value):
self.variance = value
#skew
def skew(self,value):
self._skew = value
def skew(self):
return self._skew
def unix_time_millis(self,dt):
return (dt - self.epoch).total_seconds() * 1000.0
""" covert datetime of this format 2017-10-13 19:22:50:525 to datetime object"""
def str_to_datetime_(self,datetime_str):
return datetime.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S:%f')
def _print(self):
return str(self.Epoch_Counter)+","+str(len(self.Timings))+","+str(self.duration_milli_secs())+","+str(len(self.Raw))+","+str(len(self.Stimulia))+","+str(self.majority_stimulia)
I have script that has function, that calculates summary statistics and attempts to set the value of the statistics in the Epoch object (mean,median,etc...), see below:
def get_epoch_summary_stats(eeg_record_epochs_):
import numpy as np
import scipy.stats as stats
import pylab as pl
##stimulia
stimulia_raw_median = []
stimulia_raw_mean = []
stimulia_raw_positive_area = []
stimulia_raw_negative_area = []
stimulia_raw_geometric_area = []
stimulia_raw_max = []
stimulia_raw_min = []
stimulia_raw_positive_to_negative = []
stimulia_variance = []
stimulia_max_amplitude = []
stimulia_integral = []
stimulia_raw_kurtosis = []
stimulia_raw_skew = []
##no stimulia
no_stimulia_raw_median = []
no_stimulia_raw_mean = []
no_stimulia_raw_positive_area = []
no_stimulia_raw_negative_area = []
no_stimulia_raw_geometric_area = []
no_stimulia_raw_max = []
no_stimulia_raw_min = []
no_stimulia_raw_positive_to_negative = []
no_stimulia_variance = []
no_stimulia_max_amplitude = []
no_stimulia_integral = []
no_stimulia_raw_kurtosis = []
no_stimulia_raw_skew = []
no_stimulia_class_count = 0
stimulia_class_count = 0
epoch_durations = []
stimulia_raws = []
no_stimulia_raws = []
for item in eeg_record_epochs:
epoch_durations.append(item.duration_milli_secs())
epoch_durations_sorted = sorted(epoch_durations)
mean_duration = np.mean(epoch_durations_sorted)
std_duration = np.std(epoch_durations_sorted)
print("Input data:",path)
print("Epoch duration(millisecs) - mean_duration:",mean_duration)
print("Epoch duration(millisecs) - std_duration:",std_duration)
#remove epoch that are more than 1 standard deviation away from the mean in epoch size
counter = 0
for item in eeg_record_epochs_:
##DURATION SELECTION RULE
if (item.duration_milli_secs() > (mean_duration + std_duration) or item.duration_milli_secs() < (mean_duration - std_duration)):
del eeg_record_epochs[counter]
##print("epoch duration_milli_secs - REMOVED:",item.duration_milli_secs())
else:
##print("epoch duration_milli_secs:",item.duration_milli_secs())
#median, positive area, negative area, geometric area, max , ratio positive vs negative, ratio negative vs positive
raw_float_array = np.array(item.raw()).astype(np.float)
#median
item.median(np.median(raw_float_array))
#mean
item.mean(np.mean(raw_float_array))
##print("raw median: ",item.median)
positive_area = 0
negative_area = 0
#positive area
for value in raw_float_array:
if value > 0:
positive_area = positive_area + value
item.positive_area(positive_area)
##print("raw positive_area:", item.positive_area)
#negative area
for value in raw_float_array:
if value < 0 :
negative_area = negative_area + abs(value)
item.negative_area(negative_area)
##print("raw negative_area:", item.negative_area)
#geometric area
abs_raw_float_array = np.abs(raw_float_array)
item.geometric_area(sum(abs_raw_float_array))
##print("raw geometric_area:", item.geometric_area)
#max_
item.max(max(raw_float_array))
##print("raw max_:",item.max_)
#min
item.min(min(raw_float_array))
item.max_amplitude(max(max(raw_float_array),abs(min(raw_float_array))))
item.integral(item.positive_area - abs(item.negative_area))
##print("raw min_:",item.min_)
#min
#positive_to_negative_ratio
try:
item.positive_to_negative_ratio=abs(item.positive_area/item.negative_area)
except ZeroDivision as err:
continue
#variance
item.variance(np.var(raw_float_array))
#skew
item.skew(stats.skew(raw_float_array))
#kurtosis
item.kurtosis(stats.kurtosis(raw_float_array))
##print("raw positive_to_negative:",item.positive_to_negative_ratio)
item.majority_stimulia()
##default NO_STIMULIA
stimulia_class = "NO_STIMULIA"
if item.majority_stimulia().upper() == "ON":
stimulia_class = "ON"
print(stimulia_class)
item.plot()
for raw_value in item.raw():
stimulia_raws.append(int(raw_value))
stimulia_raw_median.append(item.median)
stimulia_raw_mean.append(item.mean)
stimulia_raw_positive_area.append(item.positive_area)
stimulia_raw_negative_area.append(item.negative_area)
stimulia_raw_geometric_area.append(item.geometric_area)
stimulia_raw_max.append(item.max_)
stimulia_raw_min.append(item.min_)
stimulia_raw_mean.append(item.mean)
stimulia_raw_skew.append(item.skew)
stimulia_raw_kurtosis.append(item.kurtosis)
stimulia_max_amplitude.append(item.max_amplitude)
stimulia_integral.append(item.integral)
##append only if the number is not inf or nan but just a number
if is_not_inf_or_is_nan(item.positive_to_negative_ratio) != 1:
stimulia_raw_positive_to_negative.append(item.positive_to_negative_ratio)
##print("item.positive_to_negative_ratio:",item.positive_to_negative_ratio)
stimulia_variance.append(item.variance)
stimulia_class_count= stimulia_class_count + 1
#P3 component stats +/- estimated peek for P3
else:
no_stimulia_class_count = no_stimulia_class_count + 1
print(stimulia_class)
item.plot()
for raw_value in item.raw():
no_stimulia_raws.append(int(raw_value))
no_stimulia_raw_median.append(item.median)
no_stimulia_raw_mean.append(item.mean)
no_stimulia_raw_positive_area.append(item.positive_area)
no_stimulia_raw_negative_area.append(item.negative_area)
no_stimulia_raw_geometric_area.append(item.geometric_area)
no_stimulia_raw_max.append(item.max_)
no_stimulia_raw_min.append(item.min_)
no_stimulia_raw_mean.append(item.mean)
no_stimulia_raw_skew.append(item.skew)
no_stimulia_raw_kurtosis.append(item.kurtosis)
no_stimulia_max_amplitude.append(item.max_amplitude)
no_stimulia_integral.append(item.integral)
##append only if the number is not inf or nan but just a number
if is_not_inf_or_is_nan(item.positive_to_negative_ratio) != 1:
no_stimulia_raw_positive_to_negative.append(item.positive_to_negative_ratio)
##print("item.positive_to_negative_ratio:",item.positive_to_negative_ratio)
no_stimulia_variance.append(item.variance)
##print("majority stimulia:",item.Majority_stimulia)
counter = counter + 1
##component_extraction(item,"ON",300,200,800)
print("ON summary stats-")
mean_plot = float(sum(stimulia_raw_mean)/counter)
std_plot = float(math.sqrt(sum(stimulia_variance)/counter))
fit = stats.norm.pdf(sorted(stimulia_raws), mean_plot, std_plot) #this is a fitting indeed
pl.plot(sorted(stimulia_raws),fit,'-o')
pl.hist(sorted(stimulia_raws),normed=True) #use this to draw histogram of your data
pl.show()
print("stimulia_class_count:",stimulia_class_count)
print("average stimulia_raw_mean:",sum(stimulia_raw_mean)/counter)
print("average stimulia_raw_median:",sum(stimulia_raw_median)/counter)
print("average stimulia_raw_positive_area:",sum(stimulia_raw_positive_area)/counter)
print("average stimulia_raw_negative_area:",sum(stimulia_raw_negative_area)/counter)
print("average stimulia_raw_geometric_are:",sum(stimulia_raw_geometric_area)/counter)
print("average stimulia_raw_max:",sum(stimulia_raw_max)/counter)
print("average stimulia_raw_min:",sum(stimulia_raw_min)/counter)
print("average stimulia_max_amplitude:",sum(stimulia_max_amplitude)/counter)
print("average stimulia_integral:",sum(stimulia_integral)/counter)
print("average stimulia_variance:",sum(stimulia_variance)/counter)
print("average stimulia_std:",math.sqrt(sum(stimulia_variance)/counter))
print("average stimulia_skew:",sum(stimulia_raw_skew)/counter)
print("average stimulia_kurtosis:",sum(stimulia_raw_kurtosis)/counter)
print("average stimulia_raw_positive_to_negative:",sum(stimulia_raw_positive_to_negative)/counter)
print("NO_STIMULIA summary stats-")
mean_plot = float(sum(no_stimulia_raw_mean)/counter)
std_plot = float(math.sqrt(sum(no_stimulia_variance)/counter))
fit = stats.norm.pdf(sorted(no_stimulia_raws), mean_plot, std_plot) #this is a fitting indeed
pl.plot(sorted(no_stimulia_raws),fit,'-o')
pl.hist(sorted(no_stimulia_raws),normed=True) #use this to draw histogram of your data
pl.show()
print("no_stimulia_class_count:",no_stimulia_class_count)
print("average no_stimulia_raw_mean:",sum(no_stimulia_raw_mean)/counter)
print("average no_stimulia_raw_median:",sum(no_stimulia_raw_median)/counter)
print("average no_stimulia_raw_positive_area:",sum(no_stimulia_raw_positive_area)/counter)
print("average no_stimulia_raw_negative_area:",sum(no_stimulia_raw_negative_area)/counter)
print("average no_stimulia_raw_geometric_are:",sum(no_stimulia_raw_geometric_area)/counter)
print("average no_stimulia__raw_max:",sum(no_stimulia_raw_max)/counter)
print("average no_stimulia_raw_min:",sum(no_stimulia_raw_min)/counter)
print("average no_stimulia_max_amplitude:",sum(no_stimulia_max_amplitude)/counter)
print("average no_stimulia_integral:",sum(no_stimulia_integral)/counter)
print("average no_stimulia_variance:",sum(no_stimulia_variance)/counter)
print("average no_stimulia_std:",math.sqrt(sum(no_stimulia_variance)/counter))
print("average no_stimulia_skew:",sum(no_stimulia_raw_skew)/counter)
print("average no_stimulia_kurtosis:",sum(no_stimulia_raw_kurtosis)/counter)
print("average no_stimulia_raw_positive_to_negative:",sum(no_stimulia_raw_positive_to_negative)/counter)
When running the script, I get an error:
File "", line 1, in
get_epoch_summary_stats(eeg_record_epochs)
File "", line 425, in get_epoch_summary_stats
item.median(np.median(raw_float_array))
TypeError: median() takes 1 positional argument but 2 were given
How can I fix the Epoch class or my call to item.median() in order to set Epoch's median attribute without getting this error.
Thanks a million!
There is no method overloading in python. If you define median function twice, the second definition will be used. Therefore in your code, the second definition is used, i.e.,
def median(self):
return self._median
So it only takes one positional argument (self).
It seems what you want to define is a getter and a setter. In python, you can do it by adding functional decorators. For example:
#property
def median(self):
return self._median
#median.setter
def median(self, value):
self._median = value
The first one is a getter for median, and the second one is a setter. When you invoke print(self.median), the first function will be called, while if you execute self.median = 5, the second function will be called.
You can read this article for more information about getter and setters in python: http://stackabuse.com/python-properties/
You are defining median two times:
#median
def median(self,value):
self._median = value
def median(self):
return self._median
The second definition is used, which does not accept a second argument named value.
Adding to the other answer as he was correct. Try to focus on changing your functions to getters and setters. Should help out in the long run.

Categories

Resources