From b479429080acc0a69933a906b09bca77599f3c4a Mon Sep 17 00:00:00 2001
From: zhang <zc857179121@qq.com>
Date: 星期一, 03 十一月 2025 17:00:30 +0800
Subject: [PATCH] json路径文件,从excel转json的python脚本

---
 .idea/vcs.xml                            |    6 +
 .idea/modules.xml                        |    8 ++
 algorithm_system/adjacency_from_excel.py |  207 +++++++++++++++++++++++++++++++++++++++++++++++++++
 .idea/algo-python.iml                    |    9 ++
 .idea/misc.xml                           |    5 +
 5 files changed, 234 insertions(+), 1 deletions(-)

diff --git a/.idea/algo-python.iml b/.idea/algo-python.iml
new file mode 100644
index 0000000..d6ebd48
--- /dev/null
+++ b/.idea/algo-python.iml
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="JAVA_MODULE" version="4">
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$" />
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+</module>
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
index 90dee70..8f4c91f 100644
--- a/.idea/misc.xml
+++ b/.idea/misc.xml
@@ -1,4 +1,7 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <project version="4">
-  <component name="KubernetesApiProvider">{}</component>
+  <component name="KubernetesApiProvider"><![CDATA[{}]]></component>
+  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
+    <output url="file://$PROJECT_DIR$/out" />
+  </component>
 </project>
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 0000000..87c9dd9
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/.idea/algo-python.iml" filepath="$PROJECT_DIR$/.idea/algo-python.iml" />
+    </modules>
+  </component>
+</project>
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 0000000..35eb1dd
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="" vcs="Git" />
+  </component>
+</project>
\ No newline at end of file
diff --git a/algorithm_system/adjacency_from_excel.py b/algorithm_system/adjacency_from_excel.py
new file mode 100644
index 0000000..1085000
--- /dev/null
+++ b/algorithm_system/adjacency_from_excel.py
@@ -0,0 +1,207 @@
+import json
+import pandas as pd
+import os
+from datetime import datetime
+
+
+def load_edges_from_excel(excel_file):
+    """
+    浠� Excel 鏂囦欢鍔犺浇杈�
+    """
+    
+    try:
+        df = pd.read_excel(excel_file, sheet_name=0)
+        direction_col = df.columns[0]
+        start_col = df.columns[1]
+        end_col = df.columns[2]
+        
+        edges = []
+        for idx, row in df.iterrows():
+            try:
+                direction = int(row[direction_col])
+                start = str(int(row[start_col]))
+                end = str(int(row[end_col]))
+                edges.append((start, end, direction))
+            except (ValueError, TypeError):
+                continue
+        return edges
+        
+    except Exception as e:
+        print(f"error: {e}")
+        raise
+
+
+def build_adjacency_from_edges(edges, path_mapping_file):
+    """
+    鏍规嵁杈规瀯寤洪偦鎺ヨ〃
+    """
+    
+    with open(path_mapping_file, 'r', encoding='utf-8') as f:
+        pm = json.load(f)['path_id_to_coordinates']
+    
+    adjacency = {}
+    
+    for start, end, edge_direction in edges:
+        if start not in adjacency:
+            adjacency[start] = []
+        if end not in adjacency:
+            adjacency[end] = []
+        
+        # 璁$畻鏂瑰悜锛堝熀浜庡潗鏍囷級
+        direction = calculate_direction(start, end, pm)
+        reverse_direction = calculate_direction(end, start, pm)
+        
+        if edge_direction == 0:  # 鍙屽悜
+            adjacency[start].append({"code": end, "direction": direction})
+            adjacency[end].append({"code": start, "direction": reverse_direction})
+        elif edge_direction == 1:  # 姝e悜锛坰tart 鈫� end锛�
+            adjacency[start].append({"code": end, "direction": direction})
+        elif edge_direction == 2:  # 鍙嶅悜锛坋nd 鈫� start锛�
+            adjacency[end].append({"code": start, "direction": reverse_direction})
+    
+    for node in adjacency:
+        # 浣跨敤 (code, direction) 浣滀负鍞竴閿幓閲�
+        unique = {}
+        for neighbor in adjacency[node]:
+            key = neighbor['code']
+            unique[key] = neighbor
+        adjacency[node] = list(unique.values())
+    
+    print(f"閭绘帴琛ㄥ寘鍚� {len(adjacency)} 涓妭鐐�")
+    
+    total_edges = sum(len(neighbors) for neighbors in adjacency.values())
+    avg_degree = total_edges / len(adjacency) if adjacency else 0
+    
+    return adjacency
+
+
+def calculate_direction(from_id, to_id, path_mapping):
+    """
+    鏍规嵁鍧愭爣璁$畻鏂瑰悜
+    """
+    if from_id not in path_mapping or to_id not in path_mapping:
+        return "90" 
+    
+    from_coords = path_mapping[from_id]
+    to_coords = path_mapping[to_id]
+    
+    if not from_coords or not to_coords:
+        return "90"
+    
+    fx, fy = from_coords[0]['x'], from_coords[0]['y']
+    tx, ty = to_coords[0]['x'], to_coords[0]['y']
+    
+    dx = tx - fx
+    dy = ty - fy
+    
+    if abs(dx) > abs(dy):
+        if dx > 0:
+            return "0"    # 鍙�
+        else:
+            return "180"  # 宸�
+    else:
+        # 涓昏鏄瀭鐩寸Щ鍔�
+        if dy > 0:
+            return "90"   # 涓�
+        else:
+            return "270"  # 涓�
+    
+    return "90"  # 榛樿
+
+
+def save_adjacency_json(adjacency, output_file, create_backup=True):
+    """
+    淇濆瓨閭绘帴琛ㄥ埌 JSON 鏂囦欢
+    """
+    
+    try:
+        # 澶囦唤
+        if create_backup and os.path.exists(output_file):
+            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+            backup_path = f"{output_file}.backup_{timestamp}"
+            import shutil
+            shutil.copy2(output_file, backup_path)
+        
+        # 淇濆瓨
+        with open(output_file, 'w', encoding='utf-8') as f:
+            json.dump(adjacency, f, indent=2, ensure_ascii=False)
+
+        
+    except Exception as e:
+        print(f"error: {e}")
+        raise
+
+
+def verify_connectivity(adjacency, test_pairs):
+    """
+    楠岃瘉杩為�氭��
+    """
+    from collections import deque
+    
+    def bfs(start, end):
+        if start not in adjacency or end not in adjacency:
+            return False, 0
+        
+        visited = set()
+        queue = deque([(start, 0)])
+        visited.add(start)
+        
+        while queue:
+            current, dist = queue.popleft()
+            
+            if current == end:
+                return True, dist
+            
+            for neighbor in adjacency.get(current, []):
+                neighbor_id = neighbor['code']
+                if neighbor_id not in visited:
+                    visited.add(neighbor_id)
+                    queue.append((neighbor_id, dist + 1))
+        
+        return False, -1
+    
+    for start, end in test_pairs:
+        connected, distance = bfs(start, end)
+        status = "Connected" if connected else "Disconnected"
+        if connected:
+            print(f"  {start} 鈫� {end}: {status} (璺濈={distance})")
+        else:
+            print(f"  {start} 鈫� {end}: {status} (涓嶈繛閫�)")
+
+
+def main():
+    
+    excel_file = "route.xlsx"
+    path_mapping_file = "path_mapping.json"
+    output_file = "adjacency.json"
+    
+    # 妫�鏌ユ枃浠�
+    if not os.path.exists(excel_file):
+        print(f"鎵句笉鍒� {excel_file}")
+        return
+    
+    if not os.path.exists(path_mapping_file):
+        print(f"鎵句笉鍒� {path_mapping_file}")
+        return
+    
+    try:
+        edges = load_edges_from_excel(excel_file)
+        
+        if not edges:
+            print("鏈兘鎻愬彇鍒拌竟")
+            return
+
+        adjacency = build_adjacency_from_edges(edges, path_mapping_file)
+ 
+        save_adjacency_json(adjacency, output_file, create_backup=True)
+        
+    except Exception as e:
+        print(f"error: {e}")
+        import traceback
+        traceback.print_exc()
+
+
+if __name__ == "__main__":
+    main()
+
+

--
Gitblit v1.9.1