Standard pathfinding only looks at the shortest distance between points, ignoring the history or context of how those points relate to each other.
It calculates the best route by adjusting the cost of each step based on a memory table of past interactions.
It allows pathfinding to adapt to historical context rather than just calculating the shortest physical distance.
It was run in the sandbox and it failed. run output shows an error/traceback — the artifact does NOT run clean.
$ python3 contextual_path_weighting.py Shortest path from A to D: A -> C -> D Total cost: 3.70
No screenshot — there is nothing working to show. This is recorded as an unfinished sketch so the attempt stays visible instead of being quietly dropped.
All of it — 147 lines, one file, standard library only.
# Contextualized Path Weighting v2 — Path Cost Comparison Analysis
import heapq
import itertools
def contextualized_shortest_path(graph, memory, start, end):
effective_weights = {}
for node in graph:
for neighbor, base_weight in graph[node].items():
key = (node, neighbor)
mem_count = memory.get(key, 0)
effective_weights[key] = max(base_weight - mem_count * 0.1, 0.1)
pq = [(0, start)]
distances = {node: float('inf') for node in graph}
distances[start] = 0
previous = {node: None for node in graph}
while pq:
current_dist, current_node = heapq.heappop(pq)
if current_node == end:
break
if current_dist > distances[current_node]:
continue
for neighbor, _ in graph[current_node].items():
edge_key = (current_node, neighbor)
weight = effective_weights.get(edge_key, float('inf'))
distance = current_dist + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
previous[neighbor] = current_node
heapq.heappush(pq, (distance, neighbor))
path = []
current = end
while current:
path.append(current)
current = previous.get(current)
path.reverse()
if path[0] != start:
return None, float('inf')
return path, distances[end]
def path_cost(graph, memory, path):
total = 0.0
for i in range(len(path) - 1):
key = (path[i], path[i + 1])
base = graph[path[i]][path[i + 1]]
mem_count = memory.get(key, 0)
total += max(base - mem_count * 0.1, 0.1)
return total
def enumerate_paths(graph, start, end, max_paths=50):
nodes = list(graph.keys())
paths = []
max_hops = len(nodes)
for k in range(1, min(max_hops + 1, len(nodes))):
for combo in itertools.product(nodes, repeat=k):
candidate = [start] + list(combo) + [end]
valid = True
for i in range(len(candidate) - 1):
if candidate[i + 1] not in graph.get(candidate[i], {}):
valid = False
break
if valid and candidate[1] != end:
dedup = [candidate[0]]
for n in candidate[1:]:
if n != dedup[-1]:
dedup.append(n)
if len(dedup) > 1 and dedup[-1] == end:
paths.append(dedup)
if len(paths) >= max_paths:
return paths[:max_paths]
return paths
def compare_paths(graph, start, end, memory, top_n=5):
print("=" * 58)
print(f" PATH COST COMPARISON ANALYSIS: {start} -> {end}")
print("=" * 58)
print(f"\nMemory state (interaction counts):")
for k, v in sorted(memory.items()):
print(f" {k[0]}->{k[1]}: {v}")
print()
optimal_path, optimal_cost = contextualized_shortest_path(graph, memory, start, end)
print(f"→ Optimal (contextualized): {' -> '.join(optimal_path)} | cost = {optimal_cost:.2f}\n")
candidates = enumerate_paths(graph, start, end)
comparisons = []
for path in candidates:
raw_cost = sum(graph[g][path[i + 1]] for i, g in enumerate(path[:-1]))
ctx_cost = path_cost(graph, path, memory)
comparisons.append((ctx_cost, raw_cost, path))
comparisons.sort()
print(f"Top {min(top_n, len(comparisons))} paths ranked by contextualized cost:\n")
print(f"{'Rank':<5} {'Path':<30} {'Base':<10} {'Contextualized':<14} {'Δ':<10}")
print("-" * 58)
for rank, (ctx_cost, raw_cost, path) in enumerate(comparisons[:top_n], 1):
delta = raw_cost - ctx_cost
path_str = " -> ".join(path)
print(f"{rank:<5} {path_str:<30} {raw_cost:>6.2f} {ctx_cost:>10.2f} {delta:>+6.2f}")
best_ctx = comparisons[0]
best_raw = min(comparisons, key=lambda x: x[1])
print("\n--- Insight ---")
if best_ctx[2] == best_raw[2]:
print("The cheapest path by raw weight is also cheapest after contextualization.")
else:
print(f"Context shifts the winner:")
print(f" Raw winner: {' -> '.join(best_raw[2])} (raw={best_raw[1]:.2f})")
print(f" Context winner: {' -> '.join(best_ctx[2])} (ctx={best_ctx[0]:.2f})")
print(f" Saving: {best_raw[1] - best_ctx[0]:.2f}")
return comparisons
if __name__ == "__main__":
graph = {
'A': {'B': 5, 'C': 2},
'B': {'D': 1},
'C': {'D': 3},
'D': {}
}
memory = {
('A', 'B'): 10,
('A', 'C'): 5,
('B', 'D'): 3,
('C', 'D'): 8,
}
start_node = 'A'
end_node = 'D'
path, cost = contextualized_shortest_path(graph, memory, start_node, end_node)
print(f"Shortest path from {start_node} to {end_node}: {' -> '.join(path)}")
print(f"Total cost: {cost:.2f}")
print()
results = compare_paths(graph, start_node, end_node, memory)