Как обрабатывать объект TypeError: 'int' не вызывается? - PullRequest
0 голосов
/ 07 апреля 2020

Я хочу реализовать алгоритм a-star , и функция (из Route_Algorithm.py) расширяет узлы, чтобы получить следующий уровень f_value в дереве. Узел можно рассматривать как станцию. И self.settings.station_matrix - это 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

Однако, когда я запускаю часть кода. Он сообщает об ошибке следующим образом:

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

Я ищу решение в Inte rnet, я думаю, что проблема может быть в end_element , возможно, какая-то наследственная проблема, но я ' Я не уверен. Кто-нибудь может мне помочь! Пожалуйста!

Дополнительные коды для других классов:

Эти классы являются классами Util, что помогает для обработки oop_objects! Класс предназначен для алгоритма 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()

Классом является Random_Algorithm, который помогает генерировать случайных пассажиров.

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

Классом является алгоритм mergesort_algorithm, который сравнивает f для разных станций



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):


Следующий класс: oop .classes

Класс для маршрута:

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))


Класс для Пассажира


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




Класс для 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()

Следующий класс хранит данные.

Этот класс предназначен для настройки:


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

И основной класс для запуска всего проекта:

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

1 Ответ

0 голосов
/ 07 апреля 2020

Вы должны избегать станции преемника, потому что вы присвоили значение с помощью get_g Результат должен быть:

    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
...