def find_path(self, latitude, longitude): # Create home node and connect it with other nodes self.insert_home(latitude, longitude) # Retrieve home node home_node = self.database(self.home_id).is_node(list)[0] # Initilize the SearchResults object to store search results result = SearchResults() # After the reinitilization the old value of the object is kept, so it is reset result.reset() # Append home node to the begining of the results result.factories.append(home_node) # Find path using nearest neighbour algorithm result = self.nearest_neighbour(self.home_id, 0, [], [result]) # Retrieve last brewery last_node = result.factories[-1] # Append home node to the back result.factories.append(home_node) # Remove home node and it's connections self.remove_home() return result
def genetic_near_neighbour(self, number_of_runs, latitude, longitude): """ Runs genetic algorithm for nearest neigbour algorithm """ # Creates SearchResults object to store the final result final_result = SearchResults() final_result.reset() # Sets the initial values max_number_of_beer = 0 org_weight = 10 new_weight = 10 # Runs the genetic algorithm number_or_runs times for i in range(number_of_runs): # sets the weight to the mutated one self.weight = new_weight # Runs the neares neighbour algorithm with a mutated weight temp_result = self.find_path(latitude, longitude) # Checks if more beers were found than previous maximum if (len(temp_result.beer) > max_number_of_beer): # sets the maximum number of beer to the new maximum max_number_of_beer = len(temp_result.beer) # sets the orginal best weight to the new weight org_weight = new_weight # Updates the final result final_result = temp_result else: # resets the weith new_weight = org_weight # Decides if to add or subtract the mutation is_negative = random.randint(0, 1) if (is_negative == 1): # Generates mutation and substrcts it new_weight -= random.random() * 10 else: # Generates mutation and adds it new_weight += random.random() * 10 return final_result
def generate_path(latitude, longitude, number_of_runs): # Validate user input try: # Check if values are the correct type latitude = float(latitude) longitude = float(longitude) number_of_runs = int(number_of_runs) # Check if latitude is in range if (latitude < -90 or latitude > 90): raise ValueError # Check if longitude is in range if (longitude < -180 or longitude > 180): raise ValueError # Check if number_of_runs is range if (number_of_runs < 0 or number_of_runs > 20): raise ValueError except ValueError: temp_result = SearchResults() temp_result.reset() return temp_result.return_in_json() # convert to float latitude = float(latitude) longitude = float(longitude) # generate home id unique_id = uuid.uuid4().hex[:12] # create graph object graph = Graph('beer.db', home_id=unique_id, weight=0.504597714410906) # find path result = graph.genetic_near_neighbour(number_of_runs, latitude, longitude) # return result in json return result.return_in_json()