amin khare 3 takmili

 avatar
unknown
python
a year ago
3.0 kB
7
Indexable
import psycopg2
import networkx as nx
import time

# Database connection parameters
hostname = 'localhost'
database = 'GraphSQL'
username = 'qs2215'
password = '****'
port = '9090'

def fetch_road_network():
    start_time = time.time()
    try:
        # Connect to the PostgreSQL database
        conn = psycopg2.connect(
            dbname=database,
            user=username,
            password=password,
            host=hostname,
            port=port
        )
        cursor = conn.cursor()

        # Update the query to match the actual column names
        query = 'SELECT source_node_id, destination_node_id FROM "Road networks"."roadNet-TX";'
        cursor.execute(query)

        # Fetch all rows from the query result
        rows = cursor.fetchall()
        print("Data fetched successfully.")
        return rows

    except Exception as error:
        print("Error while connecting to PostgreSQL:", error)
        return None
    finally:
        if conn:
            cursor.close()
            conn.close()
            print("PostgreSQL connection is closed")
            end_time = time.time()
            print(f"Runtime for fetching data: {end_time - start_time:.2f} seconds")

def create_graph(data):
    start_time = time.time()
    G = nx.Graph()

    # Each row in data is a tuple (source_node_id, destination_node_id)
    for source_node_id, destination_node_id in data:
        G.add_edge(source_node_id, destination_node_id, weight=1)  # Assuming weight = 1

    end_time = time.time()
    print(f"Runtime for creating graph: {end_time - start_time:.2f} seconds")
    return G

def find_shortest_path(G, source, target):
    start_time = time.time()
    try:
        path = nx.shortest_path(G, source=source, target=target, weight='weight')
        length = nx.shortest_path_length(G, source=source, target=target, weight='weight')
        return path, length
    except nx.NetworkXNoPath:
        return None, float('inf')
    finally:
        end_time = time.time()
        print(f"Runtime for finding shortest path: {end_time - start_time:.2f} seconds")

# Fetch road network data
road_network_data = fetch_road_network()

# Ensure road_network_data is not None before proceeding
if road_network_data is not None:
    # Create a graph from the road network data
    G = create_graph(road_network_data)

    # Define source and target nodes
    source_node = 1365149  # Replace with your actual source node
    target_node = 746839  # Replace with your actual target node

    # Find the shortest path between the source and target nodes
    path, length = find_shortest_path(G, source_node, target_node)

    if path is not None:
        print(f"The shortest path from node {source_node} to node {target_node} is: {path}")
        print(f"The length of the path is: {length}")
    else:
        print(f"No path exists between node {source_node} and node {target_node}")
else:
    print("Failed to fetch road network data.")
Editor is loading...
Leave a Comment