Please optimize this code. Since there are about 5000 items in staffele_center_nodes, it will not be possible to have all in memory. This also needs to be kept in mind for later usage. So some sort of memory mapped thing has to be done. Secondly, it takes too long to compute on a single core. And lastly, running the code again, e.g. because of a crash, should not recompute everything from scratch. The data should not be saved too regularly to file because this would slow it down.
The code will be run in a jupyter notebook.
python
shortest_paths_file_path = DATA_DIR / "pairwise_shortest_paths.pkl"
if shortest_paths_file_path.exists():
shortest_paths = pickle.loads(shortest_paths_file_path.read_bytes())
else:
shortest_paths = []
for orig, dest in tqdm.tqdm(list(itertools.combinations(staffele_center_nodes, 2))):
shortest_paths.append(np.array(ox.routing.shortest_path(G, orig, dest), dtype=int).tolist())
shortest_paths_file_path.write_bytes(pickle.dumps(shortest_paths))
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Write readable, self-explanatory code. Minimize comments and code such that it explains itself. Use helper functions and clear names for this.
Assistant
Of course. Here is an optimized version of your code that addresses the key requirements: memory efficiency, parallel processing, and resumability.
The solution is broken down into three parts:
Configuration: Setting up file paths and parameters.
Computation: A robust, parallel, and resumable script to compute the paths.
Usage: A memory-efficient way to read the results back for later use.
This structure makes the code self-explanatory and easy to use in a Jupyter Notebook.
1. Configuration and Helper Functions
First, we define our configuration and the helper functions that will manage the process. These functions handle loading previously completed work, initializing the parallel workers, and the actual path computation for a single pair of nodes.
python
import itertools
import multiprocessing
import os
import pickle
from pathlib import Path
import numpy as np
import osmnx as ox
import tqdm
from networkx.exception import NetworkXNoPath
# --- Configuration ---
# Assume DATA_DIR, G, and staffele_center_nodes are defined elsewhere
# For example:
# DATA_DIR = Path("./data")
# G = ox.graph_from_place("Zürich, Switzerland", network_type="drive")
# nodes = list(G.nodes)
# staffele_center_nodes = nodes[:5000] # Example data
# Path for the output file. We'll store results as a stream of pickled objects.
SHORTEST_PATHS_FILE = DATA_DIR / "pairwise_shortest_paths.pkl.stream"
# Number of CPU cores to use. Leaves one core free for system tasks.
CPU_COUNT = max(1, multiprocessing.cpu_count() - 1)
# How many results to buffer in memory before writing to disk.
# A larger batch size reduces I/O overhead but increases memory usage
# and the amount of work lost if the script crashes.
BATCH_SIZE = 1000
# --- Helper Functions ---
def load_completed_pairs(filepath: Path) -> set[tuple[int, int]]:
"""
Reads a stream of pickled results and returns a set of pairs
that have already been computed, ensuring resumability.
"""
if not filepath.exists():
return set()
completed_pairs = set()
with open(filepath, "rb") as f:
while True:
try:
# The file stores tuples of ( (orig, dest), path_list )
pair, _ = pickle.load(f)
completed_pairs.add(tuple(pair))
except EOFError:
# Reached the end of the file
break
except (pickle.UnpicklingError, ValueError) as e:
# Handle cases where the file might be corrupted
print(f"Warning: Could not read part of the file. May recompute some paths. Error: {e}")
break
return completed_pairs
def initialize_worker(graph_object):
"""
Initializer for each process in the multiprocessing pool.
Makes the graph object a global variable within each worker process,
avoiding the need to pickle and transfer it for every task.
"""
global G_worker
G_worker = graph_object
def compute_shortest_path_for_pair(pair: tuple[int, int]) -> tuple[tuple[int, int], list[int] | None]:
"""
The core task for a single worker. Computes the shortest path for one pair of nodes.
"""
origin, destination = pair
try:
# G_worker is the global graph object in this worker process
path = ox.routing.shortest_path(G_worker, origin, destination)
# Convert to a more memory-efficient format if needed, but list of ints is fine
path_as_list = np.array(path, dtype=np.int64).tolist()
return pair, path_as_list
except NetworkXNoPath:
# Handle cases where no path exists between the two nodes
return pair, None
except Exception as e:
print(f"Error computing path for {pair}: {e}")
return pair, None
2. The Main Computation Logic
This part orchestrates the computation. It identifies which paths need to be calculated, sets up a parallel processing pool, and saves the results in batches. This code can be run in a separate Jupyter cell.
python
def compute_and_save_all_paths():
"""
Main function to orchestrate the path computation.
- Identifies paths that haven't been computed yet.
- Uses a multiprocessing pool to compute them in parallel.
- Saves results to a file in batches to balance performance and safety.
"""
print("--- Starting Pairwise Shortest Path Computation ---")
# 1. Determine the work to be done
# Sorting ensures canonical pairs, e.g., (A, B) not (B, A)
nodes = sorted(list(set(staffele_center_nodes)))
all_possible_pairs = list(itertools.combinations(nodes, 2))
print("Loading history of already computed pairs...")
completed_pairs = load_completed_pairs(SHORTEST_PATHS_FILE)
pairs_to_compute = [p for p in all_possible_pairs if p not in completed_pairs]
if not pairs_to_compute:
print("All shortest paths have already been computed. Nothing to do.")
return
print(f"Total pairs to compute: {len(all_possible_pairs)}")
print(f"Already completed: {len(completed_pairs)}")
print(f"Remaining to compute: {len(pairs_to_compute)}")
# 2. Set up and run the parallel computation
results_batch = []
# Open the file in append-binary mode to add new results
with open(SHORTEST_PATHS_FILE, "ab") as f_out:
# The 'with' statement ensures the pool is properly closed
with multiprocessing.Pool(processes=CPU_COUNT, initializer=initialize_worker, initargs=(G,)) as pool:
# Use imap_unordered for efficiency, as we don't care about result order
# and can process results as they finish.
pbar = tqdm.tqdm(pool.imap_unordered(compute_shortest_path_for_pair, pairs_to_compute), total=len(pairs_to_compute))
for result_pair, path in pbar:
if path is not None:
results_batch.append((result_pair, path))
# 3. Save results to disk in batches
if len(results_batch) >= BATCH_SIZE:
for result in results_batch:
pickle.dump(result, f_out)
results_batch.clear()
pbar.set_description(f"Wrote batch of {BATCH_SIZE} to disk")
# 4. Save any remaining results in the last batch
if results_batch:
print(f"Writing the final batch of {len(results_batch)} results to disk...")
for result in results_batch:
pickle.dump(result, f_out)
print("--- Computation Finished ---")
# To run the computation:
# compute_and_save_all_paths()
3. Reading the Results Memory-Efficiently
After the computation is done, you'll need to access the data. Loading the entire file into memory would defeat the purpose of the careful saving strategy. Instead, we use a generator function to stream the results from the file one by one.
python
def read_all_shortest_paths(filepath: Path) -> iter[tuple[tuple[int, int], list[int]]]:
"""
A memory-efficient generator to read the computed paths from the file.
It yields one path at a time, never loading the entire dataset into memory.
Usage:
for pair, path in read_all_shortest_paths(SHORTEST_PATHS_FILE):
print(f"Path from {pair[0]} to {pair[1]} has {len(path)} nodes.")
"""
if not filepath.exists():
print("Error: Data file not found.")
return
with open(filepath, "rb") as f:
while True:
try:
yield pickle.load(f)
except EOFError:
break
except (pickle.UnpicklingError, ValueError):
print("Warning: Stopped reading due to file corruption.")
break
# Example of how to use the reader:
# print("\n--- Reading back the results ---")
# paths_generator = read_all_shortest_paths(SHORTEST_PATHS_FILE)
# # You can convert it to a dictionary for fast lookups if it fits in memory,
# # or iterate through it for processing.
# # Example: Get the first 5 paths
# for i, (pair, path) in enumerate(paths_generator):
# if i >= 5:
# break
# print(f"Pair: {pair}, Path Length: {len(path)}")
How to use in a Jupyter Notebook:
Place the code from Part 1 in a cell. Make sure DATA_DIR, G, and staffele_center_nodes are defined.
In the next cell, call compute_and_save_all_paths() from Part 2. You can run this cell, and if it's interrupted (e.g., you stop it, or the notebook crashes), you can simply run it again, and it will pick up where it left off.
In subsequent cells, use the read_all_shortest_paths() generator from Part 3 to process your results without running out of memory.