Issues with Numpy initialisation

43 Views Asked by At

In the initialisation function, I've encountered the following issue while working with ACO: I have multiple paths, each of which is subdivided into arcs that are segmented into segments, and primarily two decision variables, so that each ant must choose a path, an arc, and the secision variable, let's say Y, which takes either 0 or 1 in those segments. Y is an array (which is why I used Numpy),where rows represent arcs and columns represent segments. However, antID 0 has Y as an array, whereas the remaining ants have Y as lists and not arrays. I need assistance

import random
import numpy as np
def initialize_ant_colony(num_segments, num_arcs, num_paths, num_ants):
# Initialize an empty ant colony
ant_colony = []
segment_orders = {
    'U1': ['S1', 'S2', 'S3', 'S4'],
    'U2': ['S5', 'S6', 'S7', 'S8', 'S9', 'S10', 'S11']
num_segments_per_arc = {
    'U1': 4,
    'U2': 7,....
for ant_id in range(num_ants):
    ant = {
        'id': ant_id,
        'path': None,
        'arc': None,
        'segments_y': segments_y.copy(),
    segments_y = [random.choice([0, 1]) for _ in range(num_segments_in_arc )]
    # Initialize segments for this arc based on segment order
    arc_index = list(path_arcs[ant['path']]).index(ant['arc'])
    num_segments_in_arc = num_segments_per_arc[ant['arc']]
    arc_index = list(path_arcs[ant['path']]).index(ant['arc'])
    ant['segments_y'][arc_index] = np.array([np.random.randint(0, 2) for _ in range( 
    num_segments)])
    ant_colony.append(ant)
    return ant_colony

NB: the array that Im using is with 12 arcs and 12 segments, but not all the arcs are segmented to 12 segments for instance arc 2 is segmented into 7 segments, that's why only the four colums take 0or 1 and the rest 0 from index 7 to 11 which not the case in the output

the output is as follows

Ant ID: 0, Path: L3, Arc: U2, Segments Y: [[1 0 1 0 1 0 1 1 0 1 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0]], 
Ant ID: 1, Path: L2, Arc: U7, Segments Y: [0, array([0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 
1]), 0, 0, 0, 0, 0], 
Ant ID: 2, Path: L4, Arc: U8, Segments Y: [0, 0, 0, array([0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 
0, 1]), 1], 
0

There are 0 best solutions below