Wrong distance matrix from combining point matrix and connection matrix using csv files and numpy library

13 Views Asked by At

I need to create a distance(location) matrix from a points matrix and a connection matrix. The problem is I can't get the correct result. The points matrix is: -,x,y a,1,6 b,2,1 c,9,1 d,370,760

and connection matrix: -,a,b,c,d a,-,-,1,1 b,-,-,1,1 c,1,1,-,- d,1,1,-,-

By looking at the connection matrix points a and b connect to points c and d, points c and d connect to points a and b. So the distance(location) matrix should only have values in (x is values):

-,a,b,c,d a,-,-,x,x b,-,-,x,x c,x,x,-,- d,x,x,-,-

I calculated the distance matrix by hand and it should be: -,a,b,c,d a,-,-,9.43,839.45 b,-,-,7,843.51 c,9.43,7,-,- d,839.45,843.51,-,-

But when I run my code I get this output: a: {'a': 0.0, 'b': 5.0990195135927845, 'c': 9.433981132056603, 'd': 839.4504154504898} b: {'a': 5.0990195135927845, 'b': 0.0, 'c': 7.0, 'd': 843.5075577610435} c: {'a': 9.433981132056603, 'b': 7.0, 'c': 0.0, 'd': 840.4772453790763} d: {'a': 839.4504154504898, 'b': 843.5075577610435, 'c': 840.4772453790763, 'd': 0.0} where I have values where there shouldn't be.

Here is my code:

import csv
import numpy as np


def fetchcsv(filename_points, filename_connections):
    # Read points matrix
    with open(filename_points, "r") as file:
        reader = csv.reader(file)
        r_points = np.array([row for row in reader])

    labels_points = list(map(str, r_points[0][1:]))
    dictionary_points = {}

    # Convert points matrix into a dictionary
    for i in range(1, len(r_points)):
        point = r_points[i][0]
        values = list(map(float, r_points[i][1:]))
        dictionary_points[point] = {
            label: value for label, value in zip(labels_points, values)
        }

    # Read connection matrix
    with open(filename_connections, "r") as file:
        reader = csv.reader(file)
        r_connections = np.array([row for row in reader])

    labels_connections = list(map(str, r_connections[0][1:]))
    dictionary_connections = {}

    # Convert connection matrix into a dictionary
    for i in range(1, len(r_connections)):
        point = r_connections[i][0]
        values = []
        for value in r_connections[i][1:]:
            if value == "-":
                values.append(0)
            else:
                values.append(float(value))
        dictionary_connections[point] = {
            label: value for label, value in zip(labels_connections, values)
        }

    # Calculate location matrix based on formula
    location_matrix = {}
    for point, connections in dictionary_connections.items():
        if point in dictionary_points:
            x1 = dictionary_points[point].get(
                "x", 0
            )  # Get x coordinate, default to 0 if not found
            y1 = dictionary_points[point].get(
                "y", 0
            )  # Get y coordinate, default to 0 if not found
            locations = {}
            for connected_point, connection_strength in connections.items():
                if connected_point in dictionary_points:
                    x2 = dictionary_points[connected_point].get(
                        "x", 0
                    )  # Get x coordinate, default to 0 if not found
                    y2 = dictionary_points[connected_point].get(
                        "y", 0
                    )  # Get y coordinate, default to 0 if not found
                    distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
                    locations[connected_point] = distance
            location_matrix[point] = locations

    return dictionary_points, dictionary_connections, location_matrix


points_file = "points.csv"
connections_file = "connection_matrix.csv"

points, connections, location = fetchcsv(points_file, connections_file)

print("Points Matrix:")
for point, attributes in points.items():
    print(f"{point}: {attributes}")

print("\nConnection Matrix:")
for point, connections in connections.items():
    print(f"{point}: {connections}")

print("\nLocation Matrix:")
for point, locations in location.items():
    print(f"{point}: {locations}")

Could someone help me please fix this? Much appreciated! Also I must do this with numpy and csv libraries

P.S I just joined stack overflow so apologies in advance if I did something wrong. :)

0

There are 0 best solutions below