alle Weiche in 2D mit M und mit P ohne TEF sind korrigiert und in 2D Wizard eingepflegt.

This commit is contained in:
2025-07-11 17:41:18 +02:00
parent e760ab7a55
commit 1910b46ffa
370 changed files with 10217 additions and 2864 deletions
@@ -47,9 +47,9 @@ def process_json_item(item):
scale = round(1000 / item["Objekt_width_mm"], 7)
item["calculated_SVG_width_px"] = 1000
if item["Winkel"]==180:
item["calculated_SVG_height_px"] = round(item["Objekt_height_mm"] * scale+3.78/2, 3)
item["calculated_SVG_height_px"] = round(item["Objekt_height_mm"] * scale+3.7795/2, 3)
else:
item["calculated_SVG_height_px"] = round(item["Objekt_height_mm"] * scale+3.78/2/sin_value, 3)
item["calculated_SVG_height_px"] = round(item["Objekt_height_mm"] * scale+3.7795/2/sin_value, 3)
scale_RD_H = round(1000 / item["calculated_SVG_height_px"], 6)
scale_RD_W = 1
else:
@@ -57,9 +57,9 @@ def process_json_item(item):
scale = round(1000 / item["Objekt_height_mm"], 7)
item["calculated_SVG_height_px"] = 1000
if item["Winkel"]==180:
item["calculated_SVG_width_px"] = round(item["Objekt_width_mm"] * scale+3.78/2, 3)
item["calculated_SVG_width_px"] = round(item["Objekt_width_mm"] * scale+3.7795/2, 3)
else:
item["calculated_SVG_width_px"] = round(item["Objekt_width_mm"] * scale+3.78/2/cos_value, 3)
item["calculated_SVG_width_px"] = round(item["Objekt_width_mm"] * scale+3.7795/2/cos_value, 3)
scale_RD_W = round(1000 / item["calculated_SVG_width_px"], 6)
scale_RD_H = 1
@@ -132,7 +132,7 @@
"Objekt_width_px": 1974.947,
"Objekt_height_px": 614.951,
"calculated_SVG_width_px": 1000,
"calculated_SVG_height_px": 316.315,
"calculated_SVG_height_px": 316.314,
"scale_factor": 1.9137218,
"connectionPoints": [
{
@@ -144,7 +144,7 @@
{
"id": "cp2",
"x": 984.593,
"y": 866.791,
"y": 866.794,
"direction": 112.5
}
]
@@ -162,7 +162,7 @@
"Objekt_width_px": 1974.947,
"Objekt_height_px": 614.951,
"calculated_SVG_width_px": 1000,
"calculated_SVG_height_px": 316.315,
"calculated_SVG_height_px": 316.314,
"scale_factor": 1.9137218,
"connectionPoints": [
{
@@ -174,7 +174,7 @@
{
"id": "cp2",
"x": 984.593,
"y": 866.791,
"y": 866.794,
"direction": 112.5
}
]
@@ -252,7 +252,7 @@
"Objekt_width_px": 2306.032,
"Objekt_height_px": 1141.084,
"calculated_SVG_width_px": 1000,
"calculated_SVG_height_px": 497.499,
"calculated_SVG_height_px": 497.498,
"scale_factor": 1.6389627,
"connectionPoints": [
{
@@ -264,7 +264,7 @@
{
"id": "cp2",
"x": 975.617,
"y": 945.619,
"y": 945.621,
"direction": 135.0
}
]
@@ -432,7 +432,7 @@
"Objekt_width_px": 3327.816,
"Objekt_height_px": 1271.707,
"calculated_SVG_width_px": 1000,
"calculated_SVG_height_px": 384.818,
"calculated_SVG_height_px": 384.817,
"scale_factor": 1.13573,
"connectionPoints": [
{
@@ -444,7 +444,7 @@
{
"id": "cp2",
"x": 983.103,
"y": 949.149,
"y": 949.152,
"direction": 135.0
}
]
@@ -462,7 +462,7 @@
"Objekt_width_px": 3327.816,
"Objekt_height_px": 1271.707,
"calculated_SVG_width_px": 1000,
"calculated_SVG_height_px": 384.818,
"calculated_SVG_height_px": 384.817,
"scale_factor": 1.13573,
"connectionPoints": [
{
@@ -474,7 +474,7 @@
{
"id": "cp2",
"x": 983.103,
"y": 949.149,
"y": 949.152,
"direction": 135.0
}
]
@@ -552,7 +552,7 @@
"Objekt_width_px": 2687.376,
"Objekt_height_px": 3292.096,
"calculated_SVG_height_px": 1000,
"calculated_SVG_width_px": 3.0866042377540064e+16,
"calculated_SVG_width_px": 3.0861959567701764e+16,
"scale_factor": 1.1480529,
"connectionPoints": [
{
@@ -582,7 +582,7 @@
"Objekt_width_px": 3292.096,
"Objekt_height_px": 3367.686,
"calculated_SVG_height_px": 1000,
"calculated_SVG_width_px": 3.0866042377540224e+16,
"calculated_SVG_width_px": 3.0861959567701924e+16,
"scale_factor": 1.1222841,
"connectionPoints": [
{
@@ -1,6 +1,6 @@
import json
import math
import os
def modify_json_values(json_file):
# Constant definitions
WeichenKoerperWidth = 32.5437
@@ -15,7 +15,7 @@ def modify_json_values(json_file):
process_doppelweiche_items(data, BogenProfileWidth, WeichenGerade)
process_dreifachweiche_items(data, WeichenkProfileWidth)
process_deltaweiche_items(data, WeichenkProfileWidth)
# Ask for save confirmation
save_choice = input("\nSave all changes? (Press Enter to save, 'n' to cancel): ").lower()
if save_choice == 'n':
@@ -80,39 +80,39 @@ def process_einzelweiche_items(data,WeichenKoerperWidth, WeichenkProfileWidth,Bo
angle_rad = math.radians(item["KurvenWinkel"])
# Calculate and print basic values
old_width = item.get("Objekte_width_mm")
item["Objekte_width_mm"] = round(WeichenKoerperWidth+
old_width = item.get("Objekt_width_mm")
item["Objekt_width_mm"] = round(WeichenKoerperWidth+
(BogenProfileWidth/2 * math.cos(angle_rad)) +
item["OFWeiche_center_line_width_mm"] +
WeichenkProfileWidth/2, 3)
print(f"\nObjekte_width_mm calculated update: {old_width}{item['Objekte_width_mm']}")
print(f"\nObjekt_width_mm calculated update: {old_width}{item['Objekt_width_mm']}")
old_height = item.get("Objekte_height_mm")
old_height = item.get("Objekt_height_mm")
if item["KurvenWinkel"] == 22.5:
item["Objekte_height_mm"] = round(
item["Objekt_height_mm"] = round(
item["OFWeiche_center_line_height_mm"], 3)
else:
item["Objekte_height_mm"] = round(
item["Objekt_height_mm"] = round(
(BogenProfileWidth/2 * math.sin(angle_rad)) +
item["OFWeiche_center_line_height_mm"], 3)
print(f"Objekte_height_mm calculated update: {old_height}{item['Objekte_height_mm']}")
print(f"Objekt_height_mm calculated update: {old_height}{item['Objekt_height_mm']}")
# Calculate and print CP point coordinates
old_cp1x = item.get("OFWeiche_CP1_x_mm")
item["OFWeiche_CP1_x_mm"] = round(
(BogenProfileWidth/2 * math.sin(angle_rad)) +
(BogenProfileWidth/2 * math.cos(angle_rad)) +
item["OFWeiche_center_line_width_mm"], 3)
print(f"OFWeiche_CP1_x_mm calculated update: {old_cp1x}{item['OFWeiche_CP1_x_mm']}")
old_cp1y = item.get("OFWeiche_CP1_y_mm")
item["OFWeiche_CP1_y_mm"] = round(
item["Objekte_height_mm"] - WeichenGerade, 3)
item["Objekt_height_mm"] - WeichenGerade, 3)
print(f"OFWeiche_CP1_y_mm calculated update: {old_cp1y}{item['OFWeiche_CP1_y_mm']}")
item["OFWeiche_CP2_x_mm"] = round(item["OFWeiche_CP1_x_mm"], 3)
print(f"OFWeiche_CP2_x_mm set: {item['OFWeiche_CP2_x_mm']}")
item["OFWeiche_CP2_y_mm"] = round(item["Objekte_height_mm"], 3)
item["OFWeiche_CP2_y_mm"] = round(item["Objekt_height_mm"], 3)
print(f"OFWeiche_CP2_y_mm set: {item['OFWeiche_CP2_y_mm']}")
item["OFWeiche_CP3_x_mm"] = round(
@@ -145,8 +145,8 @@ def process_einzelweiche_items(data,WeichenKoerperWidth, WeichenkProfileWidth,Bo
fields_to_copy = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm",
"Objekt_width_mm",
"Objekt_height_mm",
"OFWeiche_CP1_x_mm",
"OFWeiche_CP1_y_mm",
"OFWeiche_CP2_x_mm",
@@ -182,8 +182,8 @@ def process_einzelweiche_items(data,WeichenKoerperWidth, WeichenkProfileWidth,Bo
base_fields = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm"
"Objekt_width_mm",
"Objekt_height_mm"
]
for field in base_fields:
@@ -197,14 +197,14 @@ def process_einzelweiche_items(data,WeichenKoerperWidth, WeichenkProfileWidth,Bo
print(f" OFWeiche_CP1_x_mm (R-type): {old_cp1x}{similar['OFWeiche_CP1_x_mm']}")
old_cp1y = similar.get("OFWeiche_CP1_y_mm")
similar["OFWeiche_CP1_y_mm"] = round(item["Objekte_height_mm"] - WeichenGerade, 3)
similar["OFWeiche_CP1_y_mm"] = round(item["Objekt_height_mm"] - WeichenGerade, 3)
print(f" OFWeiche_CP1_y_mm (R-type): {old_cp1y}{similar['OFWeiche_CP1_y_mm']}")
similar["OFWeiche_CP2_x_mm"] = similar["OFWeiche_CP1_x_mm"]
print(f" OFWeiche_CP2_x_mm (R-type): Set to {similar['OFWeiche_CP2_x_mm']}")
old_cp2y = similar.get("OFWeiche_CP2_y_mm")
similar["OFWeiche_CP2_y_mm"] = round(item["Objekte_height_mm"], 3)
similar["OFWeiche_CP2_y_mm"] = round(item["Objekt_height_mm"], 3)
print(f" OFWeiche_CP2_y_mm (R-type): {old_cp2y}{similar['OFWeiche_CP2_y_mm']}")
old_cp3x = similar.get("OFWeiche_CP3_x_mm")
@@ -233,8 +233,8 @@ def process_einzelweiche_items(data,WeichenKoerperWidth, WeichenkProfileWidth,Bo
fields_to_copy_r_p = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm",
"Objekt_width_mm",
"Objekt_height_mm",
"OFWeiche_CP1_x_mm",
"OFWeiche_CP1_y_mm",
"OFWeiche_CP2_x_mm",
@@ -317,24 +317,24 @@ def process_doppelweiche_items(data,BogenProfileWidth, WeichenGerade):
angle_rad = math.radians(item["KurvenWinkel"])
# Calculate and print basic values (Doppelweiche specific formula)
old_width = item.get("Objekte_width_mm")
item["Objekte_width_mm"] = round(
old_width = item.get("Objekt_width_mm")
item["Objekt_width_mm"] = round(
(BogenProfileWidth/2 * math.cos(angle_rad)) +
item["OFWeiche_center_line_width_mm"] +
BogenProfileWidth/2 * math.cos(angle_rad), 3)
print(f"\nObjekte_width_mm calculated update: {old_width}{item['Objekte_width_mm']}")
print(f"\nObjekt_width_mm calculated update: {old_width}{item['Objekt_width_mm']}")
old_height = item.get("Objekte_height_mm")
item["Objekte_height_mm"] = round(
old_height = item.get("Objekt_height_mm")
item["Objekt_height_mm"] = round(
(BogenProfileWidth/2 * math.sin(angle_rad)) +
item["OFWeiche_center_line_height_mm"], 3)
print(f"Objekte_height_mm calculated update: {old_height}{item['Objekte_height_mm']}")
print(f"Objekt_height_mm calculated update: {old_height}{item['Objekt_height_mm']}")
# Calculate and print CP point coordinates (Doppelweiche specific formula)
item["OFWeiche_CP1_x_mm"] = round(item["Objekte_width_mm"]/2, 3)
item["OFWeiche_CP1_x_mm"] = round(item["Objekt_width_mm"]/2, 3)
print(f"OFWeiche_CP1_x_mm calculated update: {item['OFWeiche_CP1_x_mm']}")
item["OFWeiche_CP1_y_mm"] = round(item["Objekte_height_mm"], 3)
item["OFWeiche_CP1_y_mm"] = round(item["Objekt_height_mm"], 3)
print(f"OFWeiche_CP1_y_mm calculated update: {item['OFWeiche_CP1_y_mm']}")
item["OFWeiche_CP2_x_mm"] = round(BogenProfileWidth/2 * math.cos(angle_rad), 3)
@@ -369,8 +369,8 @@ def process_doppelweiche_items(data,BogenProfileWidth, WeichenGerade):
fields_to_copy = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm",
"Objekt_width_mm",
"Objekt_height_mm",
"OFWeiche_CP1_x_mm",
"OFWeiche_CP1_y_mm",
"OFWeiche_CP2_x_mm",
@@ -409,16 +409,16 @@ def process_doppelweiche_items(data,BogenProfileWidth, WeichenGerade):
similar["OFWeiche_center_line_height_mm"] = WeichenGerade
print(f" OFWeiche_center_line_height_mm: → {WeichenGerade}")
similar["Objekte_width_mm"] = item["Objekte_width_mm"]
print(f" Objekte_width_mm: → {similar['Objekte_width_mm']}")
similar["Objekt_width_mm"] = item["Objekt_width_mm"]
print(f" Objekt_width_mm: → {similar['Objekt_width_mm']}")
similar["Objekte_height_mm"] = WeichenGerade
print(f" Objekte_height_mm: → {WeichenGerade}")
similar["Objekt_height_mm"] = WeichenGerade
print(f" Objekt_height_mm: → {WeichenGerade}")
similar["OFWeiche_CP1_x_mm"] = item["OFWeiche_CP1_x_mm"]
print(f" OFWeiche_CP1_x_mm: → {similar['OFWeiche_CP1_x_mm']}")
similar["OFWeiche_CP1_y_mm"] = similar["Objekte_height_mm"]
similar["OFWeiche_CP1_y_mm"] = similar["Objekt_height_mm"]
print(f" OFWeiche_CP1_y_mm: → {similar['OFWeiche_CP1_y_mm']}")
similar["OFWeiche_CP2_x_mm"] = item["OFWeiche_CP2_x_mm"]
@@ -438,8 +438,8 @@ def process_doppelweiche_items(data,BogenProfileWidth, WeichenGerade):
base_fields = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm",
"Objekt_width_mm",
"Objekt_height_mm",
"OFWeiche_CP1_x_mm",
"OFWeiche_CP1_y_mm",
"OFWeiche_CP2_x_mm",
@@ -454,10 +454,10 @@ def process_doppelweiche_items(data,BogenProfileWidth, WeichenGerade):
print(f" {field}: {old_val}{similar[field]}")
# Add CP4 point (T-type specific)
similar["OFWeiche_CP4_x_mm"] = round(item["Objekte_width_mm"]/2, 3)
similar["OFWeiche_CP4_x_mm"] = round(item["Objekt_width_mm"]/2, 3)
print(f" OFWeiche_CP4_x_mm added: {similar['OFWeiche_CP4_x_mm']}")
similar["OFWeiche_CP4_y_mm"] = round(item["Objekte_height_mm"] - WeichenGerade, 3)
similar["OFWeiche_CP4_y_mm"] = round(item["Objekt_height_mm"] - WeichenGerade, 3)
print(f" OFWeiche_CP4_y_mm added: {similar['OFWeiche_CP4_y_mm']}")
# 3. Find T-type P-type counterparts
@@ -477,8 +477,8 @@ def process_doppelweiche_items(data,BogenProfileWidth, WeichenGerade):
fields_to_copy_t_p = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm",
"Objekt_width_mm",
"Objekt_height_mm",
"OFWeiche_CP1_x_mm",
"OFWeiche_CP1_y_mm",
"OFWeiche_CP2_x_mm",
@@ -505,20 +505,20 @@ def process_doppelweiche_items(data,BogenProfileWidth, WeichenGerade):
print("No T-type P-type counterparts found")
else:
print("No T-type M-type similar items found")
def process_dreifachweiche_items(data, WeichenkProfileWidth):
# Filter Dreifachweiche type items
def process_deltaweiche_items(data, WeichenkProfileWidth):
# Filter deltaweiche type items
filtered_items = [
item for item in data
if (item.get("WeichenTyp") == "Dreifachweiche" and
item.get("Schaltungstyp") == "M" and
item.get("SivasnrTEF") is None)
]
item for item in data
if (item.get("WeichenTyp") == "Dreifachweiche" and
item.get("Schaltungstyp") == "M" and
item.get("SivasnrTEF") is None)
]
print(f"\n\nFound {len(filtered_items)} Dreifachweiche type records")
print(f"\n\nFound {len(filtered_items)} deltaweiche type records")
print("="*50)
for idx, item in enumerate(filtered_items, 1):
print(f"\nDreifachweiche item {idx}:")
print(f"\ndeltaweiche item {idx}:")
print(f"Sivasnr: {item['Sivasnr']}")
print(f"ProfilTyp: {item['ProfilTyp']}")
@@ -553,14 +553,14 @@ def process_dreifachweiche_items(data, WeichenkProfileWidth):
item["OFWeiche_center_line_height_mm"] is not None):
# Calculate basic dimensions
item["Objekte_width_mm"] = round(item["OFWeiche_center_line_width_mm"], 3)
print(f"\nObjekte_width_mm calculated update: {item['Objekte_width_mm']}")
item["Objekt_width_mm"] = round(item["OFWeiche_center_line_width_mm"], 3)
print(f"\nObjekt_width_mm calculated update: {item['Objekt_width_mm']}")
item["Objekte_height_mm"] = round(WeichenkProfileWidth/2 + item["OFWeiche_center_line_height_mm"], 3)
print(f"Objekte_height_mm calculated update: {item['Objekte_height_mm']}")
item["Objekt_height_mm"] = round(WeichenkProfileWidth/2 + item["OFWeiche_center_line_height_mm"]+32.5437, 3)
print(f"Objekt_height_mm calculated update: {item['Objekt_height_mm']}")
# Calculate control points
item["OFWeiche_CP1_x_mm"] = round(item["Objekte_width_mm"]/2, 3)
item["OFWeiche_CP1_x_mm"] = round(item["Objekt_width_mm"]/2, 3)
item["OFWeiche_CP1_y_mm"] = 0
item["OFWeiche_CP2_x_mm"] = 0
item["OFWeiche_CP2_y_mm"] = round(item["OFWeiche_center_line_height_mm"], 3)
@@ -575,7 +575,7 @@ def process_dreifachweiche_items(data, WeichenkProfileWidth):
# Find similar items (P-type)
if "WEICHE S C DELTA" in item["ProfilTyp"]:
similar_profil = item["ProfilTyp"].replace("KPL. M", "KPL. P")
similar_profil = item["ProfilTyp"].replace("KPL. MIT M", "KPL. MIT P")
similar_items = [x for x in data
if x["ProfilTyp"] == similar_profil and
@@ -589,8 +589,8 @@ def process_dreifachweiche_items(data, WeichenkProfileWidth):
fields_to_copy = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm",
"Objekt_width_mm",
"Objekt_height_mm",
"OFWeiche_CP1_x_mm",
"OFWeiche_CP1_y_mm",
"OFWeiche_CP2_x_mm",
@@ -616,5 +616,7 @@ def process_dreifachweiche_items(data, WeichenkProfileWidth):
print("No similar P-type items found")
if __name__ == "__main__":
json_file_path = "omniflo_weichen.json" # Replace with your JSON file path
modify_json_values(json_file_path)
json_path = os.environ.get("JSON_PATH", "JSON")
input_filename = os.path.join(json_path, "omniflo_weichen.json")
modify_json_values(input_filename)
@@ -0,0 +1,135 @@
import json
import os
def process_json_file(input_file, output_file):
# 确保输出目录存在
os.makedirs(os.path.dirname(output_file), exist_ok=True)
# 检查输入文件是否存在
if not os.path.exists(input_file):
raise FileNotFoundError(f"输入文件不存在: {input_file}")
# 加载JSON数据
with open(input_file, 'r', encoding='utf-8') as f:
data = json.load(f)
# Process each item in the JSON data
for item in data:
if item.get("SivasnrTEF") is None:
# Step 1: Calculate pixel dimensions
width_mm = item["Objekt_width_mm"]
height_mm = item["Objekt_height_mm"]
# Calculate initial pixel values
item["Objekt_width_px"] = round(width_mm * 3.7795, 3)
item["Objekt_height_px"] = round(height_mm * 3.7795, 3)
# Determine which dimension is larger and calculate scaling factor
if width_mm >= height_mm:
scale = 1000 / width_mm
item["calculated_SVG_width_px"] = 1000.0
item["calculated_SVG_height_px"] = round(height_mm * scale, 3)
scale_RD_H = round(1000 / item["calculated_SVG_height_px"],6)
scale_RD_W = 1
else:
scale = 1000 / height_mm
item["calculated_SVG_width_px"] = round(width_mm * scale, 3)
item["calculated_SVG_height_px"] = 1000.0
scale_RD_W = round(1000 / item["calculated_SVG_width_px"], 6)
scale_RD_H = 1
item["scale_factor"] = round(scale, 6)
item["scale_factor_RD_Width"] = round(scale_RD_W, 6)
item["scale_factor_RD_Height"] = round(scale_RD_H, 6)
# Process connection points
connection_points = []
# CP1
cp1_x = round(item["OFWeiche_CP1_x_mm"] * scale*scale_RD_W, 3)
cp1_y = round(item["OFWeiche_CP1_y_mm"] * scale*scale_RD_H, 3)
# CP2
cp2_x = round(item["OFWeiche_CP2_x_mm"] * scale*scale_RD_W, 3)
cp2_y = round(item["OFWeiche_CP2_y_mm"] * scale*scale_RD_H, 3)
# CP3
cp3_x = round(item["OFWeiche_CP3_x_mm"] * scale*scale_RD_W, 3)
cp3_y = round(item["OFWeiche_CP3_y_mm"] * scale*scale_RD_H, 3)
# Determine directions based on WeichenTyp
weichen_typ = item["WeichenTyp"]
kurven_winkel = item["KurvenWinkel"]
profil_typ = item["ProfilTyp"]
if weichen_typ == "Einzelweiche":
cp1_dir = 0.0
cp2_dir = 180.0
if "-L-" in profil_typ:
cp3_dir = round(360 - kurven_winkel, 1)
elif "--" in profil_typ:
cp3_dir = round(kurven_winkel, 1)
else:
cp3_dir = 0.0 # Default if pattern not found
elif weichen_typ == "Doppelweiche":
cp1_dir = 180.0
cp2_dir = round(360 - kurven_winkel, 1)
cp3_dir = round(kurven_winkel, 1)
elif weichen_typ == "Dreiwegeweiche":
cp1_dir = 180.0
cp2_dir = round(360 - kurven_winkel, 1)
cp3_dir = round(kurven_winkel, 1)
# CP4 exists for Dreiwegeweiche
cp4_x = round(item["OFWeiche_CP4_x_mm"] * scale*scale_RD_W, 3)
cp4_y = round(item["OFWeiche_CP4_y_mm"] * scale*scale_RD_H, 3)
cp4_dir = 90.0
connection_points.append({
"id": "cp4",
"x": cp4_x,
"y": cp4_y,
"direction": cp4_dir
})
elif weichen_typ == "Dreifachweiche":
cp1_dir = 0
cp2_dir = round(360 - kurven_winkel, 1)
cp3_dir = round(kurven_winkel, 1)
# Add common connection points
connection_points.extend([
{
"id": "cp1",
"x": cp1_x,
"y": cp1_y,
"direction": cp1_dir
},
{
"id": "cp2",
"x": cp2_x,
"y": cp2_y,
"direction": cp2_dir
},
{
"id": "cp3",
"x": cp3_x,
"y": cp3_y,
"direction": cp3_dir
}
])
item["connectionPoints"] = connection_points
# Save the processed data
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
if __name__ == "__main__":
json_path = os.environ.get("JSON_PATH", "JSON")
input_filename = os.path.join(json_path, "omniflo_weichen.json")
output_filename = os.path.join(json_path, "omniflo_weichen_output.json")
try:
process_json_file(input_filename, output_filename)
print(f"Process is finished , the File is saved as: {output_filename}")
except Exception as e:
print(f"Errno: {str(e)}")
@@ -0,0 +1,191 @@
''' Script Analysis
This Python script processes JSON and TXT files to update dimensions and connection points in SVG-related data, but only for entries where SivasnrTEF is null. Here's the main logic:
Input Handling:
Reads a JSON file containing reference data
Processes all TXT files in a specified directory
Data Processing:
Creates a mapping between Sivasnr (from filenames) and JSON data (only for entries with SivasnrTEF = null)
For each matching TXT file:
Updates width and height based on JSON data (converting mm to px)
Updates connection points (x, y, direction) from JSON data
Preserves the original file structure while updating specific values
Reporting:
Prints detailed change reports to console
Skips files without matching JSON data or where SivasnrTEF is not null '''
import json
import os
import glob
from datetime import datetime
def process_files(json_file_path, txt_files_dir):
# Create a log file with timestamp
if not os.path.exists(json_file_path):
print(f"Error: JSON file does not exist at {json_file_path}")
exit(1)
if not os.path.exists(txt_files_dir):
print(f"Error: Directory does not exist at {txt_files_dir}")
exit(1)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
log_file_path = os.path.join(txt_files_dir, f"modification_report_OFWeiche_{timestamp}.txt")
# Read JSON file
with open(json_file_path, 'r', encoding='utf-8') as f:
json_data = json.load(f)
# Create Sivasnr to JSON data mapping ONLY for items with SivasnrTEF = null
sivasnr_mapping = {str(item["Sivasnr"]): item for item in json_data if item["SivasnrTEF"] is None}
# Initialize counters
total_files = 0
processed_files = 0
skipped_files = 0
skipped_due_to_tef = 0
# Prepare report content
report_content = []
report_content.append(f"Modification Report - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report_content.append(f"JSON Reference File: {json_file_path}")
report_content.append(f"TXT Files Directory: {txt_files_dir}")
report_content.append("Processing only files where SivasnrTEF is null")
report_content.append(f"Total JSON entries with SivasnrTEF=null: {len(sivasnr_mapping)}")
report_content.append("="*50 + "\n")
# Process all TXT files
for txt_file_path in glob.glob(os.path.join(txt_files_dir, '*.txt')):
total_files += 1
filename = os.path.basename(txt_file_path)
sivasnr = os.path.splitext(filename)[0]
# Check if corresponding JSON data exists and SivasnrTEF is null
if sivasnr in sivasnr_mapping:
json_item = sivasnr_mapping[sivasnr]
try:
# Read TXT file content
with open(txt_file_path, 'r', encoding='utf-8-sig') as f:
txt_content = json.load(f)
# Record old values
old_width = txt_content["width"]
old_height = txt_content["height"]
old_cps = {cp["id"]: {"x": cp["x"], "y": cp["y"], "direction": cp["direction"]}
for cp in txt_content["connectionPoints"]}
# Update width and height (using direct pixel values now)
new_width = round(json_item["Objekt_width_px"], 3)
new_height = round(json_item["Objekt_height_px"], 3)
txt_content["width"] = new_width
txt_content["height"] = new_height
# Update connectionPoints
cp_changes = []
for cp in txt_content["connectionPoints"]:
cp_id = cp["id"]
# Find corresponding connection point in JSON data
json_cp = next((item for item in json_item["connectionPoints"] if item["id"] == cp_id), None)
if json_cp:
# Record old values
old_x = cp["x"]
old_y = cp["y"]
old_dir = cp["direction"]
# Update values
cp["x"] = json_cp["x"]
cp["y"] = json_cp["y"]
cp["direction"] = json_cp["direction"]
# Record changes
cp_changes.append({
"id": cp_id,
"x": (old_x, cp["x"]),
"y": (old_y, cp["y"]),
"direction": (old_dir, cp["direction"])
})
# Write back to TXT file
with open(txt_file_path, 'w', encoding='utf-8') as f:
json.dump(txt_content, f, indent=2, ensure_ascii=False)
# Print success message to console
print(f"\nSuccessfully processed file: {filename}")
print("[Dimension Changes]")
print(f"width: {old_width}{new_width}")
print(f"height: {old_height}{new_height}")
if cp_changes:
print("\n[Connection Point Changes]")
for change in cp_changes:
print(f"Connection point {change['id']}:")
print(f" x: {change['x'][0]}{change['x'][1]}")
print(f" y: {change['y'][0]}{change['y'][1]}")
print(f" direction: {change['direction'][0]}{change['direction'][1]}")
print("="*50)
# Add to report
file_entry = []
file_entry.append(f"\nProcessing file: {filename}")
file_entry.append("="*50)
file_entry.append("[Dimension Changes]")
file_entry.append(f"width: {old_width}{new_width}")
file_entry.append(f"height: {old_height}{new_height}")
if cp_changes:
file_entry.append("\n[Connection Point Changes]")
for change in cp_changes:
file_entry.append(f"Connection point {change['id']}:")
file_entry.append(f" x: {change['x'][0]}{change['x'][1]}")
file_entry.append(f" y: {change['y'][0]}{change['y'][1]}")
file_entry.append(f" direction: {change['direction'][0]}{change['direction'][1]}")
processed_files += 1
file_entry.append(f"\nFile processed successfully")
file_entry.append("="*50)
report_content.extend(file_entry)
except Exception as e:
report_content.append(f"\nError processing file {filename}: {str(e)}")
else:
skipped_files += 1
# Check if the file was skipped because SivasnrTEF is not null
matching_json_items = [item for item in json_data if str(item["Sivasnr"]) == sivasnr]
if matching_json_items and matching_json_items[0]["SivasnrTEF"] is not None:
skipped_due_to_tef += 1
# Add processing statistics to report
report_content.append("\n" + "="*50)
report_content.append("Processing Statistics:")
report_content.append(f"Total TXT files found: {total_files}")
report_content.append(f"Total JSON records available: {len(json_data)}")
report_content.append(f"JSON records with SivasnrTEF = null: {len(sivasnr_mapping)}")
report_content.append(f"Successfully processed: {processed_files}")
report_content.append(f"Skipped files (no match): {skipped_files - skipped_due_to_tef}")
report_content.append(f"Skipped files (SivasnrTEF not null): {skipped_due_to_tef}")
if len(sivasnr_mapping) > 0:
success_rate = (processed_files / len(sivasnr_mapping)) * 100
report_content.append(f"Success rate: {success_rate:.2f}%")
report_content.append("="*50)
# Print final statistics to console
print("\n" + "="*50)
print("Processing Complete - Summary Statistics:")
print(f"Successfully processed files: {processed_files}")
print(f"Total files found in directory: {total_files}")
if len(sivasnr_mapping) > 0:
print(f"Success rate: {success_rate:.2f}%")
print("="*50)
print(f"Detailed report saved to: {log_file_path}")
# Write the report file
with open(log_file_path, 'w', encoding='utf-8') as f:
f.write("\n".join(report_content))
if __name__ == "__main__":
json_path = os.environ.get("JSON_PATH", "JSON")
json_file_path = os.path.join(json_path, "omniflo_weichen_output.json")
txt_files_dir = r"C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\props"
process_files(json_file_path, txt_files_dir)
@@ -0,0 +1,125 @@
import os
import json
import re
import shutil
def extract_sivasnr_from_svg(filename):
"""
Extracts the sivasnr (numeric ID) from the SVG filename.
Example: "DeltaWeiche_1400_700_M_834372400.svg""834372400"
"""
match = re.search(r'_(\d+)\.svg$', filename)
return match.group(1) if match else None
def convert_svg_to_xml(svg_path, output_folder):
"""
Converts an SVG file to an XML file (renames it) and saves it in `output_folder`.
Returns the relative path in the format: "SSG/shapes/svg/{sivasnr}.xml"
"""
os.makedirs(output_folder, exist_ok=True)
sivasnr = extract_sivasnr_from_svg(os.path.basename(svg_path))
if not sivasnr:
raise ValueError(f"Could not extract sivasnr from SVG: {svg_path}")
xml_filename = f"{sivasnr}.xml"
xml_relative_path = f"SSG/shapes/svg/{xml_filename}" # Format: "SSG/shapes/svg/834372400.xml"
xml_abs_path = os.path.join(output_folder, xml_filename)
# Copy SVG to XML (same content, just renamed)
shutil.copy2(svg_path, xml_abs_path)
return xml_relative_path # Return the relative path for TXT file
def update_txt_srcsvg(txt_path, new_srcsvg_value):
"""
Updates the "srcSVG" field in a TXT file with the relative path.
Format: "SSG/shapes/svg/{sivasnr}.xml"
"""
try:
with open(txt_path, 'r', encoding='utf-8') as f:
data = json.load(f)
data["srcSVG"] = new_srcsvg_value # Write the relative path
with open(txt_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4, ensure_ascii=False)
return True
except Exception as e:
print(f"❌ Failed to update {txt_path}: {str(e)}")
return False
def process_svg_files(svg_folder, prorps_folder, output_folder="shapes/svg"):
"""
Processes all SVG files:
1. Extracts sivasnr.
2. Converts SVG to XML in `output_folder`.
3. Updates the TXT file with "SSG/shapes/svg/{sivasnr}.xml".
"""
if not os.path.exists(svg_folder):
print(f"❌ Error: SVG folder not found: {svg_folder}")
return
if not os.path.exists(prorps_folder):
print(f"❌ Error: Prorps folder not found: {prorps_folder}")
return
os.makedirs(output_folder, exist_ok=True)
svg_files = [f for f in os.listdir(svg_folder) if f.endswith('.svg')]
total_files = len(svg_files)
success_count = 0
failed_count = 0
print(f"\n🔍 Found {total_files} SVG files in: {svg_folder}")
print(f"📂 TXT files will be read from: {prorps_folder}")
print(f"💾 XML files will be saved to: {output_folder}\n")
for svg_filename in svg_files:
svg_path = os.path.join(svg_folder, svg_filename)
sivasnr = extract_sivasnr_from_svg(svg_filename)
if not sivasnr:
print(f"❌ Skipping {svg_filename}: Could not extract sivasnr.")
failed_count += 1
continue
print(f"🔄 Processing: {svg_filename} (sivasnr={sivasnr})")
try:
# Step 1: Convert SVG to XML and get relative path
xml_relative_path = convert_svg_to_xml(svg_path, output_folder)
print(f" ✅ Converted to XML: {xml_relative_path}")
# Step 2: Update TXT file with relative path
txt_path = os.path.join(prorps_folder, f"{sivasnr}.txt")
if not os.path.exists(txt_path):
print(f" ❌ TXT file not found: {os.path.basename(txt_path)}")
failed_count += 1
continue
if update_txt_srcsvg(txt_path, xml_relative_path):
print(f" ✅ Updated TXT: {os.path.basename(txt_path)}")
success_count += 1
else:
failed_count += 1
except Exception as e:
print(f" ❌ Error processing {svg_filename}: {str(e)}")
failed_count += 1
# Print summary
print("\n📊 Processing Summary:")
print(f" - Total SVG files: {total_files}")
print(f" - Successfully processed: {success_count}")
print(f" - Failed: {failed_count}")
if total_files > 0:
print(f" - Success rate: {(success_count / total_files) * 100:.2f}%")
if __name__ == "__main__":
# Configuration - modify these paths as needed
SVG_FOLDER = r"C:\Users\y.wang\Documents\SSG-Ruledesigner-Konfigurator\SVGs\Omniflo\Weichen\outputdir" # Folder containing SVG files
PRORPS_FOLDER = r"C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\props" # Folder containing txt files
OUTPUT_FOLDER = r"C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\svg"
# Start processing
process_svg_files(SVG_FOLDER, PRORPS_FOLDER, OUTPUT_FOLDER)
print("\nProcessing complete.")
@@ -0,0 +1,150 @@
"""
SVG XML Batch Modifier Script
This script:
1. Reads a JSON array of items
2. For each item, extracts the "Sivasnr" value
3. Locates and modifies the corresponding XML file
4. Provides comprehensive reporting
"""
import json
import os
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement, tostring
def process_xml_file(xml_path):
"""
Process a single XML file with proper namespace handling
Returns modification statistics
"""
try:
tree = ET.parse(xml_path)
root = tree.getroot()
# Register and handle SVG namespace
ET.register_namespace('', 'http://www.w3.org/2000/svg')
namespaces = {'svg': 'http://www.w3.org/2000/svg'}
stats = {
'ffe31b_groups': 0,
'ec2525_groups': 0,
'elements_modified': 0,
'modified': False
}
# Process all group elements
for g in root.findall('.//svg:g', namespaces):
stroke = g.get('stroke')
if stroke == "#ffe31b":
stats['ffe31b_groups'] += 1
if 'stroke-width' in g.attrib:
del g.attrib['stroke-width']
stats['modified'] = True
if 'stroke-miterlimit' in g.attrib:
del g.attrib['stroke-miterlimit']
stats['modified'] = True
for child in g.findall('.//svg:path', namespaces):
child.set('stroke-width', '1px')
stats['elements_modified'] += 1
stats['modified'] = True
elif stroke == "#ec2525":
stats['ec2525_groups'] += 1
for attr in ['stroke', 'stroke-width', 'stroke-linejoin']:
if attr in g.attrib:
del g.attrib[attr]
stats['modified'] = True
for child in g.findall('.//svg:path[@stroke-width="1px"]', namespaces):
del child.attrib['stroke-width']
child.set('style', 'stroke:#ec2525;stroke-width:2px')
stats['elements_modified'] += 1
stats['modified'] = True
# Save changes if modified
if stats['modified']:
xml_str = ET.tostring(root, encoding='unicode')
xml_str = xml_str.replace('><', '>\n<').replace('</svg>', '\n</svg>')
with open(xml_path, 'w', encoding='utf-8') as f:
f.write(xml_str)
return stats
except Exception as e:
print(f" Error processing file: {str(e)}")
return None
def main():
"""
Main processing function
"""
json_path=os.environ.get("JSON_PATH","JSON")
json_file_path = os.path.join(json_path,"omniflo_weichen_output.json")
svg_folder_path = os.environ.get("XML_PATH","svg")
try:
# Read and parse JSON file
with open(json_file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
# Verify we have a list of items
if not isinstance(data, list):
print("Error: JSON data should be an array of items")
return
print(f"\nFound {len(data)} items in JSON file")
# Process each item in the JSON array
for index, item in enumerate(data, 1):
if not isinstance(item, dict):
print(f"\nItem {index}: Not a dictionary, skipping")
continue
sivasnr = item.get("Sivasnr")
if not sivasnr:
print(f"\nItem {index}: Missing 'Sivasnr' value, skipping")
continue
print(f"\nProcessing item {index}: Sivasnr = {sivasnr}")
# Build XML filename and path
xml_filename = f"{sivasnr}.xml"
xml_path = os.path.join(svg_folder_path, xml_filename)
if not os.path.exists(xml_path):
print(f" XML file not found: {xml_path}")
continue
print(f" Found XML file: {xml_path}")
# Process the XML file
stats = process_xml_file(xml_path)
if stats is None:
print(" Processing failed")
elif stats['modified']:
print(" File successfully modified")
print(f" - #ffe31b groups: {stats['ffe31b_groups']}")
print(f" - #ec2525 groups: {stats['ec2525_groups']}")
print(f" - Elements modified: {stats['elements_modified']}")
else:
print(" No modifications needed")
print("\nProcessing complete")
except FileNotFoundError:
print("\nError: JSON file not found")
except json.JSONDecodeError:
print("\nError: Invalid JSON format")
except Exception as e:
print(f"\nUnexpected error: {str(e)}")
if __name__ == "__main__":
print("SVG XML Batch Modifier - Starting execution")
main()
@@ -0,0 +1,69 @@
import json
import os
import xml.etree.ElementTree as ET
def process_json_and_modify_xml(json_file_path, xml_folder_path):
# Initialize counter for total modifications
total_modified = 0
# Read JSON file
with open(json_file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
# Process each item in JSON data
for item in data:
if isinstance(item, dict) and (item.get("WeichenTyp") == "Einzelweiche" or item.get("WeichenTyp") == "Dreifachweiche") :
sivasnr = item.get("Sivasnr")
if sivasnr:
xml_file_name = f"{sivasnr}.xml"
xml_file_path = os.path.join(xml_folder_path, xml_file_name)
if os.path.exists(xml_file_path):
try:
# Register SVG namespace and parse XML
ET.register_namespace('', 'http://www.w3.org/2000/svg')
tree = ET.parse(xml_file_path)
root = tree.getroot()
file_modified_count = 0
# Find all path elements recursively
for path in root.iter('{http://www.w3.org/2000/svg}path'):
# Check for target attributes
if (path.get('stroke') == "none" and
path.get('stroke-width') == "1px" ):
# Remove original attributes
for attr in ['stroke', 'stroke-width', 'fill']:
if attr in path.attrib:
del path.attrib[attr]
# Set new style attribute
path.set('style', 'stroke:none;fill:none;')
file_modified_count += 1
total_modified += 1
if file_modified_count > 0:
# Save with proper formatting
xml_str = ET.tostring(root, encoding='unicode')
xml_str = xml_str.replace('><', '>\n<')
with open(xml_file_path, 'w', encoding='utf-8') as xml_file:
xml_file.write(xml_str)
print(f"Successfully modified {file_modified_count} path(s) in: {xml_file_name}")
else:
print(f"No target paths found in: {xml_file_name}")
except Exception as e:
print(f"Error processing {xml_file_name}: {str(e)}")
else:
print(f"XML file not found: {xml_file_name}")
# Print total modifications summary
print(f"\nTotal paths modified across all files: {total_modified}")
if __name__ == "__main__":
json_file_path = r"C:\Users\y.wang\Documents\SSG-Ruledesigner-Konfigurator\SVGs\Omniflo\python\OFWeiche\JSON\omniflo_weichen_output.json"
xml_folder_path = r"C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\svg"
process_json_and_modify_xml(json_file_path, xml_folder_path)
-17
View File
@@ -1,17 +0,0 @@
import json
# 1. 读取 JSON 文件
with open("omniflo_weichen.json", "r", encoding="utf-8") as f:
data = json.load(f) # data 是一个列表(数组)
# 2. 遍历并清理数据
for item in data:
if isinstance(item, dict) and item.get("SivasnrTEF") is None:
item.pop("TEFWeiche_center_line_width_mm", None) # 安全删除,键不存在时不报错
item.pop("TEFWeiche_center_line_height_mm", None)
item.pop("TEFWeiche_CP1_x_mm", None) # 安全删除,键不存在时不报错
item.pop("TEFWeiche_CP1_y_mm", None)
# 3. 保存修改后的 JSON
with open("omniflo_weichen.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False) # 保持中文/特殊字符
File diff suppressed because it is too large Load Diff
@@ -1,57 +0,0 @@
import json
def check_null_fields_in_items_with_sivasnrtef_null(json_file_path):
try:
with open(json_file_path, 'r', encoding='utf-8') as file:
data = json.load(file)
except FileNotFoundError:
print(f"Error: The file '{json_file_path}' does not exist.")
return
except json.JSONDecodeError:
print(f"Error: The file '{json_file_path}' is not a valid JSON file.")
return
if not isinstance(data, list):
print("Error: The JSON file should contain an array of objects.")
return
items_with_sivasnrtef_null = [item for item in data if isinstance(item, dict) and item.get("SivasnrTEF") is None]
if not items_with_sivasnrtef_null:
print("No items with 'SivasnrTEF': null found in the JSON file.")
return
# 初始化统计计数器
count_only_sivasnrtef_null = 0
count_with_other_nulls = 0
print(f"Found {len(items_with_sivasnrtef_null)} item(s) with 'SivasnrTEF': null")
print("-" * 50)
for idx, item in enumerate(items_with_sivasnrtef_null, 1):
null_fields = [key for key, value in item.items() if value is None and key != "SivasnrTEF"]
# 打印关键识别信息
sivasnr = item.get("Sivasnr", "Not found")
profil_typ = item.get("ProfilTyp", "Not found")
print(f"\nItem {idx}: Sivasnr='{sivasnr}', ProfilTyp='{profil_typ}'")
if null_fields:
count_with_other_nulls += 1
print(f" → Other null fields: {null_fields}")
print(" → Full item:", item)
else:
count_only_sivasnrtef_null += 1
print(" → No other null fields found.")
# 打印统计结果
print("\n" + "="*50)
print("Statistics:")
print(f"- Items with ONLY 'SivasnrTEF' as null: {count_only_sivasnrtef_null}")
print(f"- Items with 'SivasnrTEF' AND other null fields: {count_with_other_nulls}")
print("="*50)
# Example usage:
json_file_path = "omniflo_weichen.json" # Replace with your JSON file path
check_null_fields_in_items_with_sivasnrtef_null(json_file_path)
@@ -0,0 +1,12 @@
@echo off
set OFWeiche_PATH=%~dp0
set XML_PATH=C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\svg
set JSON_PATH=%OFWeiche_PATH%JSON
python 5_OFWeiche_SVG_XML_Modifier_Script.py
pause
@@ -0,0 +1,15 @@
@echo off
set "OFWeiche_PATH=%~dp0"
set PROPS_PATH=C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\props
set "JSON_PATH=%OFWeiche_PATH%JSON"
echo "[DEBUG] OFWeiche_PATH: %OFWeiche_PATH%"
echo "[DEBUG] PROPS_PATH: %PROPS_PATH%"
echo "[DEBUG] JSON_PATH: %JSON_PATH%"
python 1_omniflo_weichen.py
python 2_calculations_to_standardize_the_dimensions_and_add_connection_points.py
python 3_update_dimensions_and_connection_points_in_props.py
pause