Skip to content

Instantly share code, notes, and snippets.

@luisdelatorre012
Created September 5, 2024 11:32
Show Gist options
  • Save luisdelatorre012/fa688f8f4148ac9672be5af808adefe7 to your computer and use it in GitHub Desktop.
Save luisdelatorre012/fa688f8f4148ac9672be5af808adefe7 to your computer and use it in GitHub Desktop.
graph path

Prompt:

undefined

Response:

undefined

Prompt:

Use python for this. Whatever packags you wwant.

I have a graph. Each node has location label, and all nodes have edges between them.

I have a list of consolidations. Each consolidations has an origin node and a destination node.

I have a list of pairs. Each pair is a shipment id and a consolidation id.

For each shipment, I want to generate a path along the graph correponding to the origin and destination of consolidations and identify if these paths have cycles. The first stop of the path is arbitrary.

Response:

Certainly! I'll create a Python script to solve this problem using the NetworkX library, which is excellent for working with graphs. We'll use a few other standard Python libraries as well. Let's break this down step by step:

Graph Path Analysis Script

Click to open code

This script does the following:

  1. We define Node and Consolidation classes to represent our data structures.
  2. We create a graph using NetworkX and add nodes and edges.
  3. We generate a path for each shipment based on its consolidation.
  4. We check if the generated path has cycles.
  5. We process all shipments and return the results.

The main function process_shipments takes the graph, consolidations, and shipments as input and returns a dictionary with shipment IDs as keys and tuples of (path, has_cycle) as values.

In the example usage, we create sample data and demonstrate how to use the functions. You can modify this sample data or load your actual data to use the script.

To use this script, you'll need to install the NetworkX library:

Copypip install networkx

Would you like me to explain any part of the code in more detail or make any modifications?

Prompt:

undefined

Response:

undefined

Prompt:

undefined

Response:

undefined

Prompt:

undefined

Response:

undefined

@luisdelatorre012
Copy link
Author

import networkx as nx
from typing import List, Tuple, Dict

Define data structures

class Node:
def init(self, id: str, location: str):
self.id = id
self.location = location

class Consolidation:
def init(self, id: str, origin: str, destination: str):
self.id = id
self.origin = origin
self.destination = destination

Create graph and add nodes

def create_graph(nodes: List[Node]) -> nx.Graph:
G = nx.Graph()
for node in nodes:
G.add_node(node.id, location=node.location)
return G

Add edges to the graph (assuming all nodes are connected)

def add_edges(G: nx.Graph):
for node1 in G.nodes():
for node2 in G.nodes():
if node1 != node2:
G.add_edge(node1, node2)

Generate path for a shipment

def generate_path(G: nx.Graph, consolidations: List[Consolidation]) -> List[str]:
path = []
for cons in consolidations:
if not path:
path.append(cons.origin)
path.append(cons.destination)
return path

Check if a path has cycles

def has_cycle(path: List[str]) -> bool:
return len(path) != len(set(path))

Main function to process shipments

def process_shipments(G: nx.Graph,
consolidations: Dict[str, Consolidation],
shipments: List[Tuple[str, str]]) -> Dict[str, Tuple[List[str], bool]]:
results = {}
for shipment_id, consolidation_id in shipments:
cons = consolidations[consolidation_id]
path = generate_path(G, [cons])
cycle = has_cycle(path)
results[shipment_id] = (path, cycle)
return results

Example usage

if name == "main":
# Create sample data
nodes = [
Node("A", "New York"),
Node("B", "Los Angeles"),
Node("C", "Chicago"),
Node("D", "Houston")
]

consolidations = {
    "C1": Consolidation("C1", "A", "B"),
    "C2": Consolidation("C2", "B", "C"),
    "C3": Consolidation("C3", "C", "A")
}

shipments = [
    ("S1", "C1"),
    ("S2", "C2"),
    ("S3", "C3")
]

# Create graph
G = create_graph(nodes)
add_edges(G)

# Process shipments
results = process_shipments(G, consolidations, shipments)

# Print results
for shipment_id, (path, has_cycle) in results.items():
    print(f"Shipment {shipment_id}:")
    print(f"  Path: {' -> '.join(path)}")
    print(f"  Has cycle: {has_cycle}")
    print()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment