Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem in matrix
#1
Hello

The code below works fine with the matrix in comment, however I want to use the matrix of the generated graph G instead of set it manually. It gives an error

import networkx as nx
import random as rn
import numpy as np
from numpy.random import choice as np_choice
from collections import OrderedDict

class AntColony(object):

    def __init__(self, distances, n_ants, n_best, n_iterations, decay, alpha=1, beta=1):
        self.distances  = distances
        self.pheromone = np.ones(self.distances.shape) / len(distances)
        self.all_inds = range(len(distances))
        self.n_ants = n_ants
        self.n_best = n_best
        self.n_iterations = n_iterations
        self.decay = decay
        self.alpha = alpha
        self.beta = beta
        

    def run(self):
        shortest_path = None
        all_time_shortest_path = ("placeholder", np.inf)
        
        for i in range(self.n_iterations):
            all_paths = self.gen_all_paths()
            self.spread_pheronome(all_paths, self.n_best, shortest_path=shortest_path)
            shortest_path = min(all_paths, key=lambda x: x[1])
            if shortest_path[1] < all_time_shortest_path[1]:
                all_time_shortest_path = shortest_path            
            self.pheromone * self.decay    
        return all_time_shortest_path

    
    def gen_all_paths(self):
        all_paths = []
        for i in range(self.n_ants):
            path = self.gen_path(0)
            all_paths.append((path, self.gen_path_dist(path)))  # (path - distance)
        return all_paths

    def gen_path(self, start):
        path = []
        visited = set()
        visited.add(start)
        prev = start
        for i in range(len(self.distances) - 1):
            move = self.pick_move(self.pheromone[prev], self.distances[prev], visited)
            path.append((prev, move))
            prev = move
            visited.add(move)
        path.append((prev, start)) # going back to where we started    
        return path
    
    def pick_move(self, pheromone, dist, visited):
        pheromone = np.copy(pheromone)
        pheromone[list(visited)] = 0

        row = pheromone ** self.alpha * (( 1.0 / dist) ** self.beta)
        norm_row = row / row.sum()
        
        move = np_choice(self.all_inds, 1, p=norm_row)[0]
        return move    
    
    def gen_path_dist(self, path):
        total_dist = 0
        for ele in path:
            total_dist += self.distances[ele]
        return total_dist  
    
    def spread_pheronome(self, all_paths, n_best, shortest_path):
        sorted_paths = sorted(all_paths, key=lambda x: x[1])
        for path, dist in sorted_paths[:n_best]:
            for move in path:
                self.pheromone[move] += 1.0 / self.distances[move]



                
G= nx.dorogovtsev_goltsev_mendes_graph(n=2)
m = nx.to_numpy_array(G)
#print(m)

for r in range(len(m)):
    for c in range(len(m[r])):
        if m[r][c] == 0: m[r][c] = float('inf')

distances = repr(m)

"""
distances = np.array([[np.inf, 1, 1, 1, 1, np.inf],
                      [1, np.inf, 1, 1, np.inf, 1],
                      [1, 1, np.inf, np.inf, 1, 1],
                      [1, 1, np.inf, np.inf, np.inf, np.inf],
                      [1, np.inf, 1, np.inf, np.inf, np.inf],
                      [np.inf, 1, 1, np.inf, np.inf, np.inf]])
"""           


print(distances)

ant_colony = AntColony(distances, 1, 1, 100, 0.95, alpha=1, beta=1)
shortest_path = ant_colony.run()
print ("shortest_path: {}".format(shortest_path))
How can I solve it ?

Thanks !
Reply
#2
(Jun-27-2020, 10:08 AM)leemao Wrote: It gives an error

please include the actual error you get when asking for help, It gives an error is not enough information
post the entire error traceback in error code tags like the below example
Error:
Traceback (most recent call last): File "", line 1, in 1 + '2' TypeError: unsupported operand type(s) for +: 'int' and 'str'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Check if two matrix are equal and of not add the matrix to the list quest 3 833 Jul-10-2023, 02:41 AM
Last Post: deanhystad
  How to multiply a matrix with herself, until the zero matrix results peanutbutterandjelly 3 3,379 May-03-2021, 06:30 AM
Last Post: Gribouillis
  Matrix Calculation Problem arshad 4 2,648 Nov-04-2019, 03:48 PM
Last Post: baquerik
  Correlation Matrix Problem Pmllz 0 2,021 Feb-02-2019, 10:19 PM
Last Post: Pmllz
  matrix from matrix python numpy array shei7141 1 3,713 Jan-16-2017, 06:10 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020