Alef1986 commited on
Commit
c90219f
·
verified ·
1 Parent(s): aa4872e

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +216 -76
src/streamlit_app.py CHANGED
@@ -10,8 +10,8 @@ import json
10
  # ==========================================
11
  st.set_page_config(page_title="ISO 15288 Analyzer", layout="wide")
12
 
13
- # CSS hacks to remove Streamlit width limits and prevent horizontal scrolling.
14
- # Width is set to 100% instead of 100vw to avoid scrollbar overlap.
15
  st.markdown("""
16
  <style>
17
  .main .block-container {
@@ -53,7 +53,7 @@ def render_mermaid(mermaid_code, nodes_json):
53
  #graphDiv {{ width: 100%; height: 100vh; cursor: grab; position: relative; }}
54
  #graphDiv:active {{ cursor: grabbing; }}
55
 
56
- /* Export button moved to the bottom-left to avoid pan-zoom controls */
57
  #toolbar {{ position: absolute; bottom: 25px; left: 25px; z-index: 100; }}
58
  button.export-btn {{
59
  background: #ffffff; border: 1px solid #ccc; padding: 10px 18px;
@@ -80,6 +80,9 @@ def render_mermaid(mermaid_code, nodes_json):
80
  #closeBtn:hover {{ color: #333; }}
81
 
82
  .node {{ cursor: pointer !important; }}
 
 
 
83
  </style>
84
 
85
  <script>
@@ -88,7 +91,6 @@ def render_mermaid(mermaid_code, nodes_json):
88
  const svg = document.querySelector('#graphDiv svg');
89
  if (!svg) return;
90
 
91
- // Save current zoom state and reset to 100% for capturing the full graph
92
  const oldZoom = window.panZoomSetup.getZoom();
93
  const oldPan = window.panZoomSetup.getPan();
94
  window.panZoomSetup.resetZoom();
@@ -99,43 +101,34 @@ def render_mermaid(mermaid_code, nodes_json):
99
  const canvas = document.createElement("canvas");
100
  const bbox = svg.getBoundingClientRect();
101
 
102
- // Multiply by 2 for high-resolution retina export
103
  canvas.width = bbox.width * 2;
104
  canvas.height = bbox.height * 2;
105
 
106
  const ctx = canvas.getContext("2d");
107
-
108
- // Fill white background before scaling
109
  ctx.fillStyle = "white";
110
  ctx.fillRect(0, 0, canvas.width, canvas.height);
111
-
112
  ctx.scale(2, 2);
113
 
114
  const img = new Image();
115
  img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData)));
116
 
117
  img.onload = function() {{
118
- // Draw the diagram
119
  ctx.drawImage(img, 0, 0);
120
 
121
- // Draw the watermark on the bottom-left corner
122
  ctx.font = "12px sans-serif";
123
  ctx.fillStyle = "#888888";
124
  const dateStr = new Date().toLocaleString('en-US');
125
  const watermarkText1 = `Diagram generated on ${{dateStr}} by the model analysis script.`;
126
  const watermarkText2 = `Script rights belong to INCOSE. Developed by Alexander Efremov.`;
127
 
128
- // Position text at the bottom, adjusting for scaled coordinates
129
  ctx.fillText(watermarkText1, 15, bbox.height - 25);
130
  ctx.fillText(watermarkText2, 15, bbox.height - 10);
131
 
132
- // Trigger download
133
  const a = document.createElement("a");
134
  a.download = "Architecture_Diagram.png";
135
  a.href = canvas.toDataURL("image/png");
136
  a.click();
137
 
138
- // Restore user's zoom and pan
139
  window.panZoomSetup.zoom(oldZoom);
140
  window.panZoomSetup.pan(oldPan);
141
  }};
@@ -151,7 +144,6 @@ def render_mermaid(mermaid_code, nodes_json):
151
  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
152
  mermaid.initialize({{ startOnLoad: false, theme: 'default', securityLevel: 'loose' }});
153
 
154
- // Map JSON data for quick name-based lookups during click events
155
  const nodeData = {nodes_json};
156
  const nodeByName = {{}};
157
  for (const key in nodeData) {{
@@ -162,7 +154,6 @@ def render_mermaid(mermaid_code, nodes_json):
162
  window.renderDiagram = async function() {{
163
  const container = document.getElementById('graphDiv');
164
 
165
- // Prevent browser scrolling ONLY when hovering over the graph
166
  container.addEventListener('wheel', function(e) {{
167
  e.preventDefault();
168
  }}, {{ passive: false }});
@@ -188,7 +179,6 @@ def render_mermaid(mermaid_code, nodes_json):
188
  if (window.panZoomSetup) window.panZoomSetup.resize();
189
  }});
190
 
191
- // Custom mouse listeners to differentiate clicks from panning
192
  let isDragging = false;
193
  let startPos = {{x: 0, y: 0}};
194
 
@@ -205,10 +195,10 @@ def render_mermaid(mermaid_code, nodes_json):
205
 
206
  container.addEventListener('mouseup', function(e) {{
207
  if (!isDragging) {{
208
- let node = e.target.closest('.node');
209
  if (node) {{
210
  let label = "";
211
- let span = node.querySelector('.nodeLabel');
212
  if (span) {{
213
  label = span.textContent.trim();
214
  }} else {{
@@ -251,13 +241,9 @@ def render_mermaid(mermaid_code, nodes_json):
251
  @st.cache_data
252
  def load_and_parse_xml(file_path):
253
  """
254
- Reads the ArchiMate Open Exchange XML and constructs two NetworkX graphs:
255
- - G_full: Contains explicit connections AND hidden reverse paths for hierarchical relationships
256
- (Composition, Aggregation, Specialization) to allow bottom-up data flow routing.
257
- - G_direct: Contains ONLY explicit input/output connections (no hierarchical routing).
258
-
259
  Returns:
260
- tuple: (G_full, G_direct, dictionary of Business Functions for the dropdown menu)
261
  """
262
  tree = ET.parse(file_path)
263
  root = tree.getroot()
@@ -265,8 +251,9 @@ def load_and_parse_xml(file_path):
265
  G_full = nx.DiGraph()
266
  G_direct = nx.DiGraph()
267
  processes = {}
 
268
 
269
- # 1. Extract nodes and descriptions
270
  for elem in root.findall('.//*'):
271
  if elem.tag.endswith('element'):
272
  n_id = elem.get('identifier')
@@ -285,8 +272,10 @@ def load_and_parse_xml(file_path):
285
 
286
  if 'BusinessFunction' in n_type:
287
  processes[n_id] = name
 
 
288
 
289
- # 2. Extract relationships and set up correct routing
290
  for rel in root.findall('.//*'):
291
  if rel.tag.endswith('relationship'):
292
  src = rel.get('source')
@@ -304,29 +293,23 @@ def load_and_parse_xml(file_path):
304
  else:
305
  G_full.add_edge(src, tgt, type=r_type, access=access)
306
 
307
- # G_direct ignores hierarchical routing capabilities
308
  if not any(x in r_type for x in ['Composition', 'Aggregation', 'Specialization']):
309
  G_direct.add_edge(src, tgt, type=r_type, access=access)
310
 
311
- # G_full gets a hidden reverse vector for data to flow upwards through objects
312
  if any(x in r_type for x in ['Composition', 'Aggregation', 'Specialization']):
313
  G_full.add_edge(tgt, src, type=r_type, access='hierarchy_reverse')
314
 
315
- return G_full, G_direct, processes
316
 
317
  # ==========================================
318
  # MODULE: Code Generation (NetworkX to Mermaid)
319
  # ==========================================
320
- def graph_to_mermaid_and_data(G_active, nodes_to_include, edges_to_include):
321
  """
322
  Translates a NetworkX subgraph into Mermaid.js syntax.
323
- Applies custom visual rules:
324
- - Translates 'Read/Write' access into 'Input/Output'.
325
- - Draws specific line types for ArchiMate hierarchy (Composition, Aggregation, Specialization)
326
- pointing from the Part to the Whole.
327
-
328
- Returns:
329
- tuple: (Mermaid string, JSON string mapping node IDs to their descriptions)
330
  """
331
  if not nodes_to_include:
332
  return "", "{}"
@@ -338,9 +321,69 @@ def graph_to_mermaid_and_data(G_active, nodes_to_include, edges_to_include):
338
  ]
339
 
340
  nodes_data = {}
 
 
341
 
342
- # Render nodes based on type
343
- for n_id in set(nodes_to_include):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  data = G_active.nodes.get(n_id, {})
345
  m_id = n_id.replace("-", "_")
346
  name = data.get("name", "Unknown").replace('"', "'")
@@ -352,12 +395,12 @@ def graph_to_mermaid_and_data(G_active, nodes_to_include, edges_to_include):
352
  else:
353
  lines.append(f' {m_id}["{name}"]:::object')
354
 
 
355
  nodes_data[m_id] = {"name": name, "doc": doc}
356
 
 
357
  added_edges = set()
358
-
359
- # Render edges based on ArchiMate types
360
- for u, v, data in edges_to_include:
361
  edge_key = (u, v)
362
  if edge_key not in added_edges:
363
  u_id = u.replace("-", "_")
@@ -365,18 +408,13 @@ def graph_to_mermaid_and_data(G_active, nodes_to_include, edges_to_include):
365
  e_type = data.get("type", "")
366
  access = data.get("access", "")
367
 
368
- # Logic 1: Rename Read/Write to Input/Output
369
  if 'Access' in e_type:
370
- if access.lower() == 'read':
371
- label = "Input"
372
- elif access.lower() == 'write':
373
- label = "Output"
374
- else:
375
- label = "Access"
376
  else:
377
  label = e_type.replace("Relationship", "").replace("archimate:", "")
378
 
379
- # Logic 2: Render proper ArchiMate relations (Arrows point from Part to Whole)
380
  if 'Composition' in e_type:
381
  lines.append(f' {v_id} == "{label}" ==> {u_id}')
382
  elif 'Aggregation' in e_type:
@@ -391,10 +429,7 @@ def graph_to_mermaid_and_data(G_active, nodes_to_include, edges_to_include):
391
  return "\n".join(lines), json.dumps(nodes_data)
392
 
393
  def get_original_edges(G_graph, path):
394
- """
395
- Filters out the technical 'hierarchy_reverse' edges from a found path
396
- so they are not drawn on the final diagram.
397
- """
398
  edges = []
399
  for i in range(len(path)-1):
400
  u, v = path[i], path[i+1]
@@ -404,46 +439,70 @@ def get_original_edges(G_graph, path):
404
  edges.append((v, u, G_graph[v][u]))
405
  return edges
406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
407
  # ==========================================
408
  # MODULE: Application Core & Event Handlers
409
  # ==========================================
410
-
411
- # 1. Load Data
412
  try:
413
  current_script_dir = os.path.dirname(os.path.abspath(__file__))
414
  xml_file_path = os.path.join(current_script_dir, "ISO15288_Archi_Import.xml")
415
 
416
- G_full, G_direct, processes = load_and_parse_xml(xml_file_path)
417
  sorted_process_names = sorted(list(processes.values()))
 
418
  except FileNotFoundError:
419
  st.error(f"File 'ISO15288_Archi_Import.xml' not found. Looked at: {xml_file_path}")
420
  st.stop()
421
 
422
- # 2. Main Interface Setup
423
  mode = st.radio(
424
  "Select analysis scenario:",
425
  (
426
  "Case 1: Interface exchange between selected processes",
427
  "Case 2: Shortest DATA FLOW path (Directed)",
428
  "Case 3: Closest STRUCTURAL connection (Undirected)",
429
- "Case 4: All possible DATA FLOW paths (Directed)"
 
 
430
  )
431
  )
432
 
433
- use_hierarchy = st.checkbox("Include derived connections (Whole-Part, Specialization hierarchy)", value=True)
 
 
 
 
434
 
435
- # Select the appropriate graph instance based on the user's hierarchy preference
436
  G_active = G_full if use_hierarchy else G_direct
437
  U_active = G_active.to_undirected()
438
 
439
  st.markdown("---")
440
 
441
- # 3. Scenario Logic Handlers
442
- if mode == "Case 1: Interface exchange between selected processes":
443
  st.write("Select 2 to 5 processes. The script will find objects they exchange data through.")
444
  selected_names = st.multiselect("Select processes:", sorted_process_names, max_selections=5)
445
 
446
- if st.button("Generate Interface Diagram") and len(selected_names) >= 2:
447
  selected_ids = [k for k, v in processes.items() if v in selected_names]
448
  nodes_to_draw = set(selected_ids)
449
  edges_to_draw = []
@@ -452,7 +511,6 @@ if mode == "Case 1: Interface exchange between selected processes":
452
  if G_active.has_edge(u, v) and G_active[u][v].get('access') != 'hierarchy_reverse':
453
  edges_to_draw.append((u, v, G_active[u][v]))
454
 
455
- # Limit search depth: 4 steps if navigating through hierarchy, 2 steps if direct connections only
456
  cutoff = 4 if use_hierarchy else 2
457
 
458
  for i in range(len(selected_ids)):
@@ -466,7 +524,6 @@ if mode == "Case 1: Interface exchange between selected processes":
466
  paths = list(nx.all_simple_paths(U_active, p1, p2, cutoff=cutoff))
467
  for path in paths:
468
  if len(path) > 2:
469
- # Verify that intermediate nodes are ONLY objects, preventing process-to-process jumping
470
  is_valid = True
471
  for n in path[1:-1]:
472
  n_type = U_active.nodes[n].get('type', '')
@@ -487,10 +544,13 @@ if mode == "Case 1: Interface exchange between selected processes":
487
  st.warning("No links or shared exchange objects found between these processes.")
488
  else:
489
  st.success("Exchange interfaces found!")
 
 
 
490
  mermaid_code, json_data = graph_to_mermaid_and_data(G_active, nodes_to_draw, edges_to_draw)
491
  render_mermaid(mermaid_code, json_data)
492
 
493
- elif mode == "Case 2: Shortest DATA FLOW path (Directed)":
494
  st.write("Finds the shortest valid data sequence (respecting Input/Output directions).")
495
  col1, col2 = st.columns(2)
496
  with col1:
@@ -498,7 +558,7 @@ elif mode == "Case 2: Shortest DATA FLOW path (Directed)":
498
  with col2:
499
  p2_name = st.selectbox("Process B (To):", sorted_process_names, key="c2_p2")
500
 
501
- if st.button("Find Directed Path") and p1_name != p2_name:
502
  p1_id = [k for k, v in processes.items() if v == p1_name][0]
503
  p2_id = [k for k, v in processes.items() if v == p2_name][0]
504
 
@@ -506,14 +566,16 @@ elif mode == "Case 2: Shortest DATA FLOW path (Directed)":
506
  path = nx.shortest_path(G_active, source=p1_id, target=p2_id)
507
  edges_in_path = get_original_edges(G_active, path)
508
 
 
 
 
509
  st.success(f"Data flow path found! Length: {len(path)-1} step(s).")
510
  mermaid_code, json_data = graph_to_mermaid_and_data(G_active, path, edges_in_path)
511
  render_mermaid(mermaid_code, json_data)
512
-
513
  except nx.NetworkXNoPath:
514
  st.error("No valid DATA FLOW exists between these processes.")
515
 
516
- elif mode == "Case 3: Closest STRUCTURAL connection (Undirected)":
517
  st.write("Finds any connection (e.g., sharing the same input document), ignoring direction.")
518
  col1, col2 = st.columns(2)
519
  with col1:
@@ -521,7 +583,7 @@ elif mode == "Case 3: Closest STRUCTURAL connection (Undirected)":
521
  with col2:
522
  p2_name = st.selectbox("Process B:", sorted_process_names, key="c3_p2")
523
 
524
- if st.button("Find Closest Connection") and p1_name != p2_name:
525
  p1_id = [k for k, v in processes.items() if v == p1_name][0]
526
  p2_id = [k for k, v in processes.items() if v == p2_name][0]
527
 
@@ -529,14 +591,16 @@ elif mode == "Case 3: Closest STRUCTURAL connection (Undirected)":
529
  path = nx.shortest_path(U_active, source=p1_id, target=p2_id)
530
  edges_in_path = get_original_edges(G_active, path)
531
 
 
 
 
532
  st.success(f"Structural connection found! Length: {len(path)-1} step(s).")
533
  mermaid_code, json_data = graph_to_mermaid_and_data(G_active, path, edges_in_path)
534
  render_mermaid(mermaid_code, json_data)
535
-
536
  except nx.NetworkXNoPath:
537
  st.error("These processes are completely disconnected in the model.")
538
 
539
- elif mode == "Case 4: All possible DATA FLOW paths (Directed)":
540
  st.write("Finds all valid data flow sequences (respecting directions).")
541
  col1, col2 = st.columns(2)
542
  with col1:
@@ -544,7 +608,7 @@ elif mode == "Case 4: All possible DATA FLOW paths (Directed)":
544
  with col2:
545
  p2_name = st.selectbox("Process B (To):", sorted_process_names, key="c4_p2")
546
 
547
- if st.button("Find All Directed Paths") and p1_name != p2_name:
548
  p1_id = [k for k, v in processes.items() if v == p1_name][0]
549
  p2_id = [k for k, v in processes.items() if v == p2_name][0]
550
 
@@ -562,9 +626,85 @@ elif mode == "Case 4: All possible DATA FLOW paths (Directed)":
562
  for path in paths:
563
  nodes_in_paths.update(path)
564
  edges_in_paths.extend(get_original_edges(G_active, path))
 
 
 
565
 
566
  mermaid_code, json_data = graph_to_mermaid_and_data(G_active, nodes_in_paths, edges_in_paths)
567
  render_mermaid(mermaid_code, json_data)
568
-
569
  except nx.NetworkXNoPath:
570
- st.error("No valid DATA FLOW exists between these processes.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  # ==========================================
11
  st.set_page_config(page_title="ISO 15288 Analyzer", layout="wide")
12
 
13
+ # CSS hacks to force the application to use the maximum screen width
14
+ # and hide the default Streamlit header.
15
  st.markdown("""
16
  <style>
17
  .main .block-container {
 
53
  #graphDiv {{ width: 100%; height: 100vh; cursor: grab; position: relative; }}
54
  #graphDiv:active {{ cursor: grabbing; }}
55
 
56
+ /* Export button bottom-left */
57
  #toolbar {{ position: absolute; bottom: 25px; left: 25px; z-index: 100; }}
58
  button.export-btn {{
59
  background: #ffffff; border: 1px solid #ccc; padding: 10px 18px;
 
80
  #closeBtn:hover {{ color: #333; }}
81
 
82
  .node {{ cursor: pointer !important; }}
83
+
84
+ /* Add pointer to subgraphs */
85
+ .cluster {{ cursor: pointer !important; }}
86
  </style>
87
 
88
  <script>
 
91
  const svg = document.querySelector('#graphDiv svg');
92
  if (!svg) return;
93
 
 
94
  const oldZoom = window.panZoomSetup.getZoom();
95
  const oldPan = window.panZoomSetup.getPan();
96
  window.panZoomSetup.resetZoom();
 
101
  const canvas = document.createElement("canvas");
102
  const bbox = svg.getBoundingClientRect();
103
 
 
104
  canvas.width = bbox.width * 2;
105
  canvas.height = bbox.height * 2;
106
 
107
  const ctx = canvas.getContext("2d");
 
 
108
  ctx.fillStyle = "white";
109
  ctx.fillRect(0, 0, canvas.width, canvas.height);
 
110
  ctx.scale(2, 2);
111
 
112
  const img = new Image();
113
  img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgData)));
114
 
115
  img.onload = function() {{
 
116
  ctx.drawImage(img, 0, 0);
117
 
 
118
  ctx.font = "12px sans-serif";
119
  ctx.fillStyle = "#888888";
120
  const dateStr = new Date().toLocaleString('en-US');
121
  const watermarkText1 = `Diagram generated on ${{dateStr}} by the model analysis script.`;
122
  const watermarkText2 = `Script rights belong to INCOSE. Developed by Alexander Efremov.`;
123
 
 
124
  ctx.fillText(watermarkText1, 15, bbox.height - 25);
125
  ctx.fillText(watermarkText2, 15, bbox.height - 10);
126
 
 
127
  const a = document.createElement("a");
128
  a.download = "Architecture_Diagram.png";
129
  a.href = canvas.toDataURL("image/png");
130
  a.click();
131
 
 
132
  window.panZoomSetup.zoom(oldZoom);
133
  window.panZoomSetup.pan(oldPan);
134
  }};
 
144
  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
145
  mermaid.initialize({{ startOnLoad: false, theme: 'default', securityLevel: 'loose' }});
146
 
 
147
  const nodeData = {nodes_json};
148
  const nodeByName = {{}};
149
  for (const key in nodeData) {{
 
154
  window.renderDiagram = async function() {{
155
  const container = document.getElementById('graphDiv');
156
 
 
157
  container.addEventListener('wheel', function(e) {{
158
  e.preventDefault();
159
  }}, {{ passive: false }});
 
179
  if (window.panZoomSetup) window.panZoomSetup.resize();
180
  }});
181
 
 
182
  let isDragging = false;
183
  let startPos = {{x: 0, y: 0}};
184
 
 
195
 
196
  container.addEventListener('mouseup', function(e) {{
197
  if (!isDragging) {{
198
+ let node = e.target.closest('.node') || e.target.closest('.cluster');
199
  if (node) {{
200
  let label = "";
201
+ let span = node.querySelector('.nodeLabel') || node.querySelector('.cluster-label');
202
  if (span) {{
203
  label = span.textContent.trim();
204
  }} else {{
 
241
  @st.cache_data
242
  def load_and_parse_xml(file_path):
243
  """
244
+ Reads the ArchiMate Open Exchange XML and constructs NetworkX graphs.
 
 
 
 
245
  Returns:
246
+ tuple: (G_full, G_direct, processes_dict, objects_dict)
247
  """
248
  tree = ET.parse(file_path)
249
  root = tree.getroot()
 
251
  G_full = nx.DiGraph()
252
  G_direct = nx.DiGraph()
253
  processes = {}
254
+ business_objects = {}
255
 
256
+ # 1. Extract nodes and categorize them
257
  for elem in root.findall('.//*'):
258
  if elem.tag.endswith('element'):
259
  n_id = elem.get('identifier')
 
272
 
273
  if 'BusinessFunction' in n_type:
274
  processes[n_id] = name
275
+ elif 'BusinessProcess' not in n_type and 'Unknown' not in n_type and 'Role' not in n_type and 'Actor' not in n_type:
276
+ business_objects[n_id] = name
277
 
278
+ # 2. Extract relationships and apply hierarchical logic
279
  for rel in root.findall('.//*'):
280
  if rel.tag.endswith('relationship'):
281
  src = rel.get('source')
 
293
  else:
294
  G_full.add_edge(src, tgt, type=r_type, access=access)
295
 
296
+ # Direct graph strictly ignores hierarchy logic
297
  if not any(x in r_type for x in ['Composition', 'Aggregation', 'Specialization']):
298
  G_direct.add_edge(src, tgt, type=r_type, access=access)
299
 
300
+ # Full graph receives hidden reverse edges for cross-level search
301
  if any(x in r_type for x in ['Composition', 'Aggregation', 'Specialization']):
302
  G_full.add_edge(tgt, src, type=r_type, access='hierarchy_reverse')
303
 
304
+ return G_full, G_direct, processes, business_objects
305
 
306
  # ==========================================
307
  # MODULE: Code Generation (NetworkX to Mermaid)
308
  # ==========================================
309
+ def graph_to_mermaid_and_data(G_active, nodes_to_include, edges_to_include, render_subgraphs=False):
310
  """
311
  Translates a NetworkX subgraph into Mermaid.js syntax.
312
+ If render_subgraphs=True, groups BusinessProcesses inside their parent BusinessFunctions.
 
 
 
 
 
 
313
  """
314
  if not nodes_to_include:
315
  return "", "{}"
 
321
  ]
322
 
323
  nodes_data = {}
324
+ parent_map = {}
325
+ filtered_edges = []
326
 
327
+ # 1. Map children to parents if subgraphs are enabled
328
+ if render_subgraphs:
329
+ for u, v, data in edges_to_include:
330
+ u_type = G_active.nodes[u].get('type', '')
331
+ v_type = G_active.nodes[v].get('type', '')
332
+
333
+ # If U (Function) is composed of V (Process)
334
+ if 'Composition' in data.get('type', '') and 'BusinessFunction' in u_type and 'BusinessProcess' in v_type:
335
+ parent_map[v] = u
336
+ else:
337
+ filtered_edges.append((u, v, data))
338
+ else:
339
+ filtered_edges = edges_to_include
340
+
341
+ # 2. Distribute nodes into subgraphs or standalone lists
342
+ children_by_parent = {}
343
+ standalone_nodes = []
344
+
345
+ for n in nodes_to_include:
346
+ if render_subgraphs and n in parent_map:
347
+ p = parent_map[n]
348
+ if p not in children_by_parent:
349
+ children_by_parent[p] = []
350
+ children_by_parent[p].append(n)
351
+ else:
352
+ standalone_nodes.append(n)
353
+
354
+ # If a parent is acting as a subgraph, remove it from standalone nodes
355
+ for p in children_by_parent.keys():
356
+ if p in standalone_nodes:
357
+ standalone_nodes.remove(p)
358
+
359
+ # 3. Draw Subgraphs
360
+ for p_id, children in children_by_parent.items():
361
+ if p_id in nodes_to_include:
362
+ p_data = G_active.nodes[p_id]
363
+ m_pid = p_id.replace("-", "_")
364
+ p_name = p_data.get("name", "Unknown").replace('"', "'")
365
+
366
+ lines.append(f' subgraph {m_pid} ["{p_name}"]')
367
+ lines.append(f' style {m_pid} fill:#FFF2CC,stroke:#D6B656,stroke-width:2px,color:#000;')
368
+
369
+ for c_id in children:
370
+ c_data = G_active.nodes[c_id]
371
+ m_cid = c_id.replace("-", "_")
372
+ c_name = c_data.get("name", "Unknown").replace('"', "'")
373
+ lines.append(f' {m_cid}("{c_name}"):::process')
374
+ lines.append(f' click {m_cid} call handleNodeClick()')
375
+ nodes_data[m_cid] = {"name": c_name, "doc": c_data.get("doc", "").replace('"', "'").replace("\n", " ")}
376
+
377
+ lines.append(f' end')
378
+ lines.append(f' click {m_pid} call handleNodeClick()')
379
+ nodes_data[m_pid] = {"name": p_name, "doc": p_data.get("doc", "").replace('"', "'").replace("\n", " ")}
380
+ else:
381
+ # Fallback if parent isn't requested but children are
382
+ for c_id in children:
383
+ standalone_nodes.append(c_id)
384
+
385
+ # 4. Draw Standalone Nodes
386
+ for n_id in standalone_nodes:
387
  data = G_active.nodes.get(n_id, {})
388
  m_id = n_id.replace("-", "_")
389
  name = data.get("name", "Unknown").replace('"', "'")
 
395
  else:
396
  lines.append(f' {m_id}["{name}"]:::object')
397
 
398
+ lines.append(f' click {m_id} call handleNodeClick()')
399
  nodes_data[m_id] = {"name": name, "doc": doc}
400
 
401
+ # 5. Draw Edges
402
  added_edges = set()
403
+ for u, v, data in filtered_edges:
 
 
404
  edge_key = (u, v)
405
  if edge_key not in added_edges:
406
  u_id = u.replace("-", "_")
 
408
  e_type = data.get("type", "")
409
  access = data.get("access", "")
410
 
 
411
  if 'Access' in e_type:
412
+ if access.lower() == 'read': label = "Input"
413
+ elif access.lower() == 'write': label = "Output"
414
+ else: label = "Access"
 
 
 
415
  else:
416
  label = e_type.replace("Relationship", "").replace("archimate:", "")
417
 
 
418
  if 'Composition' in e_type:
419
  lines.append(f' {v_id} == "{label}" ==> {u_id}')
420
  elif 'Aggregation' in e_type:
 
429
  return "\n".join(lines), json.dumps(nodes_data)
430
 
431
  def get_original_edges(G_graph, path):
432
+ """Filters out hidden 'hierarchy_reverse' edges from shortest-path results."""
 
 
 
433
  edges = []
434
  for i in range(len(path)-1):
435
  u, v = path[i], path[i+1]
 
439
  edges.append((v, u, G_graph[v][u]))
440
  return edges
441
 
442
+ def enforce_border_object_relations(G_graph, nodes_set, edges_list):
443
+ """Finds and injects structural relations between any objects present in the view."""
444
+ objects_in_graph = [n for n in nodes_set if 'BusinessProcess' not in G_graph.nodes[n].get('type','') and 'BusinessFunction' not in G_graph.nodes[n].get('type','')]
445
+ existing_edges = set((u, v) for u, v, _ in edges_list)
446
+
447
+ for i in range(len(objects_in_graph)):
448
+ for j in range(i + 1, len(objects_in_graph)):
449
+ o1, o2 = objects_in_graph[i], objects_in_graph[j]
450
+
451
+ if G_graph.has_edge(o1, o2) and G_graph[o1][o2].get('access') != 'hierarchy_reverse':
452
+ if (o1, o2) not in existing_edges:
453
+ edges_list.append((o1, o2, G_graph[o1][o2]))
454
+ existing_edges.add((o1, o2))
455
+
456
+ if G_graph.has_edge(o2, o1) and G_graph[o2][o1].get('access') != 'hierarchy_reverse':
457
+ if (o2, o1) not in existing_edges:
458
+ edges_list.append((o2, o1, G_graph[o2][o1]))
459
+ existing_edges.add((o2, o1))
460
+
461
+ return edges_list
462
+
463
  # ==========================================
464
  # MODULE: Application Core & Event Handlers
465
  # ==========================================
 
 
466
  try:
467
  current_script_dir = os.path.dirname(os.path.abspath(__file__))
468
  xml_file_path = os.path.join(current_script_dir, "ISO15288_Archi_Import.xml")
469
 
470
+ G_full, G_direct, processes, business_objects = load_and_parse_xml(xml_file_path)
471
  sorted_process_names = sorted(list(processes.values()))
472
+ sorted_object_names = sorted(list(business_objects.values()))
473
  except FileNotFoundError:
474
  st.error(f"File 'ISO15288_Archi_Import.xml' not found. Looked at: {xml_file_path}")
475
  st.stop()
476
 
477
+ # Scenario Selection
478
  mode = st.radio(
479
  "Select analysis scenario:",
480
  (
481
  "Case 1: Interface exchange between selected processes",
482
  "Case 2: Shortest DATA FLOW path (Directed)",
483
  "Case 3: Closest STRUCTURAL connection (Undirected)",
484
+ "Case 4: All possible DATA FLOW paths (Directed)",
485
+ "Case 5: Process Neighborhood & Internal Steps (Subgraphs)",
486
+ "Case 6: Shortest connection between Business Objects (Undirected)"
487
  )
488
  )
489
 
490
+ col_opt1, col_opt2 = st.columns(2)
491
+ with col_opt1:
492
+ use_hierarchy = st.checkbox("Include derived connections (Whole-Part, Specialization hierarchy)", value=True)
493
+ with col_opt2:
494
+ connect_border_objects = st.checkbox("Show relationships between boundary objects on diagram", value=True)
495
 
 
496
  G_active = G_full if use_hierarchy else G_direct
497
  U_active = G_active.to_undirected()
498
 
499
  st.markdown("---")
500
 
501
+ if mode.startswith("Case 1"):
 
502
  st.write("Select 2 to 5 processes. The script will find objects they exchange data through.")
503
  selected_names = st.multiselect("Select processes:", sorted_process_names, max_selections=5)
504
 
505
+ if st.button("Generate Diagram") and len(selected_names) >= 2:
506
  selected_ids = [k for k, v in processes.items() if v in selected_names]
507
  nodes_to_draw = set(selected_ids)
508
  edges_to_draw = []
 
511
  if G_active.has_edge(u, v) and G_active[u][v].get('access') != 'hierarchy_reverse':
512
  edges_to_draw.append((u, v, G_active[u][v]))
513
 
 
514
  cutoff = 4 if use_hierarchy else 2
515
 
516
  for i in range(len(selected_ids)):
 
524
  paths = list(nx.all_simple_paths(U_active, p1, p2, cutoff=cutoff))
525
  for path in paths:
526
  if len(path) > 2:
 
527
  is_valid = True
528
  for n in path[1:-1]:
529
  n_type = U_active.nodes[n].get('type', '')
 
544
  st.warning("No links or shared exchange objects found between these processes.")
545
  else:
546
  st.success("Exchange interfaces found!")
547
+ if connect_border_objects:
548
+ edges_to_draw = enforce_border_object_relations(G_active, nodes_to_draw, edges_to_draw)
549
+
550
  mermaid_code, json_data = graph_to_mermaid_and_data(G_active, nodes_to_draw, edges_to_draw)
551
  render_mermaid(mermaid_code, json_data)
552
 
553
+ elif mode.startswith("Case 2"):
554
  st.write("Finds the shortest valid data sequence (respecting Input/Output directions).")
555
  col1, col2 = st.columns(2)
556
  with col1:
 
558
  with col2:
559
  p2_name = st.selectbox("Process B (To):", sorted_process_names, key="c2_p2")
560
 
561
+ if st.button("Generate Diagram") and p1_name != p2_name:
562
  p1_id = [k for k, v in processes.items() if v == p1_name][0]
563
  p2_id = [k for k, v in processes.items() if v == p2_name][0]
564
 
 
566
  path = nx.shortest_path(G_active, source=p1_id, target=p2_id)
567
  edges_in_path = get_original_edges(G_active, path)
568
 
569
+ if connect_border_objects:
570
+ edges_in_path = enforce_border_object_relations(G_active, set(path), edges_in_path)
571
+
572
  st.success(f"Data flow path found! Length: {len(path)-1} step(s).")
573
  mermaid_code, json_data = graph_to_mermaid_and_data(G_active, path, edges_in_path)
574
  render_mermaid(mermaid_code, json_data)
 
575
  except nx.NetworkXNoPath:
576
  st.error("No valid DATA FLOW exists between these processes.")
577
 
578
+ elif mode.startswith("Case 3"):
579
  st.write("Finds any connection (e.g., sharing the same input document), ignoring direction.")
580
  col1, col2 = st.columns(2)
581
  with col1:
 
583
  with col2:
584
  p2_name = st.selectbox("Process B:", sorted_process_names, key="c3_p2")
585
 
586
+ if st.button("Generate Diagram") and p1_name != p2_name:
587
  p1_id = [k for k, v in processes.items() if v == p1_name][0]
588
  p2_id = [k for k, v in processes.items() if v == p2_name][0]
589
 
 
591
  path = nx.shortest_path(U_active, source=p1_id, target=p2_id)
592
  edges_in_path = get_original_edges(G_active, path)
593
 
594
+ if connect_border_objects:
595
+ edges_in_path = enforce_border_object_relations(G_active, set(path), edges_in_path)
596
+
597
  st.success(f"Structural connection found! Length: {len(path)-1} step(s).")
598
  mermaid_code, json_data = graph_to_mermaid_and_data(G_active, path, edges_in_path)
599
  render_mermaid(mermaid_code, json_data)
 
600
  except nx.NetworkXNoPath:
601
  st.error("These processes are completely disconnected in the model.")
602
 
603
+ elif mode.startswith("Case 4"):
604
  st.write("Finds all valid data flow sequences (respecting directions).")
605
  col1, col2 = st.columns(2)
606
  with col1:
 
608
  with col2:
609
  p2_name = st.selectbox("Process B (To):", sorted_process_names, key="c4_p2")
610
 
611
+ if st.button("Generate Diagram") and p1_name != p2_name:
612
  p1_id = [k for k, v in processes.items() if v == p1_name][0]
613
  p2_id = [k for k, v in processes.items() if v == p2_name][0]
614
 
 
626
  for path in paths:
627
  nodes_in_paths.update(path)
628
  edges_in_paths.extend(get_original_edges(G_active, path))
629
+
630
+ if connect_border_objects:
631
+ edges_in_paths = enforce_border_object_relations(G_active, nodes_in_paths, edges_in_paths)
632
 
633
  mermaid_code, json_data = graph_to_mermaid_and_data(G_active, nodes_in_paths, edges_in_paths)
634
  render_mermaid(mermaid_code, json_data)
 
635
  except nx.NetworkXNoPath:
636
+ st.error("No valid DATA FLOW exists between these processes.")
637
+
638
+ elif mode.startswith("Case 5"):
639
+ st.write("Shows all connected objects up to X steps away. Renders internal steps inside the function block.")
640
+
641
+ p_name = st.selectbox("Select Process (Business Function):", sorted_process_names, key="c5_p")
642
+ distance = st.radio("Search depth (steps):", (1, 2), horizontal=True)
643
+
644
+ if st.button("Generate Diagram"):
645
+ p_id = [k for k, v in processes.items() if v == p_name][0]
646
+
647
+ nodes_to_draw = set([p_id])
648
+ edges_to_draw = []
649
+
650
+ # 1. Find all internal steps (BusinessProcesses connected via Composition)
651
+ children = [v for u, v, d in G_full.out_edges(p_id, data=True) if 'Composition' in d.get('type','') and 'BusinessProcess' in G_full.nodes[v].get('type','')]
652
+ nodes_to_draw.update(children)
653
+
654
+ # 2. Extract outward neighborhood iteratively
655
+ visited = set(nodes_to_draw)
656
+ current_front = set(nodes_to_draw)
657
+
658
+ for step in range(distance):
659
+ next_front = set()
660
+ for node in current_front:
661
+ for neighbor in U_active.neighbors(node):
662
+ if neighbor not in visited:
663
+ n_type = G_full.nodes[neighbor].get('type', '')
664
+ # Expand only into Objects, not jumping into other Functions/Processes
665
+ if 'BusinessFunction' not in n_type and 'BusinessProcess' not in n_type:
666
+ next_front.add(neighbor)
667
+ visited.add(neighbor)
668
+ nodes_to_draw.update(next_front)
669
+ current_front = next_front
670
+
671
+ # 3. Collect all valid edges inside this subgraph
672
+ existing_edges = set()
673
+ for u in nodes_to_draw:
674
+ for v in nodes_to_draw:
675
+ if G_active.has_edge(u, v) and G_active[u][v].get('access') != 'hierarchy_reverse':
676
+ edges_to_draw.append((u, v, G_active[u][v]))
677
+ existing_edges.add((u, v))
678
+
679
+ if connect_border_objects:
680
+ edges_to_draw = enforce_border_object_relations(G_active, nodes_to_draw, edges_to_draw)
681
+
682
+ st.success(f"Neighborhood built with radius {distance}.")
683
+ # Use render_subgraphs=True to draw internal steps inside the main Function
684
+ mermaid_code, json_data = graph_to_mermaid_and_data(G_active, nodes_to_draw, edges_to_draw, render_subgraphs=True)
685
+ render_mermaid(mermaid_code, json_data)
686
+
687
+ elif mode.startswith("Case 6"):
688
+ st.write("Finds any connection between two Business Objects, ignoring direction.")
689
+ col1, col2 = st.columns(2)
690
+ with col1:
691
+ o1_name = st.selectbox("Object A:", sorted_object_names, key="c6_o1")
692
+ with col2:
693
+ o2_name = st.selectbox("Object B:", sorted_object_names, key="c6_o2")
694
+
695
+ if st.button("Generate Diagram") and o1_name != o2_name:
696
+ o1_id = [k for k, v in business_objects.items() if v == o1_name][0]
697
+ o2_id = [k for k, v in business_objects.items() if v == o2_name][0]
698
+
699
+ try:
700
+ path = nx.shortest_path(U_active, source=o1_id, target=o2_id)
701
+ edges_in_path = get_original_edges(G_active, path)
702
+
703
+ if connect_border_objects:
704
+ edges_in_path = enforce_border_object_relations(G_active, set(path), edges_in_path)
705
+
706
+ st.success(f"Connection found! Length: {len(path)-1} step(s).")
707
+ mermaid_code, json_data = graph_to_mermaid_and_data(G_active, path, edges_in_path)
708
+ render_mermaid(mermaid_code, json_data)
709
+ except nx.NetworkXNoPath:
710
+ st.error("These objects are completely disconnected in the model.")