-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1183 lines (954 loc) · 49.1 KB
/
main.py
File metadata and controls
1183 lines (954 loc) · 49.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import platform
import numpy as np
import pandas as pd
import networkx as nx
import itertools
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QPushButton, QComboBox, QSpinBox, QLineEdit, QTableWidget,
QTableWidgetItem, QTabWidget, QMessageBox, QFileDialog, QDialog, QColorDialog, QSizePolicy)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
# Packaging graphviz
if platform.system() == 'Windows':
# Determine base path (whether running from PyInstaller bundle or not)
if getattr(sys, 'frozen', False): # running as a bundled executable
base_path = sys._MEIPASS
else:
base_path = os.path.dirname(__file__)
# Point to the Graphviz 'bin' directory inside the bundled data
graphviz_bin = os.path.join(base_path, 'graphviz', 'bin')
# Temporarily prepend the Graphviz bin path to PATH
os.environ["PATH"] = graphviz_bin + os.pathsep + os.environ["PATH"]
from graphviz import Digraph
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import io
import shutil
from PIL import Image
class GraphEditorApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Утилита для структурного анализа")
self.setGeometry(100, 100, 1200, 800)
self.graph = nx.DiGraph()
self.weighted = False
self.electrical_circuit = False
self.current_matrix_type = None
self.vertex_count = 0
dot_path = shutil.which('dot')
self.use_graphviz = False
if dot_path:
self.use_graphviz = True
self.connection_edits = None
self.node_probability_edits = None
# Цвета по умолчанию
self.color_settings = {
'node_colors': {
'Висячая': '#90EE90', # lightgreen
'Тупиковая': '#F08080', # lightcoral
'Изолированная': '#A9A9A9', # gray
'Внутренняя': '#ADD8E6' # lightblue
},
'matrix_colors': {
'1': '#90EE90', # lightgreen
'-1': '#F08080', # lightcoral
'0': '#FFFFFF' # white
}
}
self.init_ui()
def init_ui(self):
# Central widget and main layout
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QHBoxLayout(central_widget)
# Left panel for controls
left_panel = QWidget()
left_layout = QVBoxLayout(left_panel)
left_layout.setAlignment(Qt.AlignTop)
# Graph type selection
self.graph_type_combo = QComboBox()
self.graph_type_combo.addItems(["Обычный граф", "Взвешенный граф", "Схема цепи"])
left_layout.addWidget(QLabel("Тип графа:"))
left_layout.addWidget(self.graph_type_combo)
# Graph creation options
self.create_graph_button = QPushButton("Создать граф")
self.create_graph_button.clicked.connect(
lambda: self.start_text_editor(None)) # self.show_graph_creation_dialog)
left_layout.addWidget(self.create_graph_button)
# Edit graph button
self.edit_graph_button = QPushButton("Редактировать граф")
self.edit_graph_button.clicked.connect(self.edit_current_graph)
left_layout.addWidget(self.edit_graph_button)
left_layout.addWidget(QLabel("Операции с любым графом:"))
self.find_paths_button = QPushButton("Поиск путей от точки до точки")
self.find_paths_button.clicked.connect(self.show_path_search_dialog)
left_layout.addWidget(self.find_paths_button)
left_layout.addWidget(QLabel("Операции с обычным или взвешанным графом:"))
self.vertex_rank_button = QPushButton("Ранг вершин")
self.vertex_rank_button.clicked.connect(self.calculate_vertex_rank)
left_layout.addWidget(self.vertex_rank_button)
self.structure_diameter_button = QPushButton("Диаметр структуры")
self.structure_diameter_button.clicked.connect(self.calculate_structure_diameter)
left_layout.addWidget(self.structure_diameter_button)
self.structure_complexity_button = QPushButton("Сложность структуры")
self.structure_complexity_button.clicked.connect(self.calculate_structure_complexity)
left_layout.addWidget(self.structure_complexity_button)
# Graph operations
left_layout.addWidget(QLabel("Операции с взвешенным графом:"))
self.network_weight_button = QPushButton("Вес сети")
self.network_weight_button.clicked.connect(self.calculate_network_weight)
left_layout.addWidget(self.network_weight_button)
self.vertex_weight_button = QPushButton("Вес вершин")
self.vertex_weight_button.clicked.connect(self.calculate_vertex_weights)
left_layout.addWidget(self.vertex_weight_button)
# Graph operations
left_layout.addWidget(QLabel("Операции со схеммой цепи:"))
self.reliability_button = QPushButton("Надежность")
self.reliability_button.clicked.connect(self.calculate_reliability)
left_layout.addWidget(self.reliability_button)
# Import/Export buttons
left_layout.addWidget(QLabel("Импорт/Экспорт:"))
self.import_excel_button = QPushButton("Импорт из Excel")
self.import_excel_button.clicked.connect(self.import_from_excel)
left_layout.addWidget(self.import_excel_button)
self.export_excel_button = QPushButton("Экспорт в Excel")
self.export_excel_button.clicked.connect(self.export_to_excel)
left_layout.addWidget(self.export_excel_button)
self.export_image_button = QPushButton("Экспорт графа как изображение")
self.export_image_button.clicked.connect(self.export_graph_image)
left_layout.addWidget(self.export_image_button)
# Color settings
left_layout.addWidget(QLabel("Настройки цветов:"))
self.node_colors_button = QPushButton("Цвета типов вершин")
self.node_colors_button.clicked.connect(self.configure_node_colors)
left_layout.addWidget(self.node_colors_button)
self.matrix_colors_button = QPushButton("Цвета значений матрицы")
self.matrix_colors_button.clicked.connect(self.configure_matrix_colors)
left_layout.addWidget(self.matrix_colors_button)
# Right panel for graph visualization and matrix
right_panel = QTabWidget()
self.graph_tab = QWidget()
self.adjacency_tab = QWidget()
self.incidence_tab = QWidget()
self.weight_tab = QWidget()
# Graph visualization
self.figure = Figure()
self.canvas = FigureCanvas(self.figure)
graph_layout = QVBoxLayout(self.graph_tab)
graph_layout.addWidget(self.canvas)
# Matrix displays
self.adjacency_table = QTableWidget()
adjacency_layout = QVBoxLayout(self.adjacency_tab)
adjacency_layout.addWidget(self.adjacency_table)
self.incidence_table = QTableWidget()
incidence_layout = QVBoxLayout(self.incidence_tab)
incidence_layout.addWidget(self.incidence_table)
self.weight_table = QTableWidget()
weight_layout = QVBoxLayout(self.weight_tab)
weight_layout.addWidget(self.weight_table)
right_panel.addTab(self.graph_tab, "Граф")
right_panel.addTab(self.adjacency_tab, "Матрица смежности")
right_panel.addTab(self.incidence_tab, "Матрица инцидентности")
right_panel.addTab(self.weight_tab, "Весовая матрица")
# Add panels to main layout
main_layout.addWidget(left_panel, stretch=1)
main_layout.addWidget(right_panel, stretch=3)
# Disable buttons initially
self.toggle_buttons(False)
def toggle_buttons(self, enabled):
"""Enable or disable operation buttons based on graph existence"""
self.find_paths_button.setEnabled(enabled)
self.network_weight_button.setEnabled(enabled and self.weighted)
self.vertex_weight_button.setEnabled(enabled and self.weighted)
self.vertex_rank_button.setEnabled(enabled)
self.structure_complexity_button.setEnabled(enabled)
self.structure_diameter_button.setEnabled(enabled)
self.reliability_button.setEnabled(enabled and self.electrical_circuit)
self.export_excel_button.setEnabled(enabled)
self.export_image_button.setEnabled(enabled)
self.node_colors_button.setEnabled(enabled)
self.matrix_colors_button.setEnabled(enabled)
self.edit_graph_button.setEnabled(enabled)
self.import_excel_button.setEnabled(True) # Always enabled
def edit_current_graph(self):
"""Edit the current graph"""
if not self.graph.nodes():
QMessageBox.warning(self, "Ошибка", "Нет графа для редактирования")
return
# Set the combo box to current graph type
if self.electrical_circuit:
self.graph_type_combo.setCurrentText("Схема цепи")
elif self.weighted:
self.graph_type_combo.setCurrentText("Взвешенный граф")
else:
self.graph_type_combo.setCurrentText("Обычный граф")
# Prepare the text editor with current connections
self.show_connections_dialog(None)
def import_from_excel(self):
"""Import graph from Excel file"""
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, "Импорт из Excel", "",
"Excel Files (*.xlsx);;All Files (*)",
options=options)
if not file_name:
return
try:
# Read Excel file
xls = pd.ExcelFile(file_name)
# Determine graph type based on sheets
if "Весовая матрица" in xls.sheet_names:
self.weighted = True
self.electrical_circuit = False
self.graph_type_combo.setCurrentText("Взвешенный граф")
sheet_name = "Весовая матрица"
has_weights = True
elif "Матрица смежности" in xls.sheet_names:
self.weighted = False
self.electrical_circuit = False
sheet_name = "Матрица смежности"
has_weights = False
else:
QMessageBox.warning(self, "Ошибка", "Не удалось определить тип графа из файла")
return
# Read the main sheet
df = pd.read_excel(xls, sheet_name=sheet_name, index_col=0)
if 'Вероятность' in df.axes[1]:
self.electrical_circuit = True
# Create new graph
self.graph = nx.DiGraph()
# Add nodes
nodes = df.index.tolist()
for node in nodes:
self.graph.add_node(node)
# Add edges
for i, row in df.iterrows():
for j, value in row.items():
if j == 'Тип вершины' or j == 'Топологический анализ' or j == 'Вероятность':
continue
if pd.notna(value) and value != 0 and str(value) != '0':
if has_weights:
self.graph.add_edge(i, j, weight=float(value))
else:
self.graph.add_edge(i, j)
# Handle electrical circuit probabilities
if self.electrical_circuit and 'Вероятность' in df.columns:
for i, row in df.iterrows():
probability = row.get('Вероятность', 1.0)
if pd.notna(probability):
self.graph.nodes[i]['probability'] = float(probability)
elif self.electrical_circuit:
for i in range(len(self.graph.nodes)):
node_id = i + 1
self.graph.nodes[node_id]['probability'] = 1.0
# Update UI
self.draw_graph(self.graph)
self.update_all_matrices()
self.toggle_buttons(True)
QMessageBox.information(self, "Успех", "Граф успешно импортирован")
except Exception as e:
QMessageBox.warning(self, "Ошибка", f"Ошибка при импорте графа: {str(e)}")
def show_graph_creation_dialog(self):
"""Show dialog for graph creation method selection"""
dialog = QDialog(self)
dialog.setWindowTitle("Создание графа")
layout = QVBoxLayout(dialog)
label = QLabel("Выберите метод создания графа:")
layout.addWidget(label)
# visual_button = QPushButton("Визуальный редактор")
# visual_button.clicked.connect(lambda: self.start_visual_editor(dialog))
# layout.addWidget(visual_button)
text_button = QPushButton("Описание связей")
text_button.clicked.connect(lambda: self.start_text_editor(dialog))
layout.addWidget(text_button)
dialog.exec_()
def start_visual_editor(self, dialog):
"""Start visual graph editor"""
dialog.close()
QMessageBox.information(self, "Визуальный редактор",
"Визуальный редактор будет реализован в полной версии приложения.")
def start_text_editor(self, dialog):
"""Start text-based graph editor"""
if dialog:
dialog.close()
self.weighted = self.graph_type_combo.currentText() in "Взвешенный граф"
self.electrical_circuit = self.graph_type_combo.currentText() in "Схема цепи"
self.show_vertex_count_dialog()
def show_vertex_count_dialog(self):
"""Show dialog to enter number of vertices"""
dialog = QDialog(self)
dialog.setWindowTitle("Количество вершин")
layout = QVBoxLayout(dialog)
label = QLabel("Введите количество вершин:")
layout.addWidget(label)
self.vertex_count_spin = QSpinBox()
self.vertex_count_spin.setMinimum(1)
self.vertex_count_spin.setMaximum(30)
layout.addWidget(self.vertex_count_spin)
ok_button = QPushButton("OK")
def show_connections():
self.vertex_count = self.vertex_count_spin.value()
self.show_connections_dialog(dialog)
ok_button.clicked.connect(lambda: show_connections())
layout.addWidget(ok_button)
dialog.exec_()
def show_connections_dialog(self, prev_dialog):
"""Show dialog to enter connections for each vertex"""
if prev_dialog:
prev_dialog.close()
num_vertices = self.vertex_count if self.vertex_count > 0 else len(self.graph.nodes)
dialog = QDialog(self)
dialog.setWindowTitle("Описание связей")
layout = QVBoxLayout(dialog)
instructions = QLabel("Для каждой вершины укажите через запятую номера вершин, в которые она ведет.\n"
"Пример: для вершины 1, которая ведет в вершины 2 и 3, введите: 2, 3\n"
"Для взвешенного графа укажите вес после двоеточия: 2:0.5, 3:10\n"
"Для схеммы цепи укажите P (вероятноть) в крайнем текстовом поле\n")
instructions.setWordWrap(True)
layout.addWidget(instructions)
self.connection_edits = []
self.node_probability_edits = []
for i in range(1, num_vertices + 1):
form_layout = QHBoxLayout()
label = QLabel(f"Вершина {i}:")
form_layout.addWidget(label)
edit = QLineEdit()
self.connection_edits.append(edit)
if self.electrical_circuit:
# Create a container widget for the two line edits
container = QWidget()
container_layout = QHBoxLayout(container)
container_layout.setContentsMargins(0, 0, 0, 0)
# Main connection edit (70% width)
edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
container_layout.addWidget(edit, stretch=7)
p_label = QLabel(f"P:")
container_layout.addWidget(p_label)
# Additional weight edit (30% width)
weight_edit = QLineEdit()
weight_edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
self.node_probability_edits.append(weight_edit)
container_layout.addWidget(weight_edit, stretch=3)
form_layout.addWidget(container)
else:
form_layout.addWidget(edit)
layout.addLayout(form_layout)
if not prev_dialog:
# Pre-fill the connection fields with current graph data
num_vertices = len(self.graph.nodes)
for i in range(num_vertices):
node = i + 1
edges = []
for neighbor in self.graph.successors(node):
if self.weighted:
weight = self.graph[node][neighbor].get('weight', '')
edges.append(f"{neighbor}:{weight}")
else:
edges.append(str(neighbor))
self.connection_edits[i].setText(", ".join(edges))
if self.electrical_circuit:
probability = self.graph.nodes[node].get('probability', '')
self.node_probability_edits[i].setText(str(probability))
preview_button = QPushButton("Предпросмотр графа")
preview_button.clicked.connect(lambda: self.preview_graph(dialog))
layout.addWidget(preview_button)
apply_button = QPushButton("Применить")
apply_button.clicked.connect(lambda: self.create_graph_from_text(dialog))
layout.addWidget(apply_button)
dialog.exec_()
def preview_graph(self, dialog):
"""Show graph preview without saving"""
try:
num_vertices = self.vertex_count if self.vertex_count > 0 else len(self.graph.nodes)
temp_graph = nx.DiGraph()
for i in range(num_vertices):
connections = self.connection_edits[i].text().strip()
if connections:
for conn in connections.split(','):
conn = conn.strip()
if self.weighted and ':' in conn:
target, weight = conn.split(':')
temp_graph.add_edge(i + 1, int(target), weight=float(weight))
else:
temp_graph.add_edge(i + 1, int(conn))
else:
temp_graph.add_node(i + 1)
# Handle electrical circuit properties
if self.electrical_circuit:
for i in range(num_vertices):
p_text = self.node_probability_edits[i].text().strip()
probability = 1.0
if p_text:
probability = float(p_text)
node_id = i + 1
temp_graph.nodes[node_id]['probability'] = probability
self.draw_graph(temp_graph)
except Exception as e:
QMessageBox.warning(dialog, "Ошибка", f"Неверный формат данных: {str(e)}")
def create_graph_from_text(self, dialog):
"""Create graph from text input"""
try:
num_vertices = self.vertex_count if self.vertex_count > 0 else len(self.graph.nodes)
self.graph = nx.DiGraph()
# Add edges
for i in range(num_vertices):
connections = self.connection_edits[i].text().strip()
if connections:
for conn in connections.split(','):
conn = conn.strip()
if self.weighted and ':' in conn:
target, weight = conn.split(':')
self.graph.add_edge(i + 1, int(target), weight=float(weight))
else:
self.graph.add_edge(i + 1, int(conn))
else:
self.graph.add_node(i + 1)
# Handle electrical circuit properties
if self.electrical_circuit:
for i in range(num_vertices):
p_text = self.node_probability_edits[i].text().strip()
probability = 1.0
if p_text:
probability = float(p_text)
node_id = i + 1
self.graph.nodes[node_id]['probability'] = probability
dialog.close()
self.draw_graph(self.graph)
self.update_all_matrices()
self.toggle_buttons(True)
except Exception as e:
QMessageBox.warning(dialog, "Ошибка", f"Неверный формат данных: {str(e)}")
def draw_graph(self, graph):
"""Draw the graph using graphviz"""
self.figure.clear()
ax = self.figure.add_subplot(111)
if self.use_graphviz:
# Create graphviz graph
dot = Digraph(engine='dot', graph_attr={'dpi': '300', 'rankdir': 'LR' if self.electrical_circuit else 'TB'})
dot.attr('node', shape='rectangle' if self.electrical_circuit else 'circle')
# Add nodes with colors
for node, data in graph.nodes(data=True):
node_type = self.get_node_type(graph, node)
probability = data.get('probability')
node_label = (f'P{node} ({probability})' if data.get(
'probability') != 1 else '') if self.electrical_circuit else f'{node}'
dot.node(str(node), label=node_label, color=self.color_settings['node_colors'][node_type],
style='filled')
# Add edges with labels
edge_counter = 1
for u, v, data in graph.edges(data=True):
if self.weighted:
label = f"{edge_counter} ({data.get('weight', '')})"
elif not self.electrical_circuit:
label = str(edge_counter)
else:
label = ''
dot.edge(str(u), str(v), label=label)
edge_counter += 1
# Convert dot to PNG and display
png_data = dot.pipe(format='png')
img = Image.open(io.BytesIO(png_data))
ax.imshow(img)
ax.axis('off')
else:
pos = nx.spring_layout(graph)
node_colors = self.get_node_colors(graph)
if self.weighted:
edge_labels = nx.get_edge_attributes(graph, 'weight')
nx.draw_networkx_edge_labels(graph, pos, edge_labels=edge_labels, ax=ax)
if self.electrical_circuit:
node_labels = nx.get_node_attributes(graph, 'probability')
formatted_labels = {}
for node, label in node_labels.items():
formatted_labels[node] = f'{node} ({label})'
nx.draw_networkx_labels(graph, pos, labels=formatted_labels, ax=ax)
nx.draw(graph, pos, ax=ax, with_labels=not self.electrical_circuit, node_size=2000,
node_color=node_colors, arrows=True)
self.canvas.draw()
def get_node_type(self, graph, node):
"""Determine node type for coloring"""
in_degree = graph.in_degree(node)
out_degree = graph.out_degree(node)
if in_degree == 0 and out_degree == 0:
return "Изолированная"
elif in_degree == 0:
return "Висячая"
elif out_degree == 0:
return "Тупиковая"
else:
return "Внутренняя"
def update_all_matrices(self):
"""Update all matrix tabs"""
self.show_matrix("adjacency")
self.show_matrix("incidence")
if self.weighted:
self.show_matrix("weight")
def show_matrix(self, matrix_type):
"""Show specified matrix in corresponding tab"""
if matrix_type == "adjacency":
matrix, node_types, analysis = self.get_adjacency_matrix()
table = self.adjacency_table
elif matrix_type == "incidence":
matrix, node_types, analysis = self.get_incidence_matrix()
table = self.incidence_table
elif matrix_type == "weight":
matrix = self.get_weight_matrix()
table = self.weight_table
else:
return
# Convert to DataFrame for easier handling
df = pd.DataFrame(matrix)
if matrix_type == "adjacency":
df.index = range(1, len(matrix) + 1)
df.columns = range(1, len(matrix) + 1)
elif matrix_type == "weight":
df.index = range(1, len(matrix) + 1)
df.columns = range(1, len(matrix) + 1)
else: # incidence
df.index = range(1, len(matrix) + 1)
df.columns = range(1, len(matrix[0]) + 1)
# Add node types and analysis columns
if matrix_type != "weight":
df.insert(0, "Тип вершины", node_types)
df.insert(1, "Топологический анализ", analysis)
# Display in table
table.setRowCount(df.shape[0])
table.setColumnCount(df.shape[1])
table.setHorizontalHeaderLabels([str(x) for x in df.columns])
for i in range(df.shape[0]):
for j in range(df.shape[1]):
item = QTableWidgetItem(str(df.iat[i, j]))
if matrix_type == "weight":
value = df.iat[i, j]
if value != 0:
item.setBackground(QColor(self.color_settings['matrix_colors']["1"]))
else:
# Color node type cells
if j == 0:
node_type = df.iat[i, j]
item.setBackground(QColor(self.color_settings['node_colors'][node_type]))
# Color matrix value cells
elif j > 1: # Skip analysis column
value = str(df.iat[i, j])
if value in self.color_settings['matrix_colors']:
item.setBackground(QColor(self.color_settings['matrix_colors'][value]))
table.setItem(i, j, item)
# Resize columns to contents
table.resizeColumnsToContents()
def get_adjacency_matrix(self):
"""Generate adjacency matrix with additional info"""
nodes = sorted(self.graph.nodes())
size = len(nodes)
matrix = [[0] * size for _ in range(size)]
for u, v in self.graph.edges():
i = nodes.index(u)
j = nodes.index(v)
matrix[i][j] = 1
node_types = []
analysis = []
for node in nodes:
in_degree = self.graph.in_degree(node)
out_degree = self.graph.out_degree(node)
node_types.append(self.get_node_type(self.graph, node))
analysis.append(f"стр. {node} выходы: {out_degree} | столб. {node} входы: {in_degree}")
return matrix, node_types, analysis
def get_incidence_matrix(self):
"""Generate incidence matrix with additional info"""
nodes = sorted(self.graph.nodes())
edges = list(self.graph.edges())
size = len(nodes)
edge_count = len(edges)
matrix = [[0] * edge_count for _ in range(size)]
for j, (u, v) in enumerate(edges):
i_u = nodes.index(u)
i_v = nodes.index(v)
matrix[i_u][j] = 1
matrix[i_v][j] = -1
node_types = []
analysis = []
for node in nodes:
node_types.append(self.get_node_type(self.graph, node))
in_degree = self.graph.in_degree(node)
out_degree = self.graph.out_degree(node)
if in_degree == 0 and out_degree == 0:
analysis.append("Без выходов и входов (0)")
elif in_degree == 0:
analysis.append("Только выходы (0 и 1)")
elif out_degree == 0:
analysis.append("Только входы (0 и -1)")
else:
analysis.append("И выходы и входы (0, 1 и -1)")
return matrix, node_types, analysis
def get_weight_matrix(self):
"""Generate weight matrix with additional info"""
nodes = sorted(self.graph.nodes())
size = len(nodes)
matrix = [[0] * size for _ in range(size)]
for u, v, data in self.graph.edges(data=True):
i = nodes.index(u)
j = nodes.index(v)
matrix[i][j] = data.get('weight', 1)
return matrix
def show_path_search_dialog(self):
"""Show dialog to enter start and """
dialog = QDialog(self)
dialog.setWindowTitle("Поиск путей от точки до точки")
layout = QVBoxLayout(dialog)
form_layout = QHBoxLayout()
src_label = QLabel("Откуда:")
form_layout.addWidget(src_label)
src_edit = QLineEdit()
form_layout.addWidget(src_edit)
dest_label = QLabel("Куда:")
form_layout.addWidget(dest_label)
dest_edit = QLineEdit()
form_layout.addWidget(dest_edit)
layout.addLayout(form_layout)
nodes = [str(x) for x in self.graph.nodes()]
nodes_list = list(self.graph.nodes())
def display_paths(src = None, dest = None):
try:
if not src:
src = nodes_list[nodes.index(src_edit.text().replace('P',''))]
if not dest:
dest = nodes_list[nodes.index(dest_edit.text().replace('P',''))]
except Exception as e:
QMessageBox.warning(self, "Ошибка", f"Ошибка ввода данных: {str(e)}")
return
self.display_all_paths(dialog, src, dest)
show_button = QPushButton("Показать пути")
show_button.clicked.connect(lambda: display_paths())
layout.addWidget(show_button)
dialog.exec_()
def display_all_paths(self, dialog, source, target):
"""Find all paths from source to target"""
try:
if not self.graph or self.graph.number_of_nodes() == 0:
return
if dialog:
dialog.close()
# Find all simple paths from source to target
all_paths = list(nx.all_simple_paths(self.graph, source, target))
text = f"Все пути от {source} до {target}: {len(all_paths)}\n"
for path in all_paths:
str_path = [str(x) for x in path]
text += " -> ".join(str_path) + "\n"
QMessageBox.information(self, "Пути", text)
return
except Exception as e:
QMessageBox.warning(self, "Ошибка", f"Ошибка при расчете путей между точками: {str(e)}")
return
def calculate_network_weight(self):
"""Calculate and show total weight of all edges"""
if not self.weighted:
QMessageBox.warning(self, "Ошибка", "Граф не является взвешенным")
return
total_weight = sum(data['weight'] for u, v, data in self.graph.edges(data=True))
QMessageBox.information(self, "Вес сети", f"Общий вес всех ребер графа: {total_weight}")
def calculate_structure_diameter(self):
paths = ""
hanging_nodes = []
final_nodes = []
lengths = []
for node in sorted(self.graph.nodes()):
# Висячая
if len(self.graph.in_edges(node)) == 0 and len(self.graph.out_edges(node)) > 0:
hanging_nodes.append(node)
# Тупиковая
if len(self.graph.in_edges(node)) > 0 and len(self.graph.out_edges(node)) == 0:
final_nodes.append(node)
for node in hanging_nodes:
for final_node in final_nodes:
all_paths = list(nx.all_simple_paths(self.graph, node, final_node))
all_paths.sort()
data = len(all_paths[0]) - 1 # Remove starting point
lengths.append(data)
paths += f"{node} -> {final_node}: {data}\n"
result = f"Диаметр структуры: {max(lengths)}\n\n {paths}"
QMessageBox.information(self, "Диаметр структуры", result)
def calculate_structure_complexity(self):
dialog = QDialog(self)
dialog.setWindowTitle("Расчет сложности структуры")
layout = QVBoxLayout(dialog)
result = "Сложность структуры:\n\n"
hanging_nodes = []
final_nodes = []
paths_count = []
sums = []
sum_text = []
sum_values = []
for node in sorted(self.graph.nodes()):
# Висячая
if len(self.graph.in_edges(node)) == 0 and len(self.graph.out_edges(node)) > 0:
hanging_nodes.append(node)
# Тупиковая
if len(self.graph.in_edges(node)) > 0 and len(self.graph.out_edges(node)) == 0:
final_nodes.append(node)
for node in hanging_nodes:
for final_node in final_nodes:
all_paths = list(nx.all_simple_paths(self.graph, node, final_node))
data = len(all_paths)
paths_count.append(data)
sums.append((f"S{node}-{final_node}", data, [node, final_node]))
sum_text.append(f"S{node}-{final_node}")
sum_values.append(data)
result += f"S{node}-{final_node}: {data}\n"
n1 = len(hanging_nodes)
n2 = len(final_nodes)
oneOverN1 = 1 / n1
oneOverN2 = 1 / n2
value = oneOverN1 * oneOverN2 * sum(sum_values) - 1
result += f'\n\n1/{n1} * 1/{n2} * ({" + ".join(sum_text)}) - 1 = '
result += f'\n{oneOverN1} * {oneOverN2} * ({" + ".join([str(x) for x in sum_values])}) - 1 = {value}\n'
label = QLabel("Расчет сложности структуры: ")
label.setWordWrap(True)
layout.addWidget(label)
for sum_text, sum_value, nodes in sums:
form_layout = QHBoxLayout()
label = QLabel(f"{sum_text}")
form_layout.addWidget(label)
button = QPushButton("Показать пути")
button.clicked.connect(lambda _, n=nodes: self.display_all_paths(None, n[0], n[1]))
form_layout.addWidget(button)
layout.addLayout(form_layout)
label = QLabel(result)
label.setWordWrap(True)
layout.addWidget(label)
dialog.exec_()
def calculate_vertex_rank(self):
"""Calculate and show rank for each vertex"""
result = "Ранг вершин (сумма входов и выходов):\n"
for node in sorted(self.graph.nodes()):
weight = sum(1 for u, v in self.graph.in_edges(node)) + sum(1 for u, v in self.graph.out_edges(node))
result += f"Вершина {node}: {weight}\n"
QMessageBox.information(self, "Ранг вершин", result)
def calculate_vertex_weights(self):
"""Calculate and show weights for each vertex"""
if not self.weighted:
QMessageBox.warning(self, "Ошибка", "Граф не является взвешенным")
return
result = "Вес вершин (сумма входящих ребер):\n"
for node in sorted(self.graph.nodes()):
weight = sum(data['weight'] for u, v, data in self.graph.in_edges(node, data=True))
result += f"Вершина {node}: {weight}\n"
QMessageBox.information(self, "Вес вершин", result)
def calculate_reliability(self):
"""Calculate graph reliability considering series and parallel connections"""
try:
if not self.graph or self.graph.number_of_nodes() == 0:
return 0
hanging_nodes = []
final_nodes = []
for node in sorted(self.graph.nodes()):
# Висячая
if len(self.graph.in_edges(node)) == 0 and len(self.graph.out_edges(node)) > 0:
hanging_nodes.append(node)
# Тупиковая
if len(self.graph.in_edges(node)) > 0 and len(self.graph.out_edges(node)) == 0:
final_nodes.append(node)
if len(hanging_nodes) != 1:
QMessageBox.warning(self, "Предупреждение", f"Не удается определить начало цепи, входов: {len(hanging_nodes)} - расчеты могут быть не верны")
if len(final_nodes) != 1:
QMessageBox.warning(self, "Предупреждение", f"Не удается определить конец цепи, входов: {len(hanging_nodes)} - расчеты могут быть не верны")
# Find all simple paths from source to target
all_paths = list(nx.all_simple_paths(self.graph, hanging_nodes[0], final_nodes[0]))
# Convert each path into a set of nodes
path_node_sets = [set(path) for path in all_paths]
# Inclusion-Exclusion Principle for exact union probability
def inclusion_exclusion(paths, node_probs):
total_prob = 0.0
n = len(paths)
for r in range(1, n + 1):
for combo in itertools.combinations(range(n), r):
# Union of node sets in this combo
node_union = set()
for i in combo:
node_union.update(paths[i])
# Product of success probabilities for this union
prob = np.prod([node_probs[node] for node in node_union])
if r % 2 == 1:
total_prob += prob
else:
total_prob -= prob
return total_prob
# Apply the formula
circuit_success = inclusion_exclusion(path_node_sets, nx.get_node_attributes(self.graph, 'probability'))
circuit_failure = 1 - circuit_success
QMessageBox.information(self, "Надежность",
f"Надежность цепи: {circuit_success:.4f}\n"
f"Ненадежность цепи: {circuit_failure:.4f}\n"
f"Количество путей: {len(all_paths)}")
return circuit_success
except Exception as e:
QMessageBox.warning(self, "Error", f"Failed to calculate reliability: {str(e)}")
return 0
def configure_node_colors(self):
"""Configure node type colors"""
node_types = ['Висячая', 'Тупиковая', 'Изолированная', 'Внутренняя']
for node_type in node_types:
color = QColorDialog.getColor(
initial=QColor(self.color_settings['node_colors'][node_type]),
parent=self,
title=f"Выберите цвет для {node_type} вершины"
)
if color.isValid():
self.color_settings['node_colors'][node_type] = color.name()
# Redraw everything with new colors
if self.graph.nodes():
self.draw_graph(self.graph)
self.update_all_matrices()
def configure_matrix_colors(self):
"""Configure matrix value colors"""
values = ['1', '-1']