-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2442 lines (2158 loc) · 127 KB
/
Copy pathmain.py
File metadata and controls
2442 lines (2158 loc) · 127 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, json, pygame, math, random, markdown
import numpy as np
import pandas as pd
import tkinter as tk
from tkinter import filedialog
import threading
import queue
import openpyxl
import pickle
import copy
import re
import sys
from datetime import datetime
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
#
#
# class MainLoop:
#
# def __init__(self):
# self.WIDTH, self.HEIGHT = 1200, 800
# self.FINAL_WIDTH, self.FINAL_HEIGHT = 2400, 1600
# pygame.init()
# self.canvas = pygame.Surface((self.WIDTH, self.HEIGHT))
# self.screen = pygame.display.set_mode((self.FINAL_WIDTH, self.FINAL_HEIGHT))
#
#
# class TkinterSetup:
# pass
#
#
# filepath = "E:\Git\MaCSBio-GEM\General\Functions\Metabolic_tasks\Task322Sample1Alpha0.50Beta0.00_Date2023-10-25_21-51-37\ModelsJSON/newModelMILP_OR_AdjustTask322Sample1Scored2.152average4.105alpha0.500beta0.000.json"
#
# with open(filepath, 'r') as file:
# # Read JSON data
# json_data = json.load(file)
#
class MetaboliteNodes:
def __init__(self, id, name, compartment):
self.id = id
self.name = name
self.compartment = compartment
self.x, self.y = 0, 0
self.amount_of_reactions = 0
self.reactions = []
self.visible = True
self.fixed_node_input = False
self.fixed_node_output = False
class ReactionEdges:
def __init__(self, id, name, metabolites, lb, ub):
self.id = id
self.name = name
self.metabolites = metabolites
self.lb = lb
self.ub = ub
self.visible = True # for compartment
self.flux = 0
self.expression = 0
class CompartmentNode:
def __init__(self, id, name):
self.id = id
self.name = name
self.metabolites = []
self.visible = False
self.flux = 0
self.expression = 0
class BoundaryNode:
def __init__(self):
pass
class NetworkNodesForPhysicsSimulation:
def __init__(self, x, y, instance, id_number, met_network):
self.x, self.y = x, y
self.instance = instance
self.x_vector, self.y_vector = 0, 0
self.id_number = id_number
self.met_network = met_network
if isinstance(self.instance, ReactionEdges):
self.node_type = "reaction"
self.fixed = False
elif isinstance(self.instance, MetaboliteNodes):
self.node_type = "metabolite"
if self.instance.fixed_node_input or self.instance.fixed_node_output:
self.fixed = True
else:
self.fixed = False
elif isinstance(self.instance, CompartmentNode):
self.node_type = "compartment"
self.fixed = False
elif isinstance(self.instance, BoundaryNode):
self.node_type = "boundary"
self.fixed = True
self.input_instances = []
self.output_instances = []
self.find_input_and_output_instances()
self.rect = pygame.Rect(self.x, self.y, 15, 15)
self.fixed_by_mouse = False
self.visible_by_mouse = True
# Unfortunately necessary to make sure all lines are drawn (something goes wrong with indicing
if isinstance(self.instance, MetaboliteNodes) and self.instance.id == "000fake":
self.visible_by_mouse = False
self.highlighted_by_mouse = False
self.split_of_nodes_partners = []
self.selected_by_drag_selection = False
def find_input_and_output_instances(self):
if isinstance(self.instance, ReactionEdges):
for metabolite, stoichiometry in self.instance.metabolites.items():
if metabolite in [metabolit.id for metabolit in self.met_network.included_metabolites] and stoichiometry > 0:
self.input_instances.append(self.met_network.find_metabolite(metabolite))
elif metabolite in [metabolit.id for metabolit in self.met_network.included_metabolites] and stoichiometry < 0:
self.output_instances.append(self.met_network.find_metabolite(metabolite))
elif isinstance(self.instance, MetaboliteNodes):
for reaction in self.instance.reactions:
reaction_ = self.met_network.find_reaction(reaction)
for metabolite, stoichiometry in reaction_.metabolites.items():
if metabolite == self.instance.id and stoichiometry < 0:
self.input_instances.append(reaction_)
elif metabolite == self.instance.id and stoichiometry > 0:
self.output_instances.append(reaction_)
elif isinstance(self.instance, CompartmentNode):
for metabolite in self.instance.metabolites:
if metabolite.id in [metabolit.id for metabolit in self.met_network.included_metabolites]:
self.input_instances.append(metabolite)
class MetabolicNetwork:
def __init__(self, nodes, edges, tkinter_app):
self.metabolites_nodes = nodes
self.reaction_edges = edges
self.tk_application = tkinter_app
self.set_amount_of_reactions_per_node()
self.set_slider()
self.filter_input_output_reactions()
self.set_reactions_for_nodes()
self.commonly_excluded_names = [] # ["H+", "H2O", "NADH", "NAD+", "NADP+", "NADPH", "FAD", "FADH", "CO2"]
self.included_metabolites = []
self.not_included_metabolites = []
self.part_of_physics_metabolites = []
self.not_part_of_physics_metabolites = []
self.create_lookup_dicts()
self.update_included_not_included_based_on_slider()
self.edge_logic_dict = {}
self.all_network_nodes = []
self.fixed_metabolite_repulsion_value = 1000
self.metabolite_compartment_attraction_value = 3000
self.rxn_met_attraction_value = 3000
self.boundary_repulsion_value = 3000
self.comp_comp_repulsion_value = 3000
self.normal_repulsion_value = 1000
self.rect_size = 15
self.font_size = 18
self.show_lines = True
self.show_fixed_metabolite_names = "No Names"
self.show_metabolite_names = "No Names"
self.show_reaction_names = "Reaction Names"
self.show_compartments = False
self.show_flux_expression = "None"
self.visible_nodes = []
self.not_visible_nodes = []
self.queue = queue.Queue()
self.df_fluxes_reactions = pd.DataFrame()
self.fluxes_dict = {}
self.expression_dict = {}
self.full_json_dict = {}
self.zoom_factor = 1
self.show_color_lines = False
self.drawing_selection_rect_on_screen = False
self.begin_selection_rect_pos = (0, 0)
self.end_selection_rect_pos = (0, 0)
self.search_mode_enabled = False
self.search_input_text = ""
self.search_suggestion_list = []
self.full_search_list = []
self.current_search_index = 0
self.selected_search_item = None
self.show_expressionless_reaction_highlight = False
self.canvas_width = 900
self.canvas_height = 800
self.current_command = None
self.previous_commands = []
self.next_commands_undone = []
self.control_groups_for_selection = {1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: []}
self.start_command_recording = True
self.key_actions = {"left_mouse_clicked": False, "right_mouse_clicked": False, "middle_mouse_clicked": False,
"shift_clicked": False, "v_clicked": False, "split_clicked": False, "up_clicked": False, "down_clicked": False,
"right_clicked": False, "left_clicked": False, "f_clicked": False, "g_clicked": False, "tab_clicked": False,
"enter_clicked": False, "escape clicked": False, "control_clicked": False}
def save_as_json(self):
node_xy_save_dict = {}
for node in self.all_network_nodes:
if not isinstance(node.instance, BoundaryNode):
node_xy_save_dict[node.instance.id] = (node.x, node.y)
# self.fluxes_dict
# self.expression_dict
# freeze all mets at loading
# xy coordinates of each node
self.full_json_dict = {}
self.full_json_dict["fluxes_dict"] = self.fluxes_dict
self.full_json_dict["expression_dict"] = self.expression_dict
self.full_json_dict["node_xy_save_dict"] = node_xy_save_dict
self.formulate_metadata_dict()
self.formulate_main_ESHER_dict()
self.remove_duplicate_main_nodes()
self.list_with_dicts_to_save = [self.meta_data_dict, self.main_ESHER_dict]
# self.formulate_labels_dict()
# self.formulate_canvas_dict()
pass
def formulate_metadata_dict(self):
self.meta_data_dict = {}
date = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
self.meta_data_dict = {
"map_name": "new_map",
"map_id": "000000000",
"map_description": f"\nLast Modified {date}",
"homepage": "https://escher.github.io", "schema": "https://escher.github.io/escher/jsonschema/1-0-0#",
"not_escher_dict": self.full_json_dict
}
def formulate_main_ESHER_dict(self):
self.main_ESHER_dict = {}
node_counter = 0
segment_counter = 0
nodes_dict = {}
reaction_counter = 0
expansion_constant = 5
self.main_ESHER_dict["reactions"] = {}
for node in self.all_network_nodes:
segments_dict = {}
if node.node_type == "reaction" and node.visible_by_mouse:
# calculate closests input and output nodes and designate them as main, all else will be build separately
distance = 100000000000
closest_input_node = None
for input_instance in node.input_instances:
for temp_node in self.all_network_nodes:
if temp_node.node_type == "metabolite" and input_instance == temp_node.instance and temp_node.visible_by_mouse:
input_node = temp_node
break
node_distance = math.sqrt((input_node.x - node.x) ** 2 + (input_node.y - node.y) ** 2)
if closest_input_node is None or node_distance < distance:
distance = node_distance
closest_input_node = input_node
distance = 10000000000000
closest_output_node = None
for output_instance in node.output_instances:
for temp_node in self.all_network_nodes:
if temp_node.node_type == "metabolite" and output_instance == temp_node.instance and temp_node.visible_by_mouse:
output_node = temp_node
node_distance = math.sqrt((output_node.x - node.x) ** 2 + (output_node.y - node.y) ** 2)
if closest_output_node is None or node_distance < distance:
distance = node_distance
closest_output_node = output_node
## create node and reaction entry
start_node_counter = node_counter
main_x, main_y = node.x, node.y
# static segments:
segments_dict[segment_counter] = {
"from_node_id": str(start_node_counter),
"to_node_id": str(start_node_counter + 1),
"b1": None,
"b2": None
}
segment_counter += 1
segments_dict[segment_counter] = {
"from_node_id": str(start_node_counter + 1),
"to_node_id": str(start_node_counter + 2),
"b1": None,
"b2": None
}
segment_counter += 1
nodes_dict[node_counter] = {
"node_type": "multimarker",
"x": expansion_constant * main_x,
"y": expansion_constant * (main_y) - 40,
}
node_counter += 1
nodes_dict[node_counter] = {
"node_type": "midmarker",
"x": expansion_constant * main_x,
"y": expansion_constant * (main_y) - 10,
}
node_counter += 1
nodes_dict[node_counter] = {
"node_type": "multimarker",
"x": expansion_constant * main_x,
"y": expansion_constant * (main_y) + 20,
}
node_counter += 1
before_input_counter = node_counter
if closest_output_node is not None:
nodes_dict[node_counter] = {
"node_type": "metabolite",
"x": expansion_constant * closest_output_node.x,
"y": expansion_constant * closest_output_node.y,
"bigg_id": closest_output_node.instance.id,
"name": closest_output_node.instance.name,
"label_x": expansion_constant * closest_output_node.x - 20,
"label_y": expansion_constant * closest_output_node.y - 20,
"node_is_primary": True
}
node_counter += 1
segments_dict[segment_counter] = {
"from_node_id": str(node_counter - 1),
"to_node_id": str(start_node_counter),
"b1": {"x": expansion_constant * closest_output_node.x + 50,
"y": expansion_constant * closest_output_node.y + 50},
"b2": {"x": expansion_constant * main_x,
"y": expansion_constant * (main_y) - 40}
}
segment_counter += 1
for idx, input_instance in enumerate(node.output_instances):
if input_instance != closest_output_node.instance:
nodes_dict[node_counter] = {
"node_type": "metabolite",
"x": expansion_constant * (main_x) + (idx * 40) - 30,
"y": expansion_constant * (main_y) - 120,
"bigg_id": input_instance.id,
"name": input_instance.name,
"label_x": expansion_constant * (main_x) + (idx * 40) - 50,
"label_y": expansion_constant * main_y - 120 - 20,
"node_is_primary": False
}
node_counter += 1
segments_dict[segment_counter] = {
"from_node_id": str(node_counter - 1),
"to_node_id": str(start_node_counter),
"b1": {"x": expansion_constant * (main_x) + (idx * 40) - 30,
"y": expansion_constant * (main_y) - 120},
"b2": {"x": expansion_constant * main_x,
"y": expansion_constant * (main_y) - 40}
}
segment_counter += 1
before_output_node_counter = node_counter
if closest_input_node is not None:
nodes_dict[node_counter] = {
"node_type": "metabolite",
"x": expansion_constant * closest_input_node.x,
"y": expansion_constant * closest_input_node.y,
"bigg_id": closest_input_node.instance.id,
"name": closest_input_node.instance.name,
"label_x": expansion_constant * closest_input_node.x - 20,
"label_y": expansion_constant * closest_input_node.y + 20,
"node_is_primary": True
}
node_counter += 1
segments_dict[segment_counter] = {
"from_node_id": str(start_node_counter + 2),
"to_node_id": str(node_counter - 1),
"b1": {"x": expansion_constant * main_x,
"y": expansion_constant * main_y + 20},
"b2": {"x": expansion_constant * closest_input_node.x - 50,
"y": expansion_constant * closest_input_node.y - 50}
}
segment_counter += 1
for idx, input_instance in enumerate(node.input_instances):
if input_instance != closest_input_node.instance:
nodes_dict[node_counter] = {
"node_type": "metabolite",
"x": expansion_constant * main_x + (idx * 40) - 30,
"y": expansion_constant * main_y + 120,
"bigg_id": input_instance.id,
"name": input_instance.name,
"label_x": expansion_constant * main_x + (idx * 40) - 50,
"label_y": expansion_constant * main_y + 120 - 20,
"node_is_primary": False
}
node_counter += 1
segments_dict[segment_counter] = {
"from_node_id": str(start_node_counter + 2),
"to_node_id": str(node_counter - 1),
"b1": {"x": expansion_constant * main_x,
"y": expansion_constant * main_y + 20},
"b2": {"x": expansion_constant * main_x + (idx * 40) - 30 - 50,
"y": expansion_constant * main_y + 120 - 50}
}
segment_counter += 1
metabolites_list_with_dicts = []
for met, stoichiometry in node.instance.metabolites.items():
dict_to_add = {"bigg_id": met, "coefficient": stoichiometry}
metabolites_list_with_dicts.append(dict_to_add)
self.main_ESHER_dict["reactions"][reaction_counter] = {
"name": node.instance.name,
"bigg_id": node.instance.id,
"reversibility": False,
"label_x": expansion_constant * main_x + 50,
"label_y": expansion_constant * main_y,
"gene_reaction_rule": "",
"genes": [{}],
"metabolites": metabolites_list_with_dicts,
"segments": segments_dict
}
reaction_counter += 1
self.main_ESHER_dict["nodes"] = nodes_dict
self.main_ESHER_dict["text_labels"] = {}
self.main_ESHER_dict["canvas"] = {
"x": -1000,
"y": -500,
"width": 10000,
"height": 7000
}
def remove_duplicate_main_nodes(self):
list_to_remove = []
for id, node_dict in self.main_ESHER_dict["nodes"].items():
if node_dict["node_type"] == "metabolite" and node_dict["node_is_primary"]:
list_with_ids = []
for id2, node_dict2 in self.main_ESHER_dict["nodes"].items():
if id != id2 and node_dict2["node_type"] == "metabolite" and node_dict2["node_is_primary"] and node_dict2["bigg_id"] == node_dict[
"bigg_id"]:
list_with_ids.append(id2)
node_dict2["bigg_id"] = f"removed {id2}"
for reaction_id, reaction_dict in self.main_ESHER_dict["reactions"].items():
segments = reaction_dict["segments"]
for value in segments.values():
# print(value,list_with_ids)
if int(value["from_node_id"]) in list_with_ids:
value["from_node_id"] = id
if int(value["to_node_id"]) in list_with_ids:
value["to_node_id"] = id
list_to_remove.extend(list_with_ids)
for key in list_to_remove:
if key in self.main_ESHER_dict["nodes"]:
del self.main_ESHER_dict["nodes"][key]
def find_main_metabolite_nodes(self):
self.big_metabolite_nodes = []
for node in self.all_network_nodes:
if node.node_type == "reaction" and node.visible_by_mouse:
reaction_instance = node.instance
mets = reaction_instance.metabolites
lowest_connection_input_reaction_number = None
lowest_connection_output_reaction_number = None
lowest_connection_input_metabolite = None
lowest_connection_output_metabolite = None
for metabolite, stoichiometry in mets.items():
metabolite_instance = self.find_metabolite(metabolite)
if stoichiometry < 0: # input reaction
amount_of_reactions_where_metabolite_is_input = self.determine_true_amount_of_reactions(metabolite_instance, "input")
if lowest_connection_input_reaction_number == None or lowest_connection_input_reaction_number > amount_of_reactions_where_metabolite_is_input:
lowest_connection_input_reaction_number = amount_of_reactions_where_metabolite_is_input
lowest_connection_input_metabolite = metabolite_instance
else:
amount_of_reactions_where_metabolite_is_output = self.determine_true_amount_of_reactions(metabolite_instance, "output")
if lowest_connection_output_reaction_number == None or lowest_connection_output_reaction_number > amount_of_reactions_where_metabolite_is_output:
lowest_connection_output_reaction_number = amount_of_reactions_where_metabolite_is_output
lowest_connection_output_metabolite = metabolite_instance
node.main_metabolite_connections = [lowest_connection_input_metabolite, lowest_connection_output_metabolite]
def determine_true_amount_of_reactions(self, metabolite_instance, input_or_output):
name_to_check = re.sub(r'\[.\]$', '', metabolite_instance.name)
other_instances_with_similiar_name = [metabolite_instance]
for metabolite in self.metabolites_nodes:
if re.sub(r'\[.\]$', '', metabolite.name) == name_to_check:
other_instances_with_similiar_name.append(metabolite)
amount_of_reactions = 0
if input_or_output == "input":
for instance in other_instances_with_similiar_name:
for reaction in self.reaction_edges:
for met, stoichiometry in reaction.metabolites.items():
if stoichiometry < 0 and instance.id == met:
amount_of_reactions += 1
return amount_of_reactions
else:
for instance in other_instances_with_similiar_name:
for reaction in self.reaction_edges:
for met, stoichiometry in reaction.metabolites.items():
if stoichiometry > 0 and instance.id == met:
amount_of_reactions += 1
return amount_of_reactions
def formulate_labels_dict(self):
self.main_ESHER_dict["text_labels"] = {}
def formulate_canvas_dict(self):
self.main_ESHER_dict["canvas"] = {
"x": -2000, "y": -1000, "width": 10000, "height": 10000
}
def read_from_json(self, data):
escher_exists = False
visualization_network_exists = False
for dicts in data:
if "not_escher_dict" in dicts:
visualization_network_exists = True
for key_, element in dicts["not_escher_dict"].items():
self.full_json_dict[key_] = element
break
if visualization_network_exists:
self.calculate_network(visualization_network_exists)
def filter_input_output_reactions(self):
reaction_edges_copy = []
for reaction in self.reaction_edges:
if not (reaction.lb > 0 and reaction.ub < 1000) or not reaction.name.startswith('temporary_exchange_'):
reaction_edges_copy.append(reaction)
else:
self.set_fixed_metabolite(reaction)
self.reaction_edges = reaction_edges_copy
def set_fixed_metabolite(self, reaction):
mets = reaction.metabolites
for metabolite, stoichiometry in mets.items():
for met in self.metabolites_nodes:
if metabolite == met.id:
if stoichiometry > 0:
met.fixed_node_input = True
if stoichiometry < 0:
met.fixed_node_output = True
break
def find_reactions_that_should_generally_be_excluded(self):
for commonly_excluded_name in self.commonly_excluded_names:
for metabolite in self.metabolites_nodes:
if metabolite.name.startswith(commonly_excluded_name):
self.not_included_metabolites.append(metabolite)
def create_lookup_dicts(self):
self.dict_metabolite_names = {}
self.dict_metabolite_alternative_names = {}
for metabolite in self.metabolites_nodes:
self.dict_metabolite_names[metabolite.id] = metabolite
self.dict_metabolite_alternative_names[metabolite.name] = metabolite
self.dict_reactions = {}
for reaction in self.reaction_edges:
self.dict_reactions[reaction.id] = reaction
def find_reaction(self, reaction_id):
if reaction_id in self.dict_reactions:
reaction_ = self.dict_reactions[reaction_id]
try:
return reaction_
except:
return None
def find_metabolite(self, metabolite_id):
if metabolite_id.startswith("MAM0"): # should be changed if metabolite IDs ever go past 10000
if metabolite_id in self.dict_metabolite_names:
metabolite = self.dict_metabolite_names[metabolite_id]
else:
if metabolite_id in self.dict_metabolite_alternative_names:
metabolite = self.dict_metabolite_alternative_names[metabolite_id]
try:
return metabolite
except:
return None
def update_included_not_included_based_on_slider(self):
self.not_included_metabolites = []
self.included_metabolites = []
self.part_of_physics_metabolites = []
self.not_part_of_physics_metabolites = []
self.find_reactions_that_should_generally_be_excluded()
for metabolite in self.metabolites_nodes:
if metabolite.amount_of_reactions > self.slider_value and metabolite not in self.not_part_of_physics_metabolites:
self.not_part_of_physics_metabolites.append(metabolite)
for metabolite in self.metabolites_nodes:
if metabolite not in self.included_metabolites:
self.included_metabolites.append(metabolite)
for metabolite in self.metabolites_nodes:
if (metabolite.fixed_node_input or metabolite.fixed_node_output) and metabolite not in self.part_of_physics_metabolites:
self.part_of_physics_metabolites.append(metabolite)
try:
self.not_part_of_physics_metabolites.remove(metabolite)
except:
pass
self.part_of_physics_metabolites = [item for item in self.metabolites_nodes if item not in self.not_part_of_physics_metabolites]
self.not_part_of_physics_metabolites = [item for item in self.metabolites_nodes if item not in self.part_of_physics_metabolites]
def set_reactions_for_nodes(self):
for reaction in self.reaction_edges:
# if not (reaction.lb > 0 and reaction.ub < 1000) or not reaction.name.startswith('temporary_exchange_'):
for key, value in reaction.metabolites.items():
for metabolite in self.metabolites_nodes:
if key == metabolite.id:
metabolite.reactions.append(reaction.id)
break
def set_amount_of_reactions_per_node(self):
# dont count temporary reactions
for reaction in self.reaction_edges:
# if not (reaction.lb > 0 and reaction.ub < 1000) or not reaction.name.startswith('temporary_exchange_'):
for key, value in reaction.metabolites.items():
for metabolite in self.metabolites_nodes:
if key == metabolite.id:
metabolite.amount_of_reactions += 1
break
def set_slider(self):
self.slider_start = 1
highest_value = 0
total_edges = 0
for metabolite in self.metabolites_nodes:
total_edges += metabolite.amount_of_reactions
if metabolite.amount_of_reactions > highest_value:
highest_value = metabolite.amount_of_reactions
self.slider_end = highest_value
self.slider_value = math.floor(highest_value * 0.8)
def restart_simulation(self):
simulation_thread = threading.Thread(target=self.run_network_simulation)
simulation_thread.start()
def calculate_network(self, load_from_json=False):
# Create compartment_pseudo_reaction_nodes:
self.create_compartment_pseudo_reaction_nodes()
self.create_network_nodes_for_simulation()
# create edge matrices
self.create_edges_matrices_dicts()
self.update_edge_network()
# set initial x, y positions for non-boundary nodes
self.set_x_y_positions_non_boundary_nodes()
if load_from_json:
for node in self.all_network_nodes:
if node.node_type != "boundary":
key = node.instance.id
x, y = self.full_json_dict["node_xy_save_dict"][key]
node.x = x
node.y = y
for node in self.all_network_nodes:
node.fixed_by_mouse = True
# run network
simulation_thread = threading.Thread(target=self.run_network_simulation)
simulation_thread.start()
nodes, edges = self.extract_non_pseudo_nodes_and_edges()
return nodes, edges
def create_compartment_pseudo_reaction_nodes(self):
compartments = []
self.compartments = []
for metabolite in self.included_metabolites:
if metabolite.compartment not in compartments:
compartments.append(metabolite.compartment)
for idx, compartment in enumerate(compartments):
self.compartments.append(CompartmentNode(compartment, compartment))
for metabolite in self.included_metabolites:
if metabolite.compartment == compartment:
self.compartments[idx].metabolites.append(metabolite)
def create_network_nodes_for_simulation(self):
# Add a fake metabolite, unfortunately necessary for making sure all lines are drawn correttly (weirdly enough)
if self.included_metabolites[0].id != "000fake":
self.included_metabolites.insert(0, MetaboliteNodes("000fake", "000fake", self.compartments[0].id))
self.all_network_nodes = []
# Create all types of nodes
id_number = 0
for metabolite in self.included_metabolites:
self.all_network_nodes.append(NetworkNodesForPhysicsSimulation(0, 0, metabolite, id_number, self))
if metabolite in [met for met in self.not_part_of_physics_metabolites]:
self.all_network_nodes[-1].visible_by_mouse = False
id_number += 1
for reaction in self.reaction_edges:
self.all_network_nodes.append(NetworkNodesForPhysicsSimulation(0, 0, reaction, id_number, self))
id_number += 1
for compartment in self.compartments:
self.all_network_nodes.append(NetworkNodesForPhysicsSimulation(0, 0, compartment, id_number, self))
id_number += 1
# Create an edge with boundary repulsors (will have a very high power so their value will fall off quickly, just to make sure network stays within the
# bounds of the canvas, takes global height and width inputted as canvas as I didn't want to do some weird directing
global width
global height
amount_of_boundary_rows = (height // 50) + 1
amount_of_boundary_columns = (width // 50) + 1
for boundary_idx in range(amount_of_boundary_columns):
self.all_network_nodes.append(NetworkNodesForPhysicsSimulation(boundary_idx * 50, 0, BoundaryNode(), id_number, self))
id_number += 1
self.all_network_nodes.append(NetworkNodesForPhysicsSimulation(boundary_idx * 50, height, BoundaryNode(), id_number, self))
id_number += 1
for boundary_idx in range(amount_of_boundary_rows):
self.all_network_nodes.append(NetworkNodesForPhysicsSimulation(0, boundary_idx * 50, BoundaryNode(), id_number, self))
id_number += 1
self.all_network_nodes.append(NetworkNodesForPhysicsSimulation(width, boundary_idx * 50, BoundaryNode(), id_number, self))
id_number += 1
def create_edges_matrices_dicts(self):
node_length = len(self.all_network_nodes)
temp_connection_matrix = np.zeros((node_length, node_length))
edges = []
for node in self.all_network_nodes:
edge = [node.id_number]
if node.node_type == "reaction" or node.node_type == "metabolite":
for input_node in node.input_instances:
for temp_node in self.all_network_nodes:
if input_node == temp_node.instance:
connected_node_id_number = temp_node.id_number
edge.append(connected_node_id_number)
break
for output_node in node.output_instances:
for temp_node in self.all_network_nodes:
if output_node == temp_node.instance:
connected_node_id_number = temp_node.id_number
edge.append(connected_node_id_number)
break
edges.append(edge)
for edge in edges:
node_id = edge[0]
connected_nodes = edge[1:]
temp_connection_matrix[node_id, connected_nodes] = 1
self.edge_logic_dict["reaction_metabolite_attraction"] = temp_connection_matrix
temp_connection_matrix = np.zeros((node_length, node_length))
edges = []
for node in self.all_network_nodes:
edge = [node.id_number]
if node.node_type == "compartment":
for other_node in self.all_network_nodes:
if other_node != node and other_node.node_type == "compartment":
edge.append(other_node.id_number)
edges.append(edge)
for edge in edges:
node_id = edge[0]
connected_nodes = edge[1:]
temp_connection_matrix[node_id, connected_nodes] = 1
self.edge_logic_dict["compartment_compartment_repulsion"] = temp_connection_matrix
temp_connection_matrix = np.zeros((node_length, node_length))
edges = []
for node in self.all_network_nodes:
edge = [node.id_number]
if node.node_type == "metabolite" and node.instance.fixed_node_input:
for other_node in self.all_network_nodes:
if node != other_node and other_node.node_type == "metabolite" and other_node.instance.fixed_node_input:
edge.append(other_node.id_number)
if node.node_type == "metabolite" and node.instance.fixed_node_output:
for other_node in self.all_network_nodes:
if other_node.node_type == "metabolite" and other_node.instance.fixed_node_output:
edge.append(other_node.id_number)
edges.append(edge)
for edge in edges:
node_id = edge[0]
connected_nodes = edge[1:]
temp_connection_matrix[node_id, connected_nodes] = 1
self.edge_logic_dict["fixed_metabolite_repulsion"] = temp_connection_matrix
temp_connection_matrix = np.zeros((node_length, node_length))
edges = []
for node in self.all_network_nodes:
edge = [node.id_number]
for boundary_node in self.all_network_nodes:
if boundary_node.node_type == "boundary":
edge.append(boundary_node.id_number)
edges.append(edge)
for edge in edges:
node_id = edge[0]
connected_nodes = edge[1:]
temp_connection_matrix[node_id, connected_nodes] = 1
self.edge_logic_dict["boundary_repulsion"] = temp_connection_matrix
temp_connection_matrix = np.zeros((node_length, node_length))
edges = []
for node in self.all_network_nodes:
edge = [node.id_number]
if node.node_type != "boundary":
for other_node in self.all_network_nodes:
if other_node != node and other_node.node_type != "boundary":
edge.append(other_node.id_number)
edges.append(edge)
for edge in edges:
node_id = edge[0]
connected_nodes = edge[1:]
temp_connection_matrix[node_id, connected_nodes] = 1
self.edge_logic_dict["normal_repulsion"] = temp_connection_matrix
temp_connection_matrix = np.zeros((node_length, node_length))
edges = []
for node in self.all_network_nodes:
edge = [node.id_number]
if node.node_type == "compartment":
for connected_instance in node.input_instances:
for other_node in self.all_network_nodes:
if connected_instance == other_node.instance and not (other_node.instance.fixed_node_input or other_node.instance.fixed_node_output):
edge.append(other_node.id_number)
edges.append(edge)
for edge in edges:
node_id = edge[0]
connected_nodes = edge[1:]
temp_connection_matrix[node_id, connected_nodes] = 1
for extra_edge in edge[1:]:
temp_connection_matrix[extra_edge, node_id] = 1
self.edge_logic_dict["metabolite_compartment_attraction"] = temp_connection_matrix
def update_edge_network(self):
self.create_edges_matrices_dicts()
idx_list = []
for node in self.all_network_nodes:
if node.node_type == "metabolite" and node.instance in [met for met in self.not_part_of_physics_metabolites]:
idx_list.append(node.id_number)
for key, matrix in self.edge_logic_dict.items():
if key != "draw_lines_connections":
for i in idx_list:
matrix[i, :] = 0 # Zero out rows
matrix[:, i] = 0 # Zero out columns
self.edge_logic_dict[key] = matrix
self.queue.put(self.tk_application.create_listboxes)
self.queue.put(self.tk_application.create_listboxes_visibility)
node_length = len(self.all_network_nodes)
temp_connection_matrix = np.zeros((node_length, node_length))
edges = []
for node in self.all_network_nodes:
edge = [node.id_number]
if node.node_type == "reaction" or node.node_type == "metabolite":
# for input_node in node.input_instances:
# for temp_node in self.all_network_nodes:
# if input_node == temp_node.instance:
# connected_node_id_number = temp_node.id_number
# edge.append(connected_node_id_number)
# break
for output_node in node.output_instances:
for temp_node in self.all_network_nodes:
if output_node == temp_node.instance:
connected_node_id_number = temp_node.id_number
edge.append(connected_node_id_number)
break
edges.append(edge)
for edge in edges:
node_id = edge[0]
connected_nodes = edge[1:]
temp_connection_matrix[node_id, connected_nodes] = 1
self.edge_logic_dict["draw_lines_connections"] = temp_connection_matrix
def set_x_y_positions_non_boundary_nodes(self):
fixed_input_counter = 0
fixed_output_counter = 0
global width
global height
random.seed(666)
for node in self.all_network_nodes:
if node.node_type == "boundary":
pass
elif node.node_type == "metabolite" and node.instance.fixed_node_output:
node.x = 200 + (fixed_output_counter * 25)
fixed_output_counter += 1
node.y = height - 50
elif node.node_type == "metabolite" and node.instance.fixed_node_input:
node.x = 200 + (fixed_input_counter * 25)
fixed_input_counter += 1
node.y = 0 + 50
else:
node.x = random.randint(200, width - 200)
node.y = random.randint(200, height - 200)
def run_network_simulation(self):
self.network_physics_simulation_loop()
def network_physics_simulation_loop(self):
# loop
try:
pygame.quit()
except:
pass
global running
running = True
pygame_on = True
if pygame_on:
os.environ['SDL_VIDEO_WINDOW_POS'] = '100,30' # TODO ADD IN DEFAULT SETTING
pygame.init()
display = pygame.display.set_mode([self.canvas_width, self.canvas_height])
text_input_rect = pygame.Rect(50, 50, 300, 40)
self.viewport = pygame.Rect(0, 0, 1500, 1200)
self.font = pygame.font.SysFont(None, self.font_size)
self.font2 = pygame.font.SysFont(None, 28)
self.font3 = pygame.font.Font(None, 32)
self.selected_node = None
while running:
if pygame_on:
display.fill((0, 0, 0))
self.pygame_event_handling_code(display)
if self.drawing_selection_rect_on_screen:
x_ = min(self.begin_selection_rect_pos[0], self.end_selection_rect_pos[0]) * self.zoom_factor - self.viewport.x
y_ = min(self.begin_selection_rect_pos[1], self.end_selection_rect_pos[1]) * self.zoom_factor - self.viewport.y
width_ = abs(self.end_selection_rect_pos[0] - self.begin_selection_rect_pos[0]) * self.zoom_factor
height_ = abs(self.end_selection_rect_pos[1] - self.begin_selection_rect_pos[1]) * self.zoom_factor
rect_to_draw = pygame.Rect(x_, y_, width_, height_)
pygame.draw.rect(display, (255, 0, 0), rect_to_draw, 2)
self.pygame_draw_highlighted_rects_code(display)
self.pygame_draw_nodes(display)
self.pygame_draw_compartment_legends(display)
self.pygame_draw_lines(display)
self.pygame_search_mode(display, text_input_rect)
self.pygame_show_expression_or_fluxes(display)
self.pygame_event_handling_code(display)
## # Centre Dot
# unscaled_middle_x = display.get_width() / 2
# unscaled_middle_y = display.get_height() / 2
# dot_size = 5 # Define the dot size
# dot_color = (255, 165, 0) # Orange color
# pygame.draw.circle(display, dot_color, (int(unscaled_middle_x), int(unscaled_middle_y)), dot_size)
pygame.display.flip()
self.calculate_forces_through_network()
self.move_nodes_based_on_forces()
if pygame_on:
pygame.quit()
def draw_arrow_head(self, end, start, display, color_):
dx = end[0] - start[0]
dy = end[1] - start[1]
angle = math.atan2(dy, dx)
arrow_len = max(3, self.rect_size - 6)
arrow_angle = math.pi / 6
arrow1 = (end[0] - arrow_len * math.cos(angle - arrow_angle),
end[1] - arrow_len * math.sin(angle - arrow_angle))
arrow2 = (end[0] - arrow_len * math.cos(angle + arrow_angle),
end[1] - arrow_len * math.sin(angle + arrow_angle))
pygame.draw.line(display, color_, (start[0], start[1]), (end[0], end[1]))
pygame.draw.polygon(display, color_, (end, arrow1, arrow2))
def pygame_draw_highlighted_rects_code(self, display):
# highlighted rects
for node in self.all_network_nodes:
if node.visible_by_mouse and node.node_type != "boundary" and node.selected_by_drag_selection:
if self.show_compartments:
outer_rect = node.rect.inflate(15, 15)
scaled_outer_rect = pygame.Rect(outer_rect.x * self.zoom_factor - self.viewport.x,
outer_rect.y * self.zoom_factor - self.viewport.y,
outer_rect.width * self.zoom_factor,
outer_rect.height * self.zoom_factor)
outer_color = (0, 200, 0)
pygame.draw.rect(display, outer_color, scaled_outer_rect, 2) # Inn
elif node.node_type != "compartment":
outer_rect = node.rect.inflate(15, 15)
scaled_outer_rect = pygame.Rect(outer_rect.x * self.zoom_factor - self.viewport.x,
outer_rect.y * self.zoom_factor - self.viewport.y,
outer_rect.width * self.zoom_factor,
outer_rect.height * self.zoom_factor)
outer_color = (0, 200, 0)
pygame.draw.rect(display, outer_color, scaled_outer_rect, 2) # Inn
def pygame_draw_nodes(self, display):
for idx, node in enumerate(self.all_network_nodes):
if node.visible_by_mouse:
if node.node_type == "reaction":
scaled_rect = pygame.Rect(node.rect.x * self.zoom_factor - self.viewport.x,
node.rect.y * self.zoom_factor - self.viewport.y,
node.rect.width * self.zoom_factor,
node.rect.height * self.zoom_factor)