-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathTree.py
1605 lines (1500 loc) · 81 KB
/
Tree.py
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
"""
Defines the Tree of the MCTS: main object for RetroPath 3
"""
# General utilities
import os
import sys
import time
import logging
import argparse
import pickle
import string
import numpy as np
import csv
import random
# RP3 specific packages
from compound import Compound, unpickle, CompoundDefinitionException, ChemConversionError
from chemical_compounds_state import ChemicalCompoundState
from MCTS_node import MCTS_node
from representation import Test_representation, Test_to_file
from UCT_policies import Biochemical_UCT_1, Nature_UCT, Classical_UCT_RAVE, Classical_UCT_with_bias, Classical_UCT, \
Biochemical_UCT_1_with_RAVE, Biochemical_UCT_with_progressive_bias, Chemical_UCT_1, Biological_UCT_1, \
Biochemical_UCT_with_toxicity
from Rollout_policies import Rollout_policy_first, Rollout_policy_random_uniform_on_biochemical_multiplication_score, Rollout_policy_random_uniform
from rewarding import Basic_Rollout_Reward, RolloutRewards
from rule_sets_examples import applicable_rules_10_dict
from rule_sets_similarity import get_rules_and_score, full_rules_forward_H, full_rules_retro_H, full_rules_forward_no_H, \
full_rules_retro_no_H
from pathway import Pathway
from pathway_scoring import RandomPathwayScorer, constant_pathway_scoring, null_pathway_scoring, \
biological_pathway_scoring, biochemical_pathway_scoring
from tree_viewer import Tree_viewer
from organisms import (
# With Hs
bsubtilis_H,
core_ecoli_H,
detectable_cmpds_H,
ecoli_chassis_H,
iJO1366_chassis_H,
Test_organism_H,
# Without Hs
core_ecoli_noH,
bsubtilis_noH,
detectable_cmpds_noH,
ecoli_chassis_noH,
iJO1366_chassis_noH,
Test_organism_noH,
# Import function
import_organism_from_csv,
)
# General Configuration
from config import *
if use_toxicity:
from compound_scoring import toxicity_scorer
sys.setrecursionlimit(50000)
class RunModeError(Exception):
"""Class for Tree Mode exception."""
def __init__(self, retrosynthesis, biosensor):
self.message = "Choose between retrosynthesis ({}) and biosensor ({})".format(retrosynthesis, biosensor)
self.reason = "RunModeError"
class IncorrectTreeLoading(Exception):
"""Class for Conflicts between trees when loading a tree for search extension."""
def __init__(self, message):
self.message = message
self.reason = "IncorrectTreeLoading"
class myTimeoutException(Exception):
"""Class for Tree Timeout exception."""
def __init__(self, iteration=-1):
self.iteration = iteration
self.time = time.time()
self.message = "Timeout at time {}, at iteration {}".format(self.time, self.iteration)
class FirstResultException(Exception):
"""Class for Tree First Result Stop exception."""
def __init__(self, file_to_save, name, time_spent, iteration=-1):
self.message = "First result after {}s for compound {}".format(time_spent, name)
self.time = time_spent
self.iteration = iteration
with open(file_to_save, "w") as writer:
writer.write("{};{}".format(name, round(time_spent, 2)))
class CompoundInSink(Exception):
"""Class for raising exception if compound already in sink."""
def __init__(self, folder_to_save, name):
self.message = "Compound {} already in organism".format(name)
self.reason = "CompoundInSink"
with open("{}/in_sink".format(folder_to_save), "w") as results_file:
pass
class InvalidSink(Exception):
"""Class for raising exception if sink is invalid."""
def __init__(self):
self.reason = "InvalidSink"
self.message = "Invalid (empty) sink"
# def timeout_tree_search(signum, frame):
# """
# Used for raising myTimeoutException when the alloted time has been spent.
# Not in use at the moment - another strategy was defined that waits until the end of the iteration.
# """
# raise myTimeoutException
"""
The folllwoing commented functions were used for parallelisation.
They are not available at the publication of this tool.
"""
# def kill(pool):
# """Send SIGTERMs to kill all processes belonging to pool.
#
# Will not work on Windows OS.
# Necessary for killing RDKit processes that don't listen when on C++
# """
# # stop repopulating new child
# pool._state = mp.pool.TERMINATE
# pool._worker_handler._state = mp.pool.TERMINATE
# for p in pool._pool:
# os.kill(p.pid, signal.SIGKILL)
# # .is_alive() will reap dead process
# while any(p.is_alive() for p in pool._pool):
# pass
# # Get-lucky workaround: force releasing lock
# try:
# pool._inqueue._rlock.release()
# except ValueError as e:
# logging.error(e)
# pool.terminate()
# def worker_init_array(state_array, kwargs_local):
# # Using code from https://stackoverflow.com/questions/39322677/python-how-to-use-value-and-array-in-multiprocessing-pool
# global shared_array, kwargs
# shared_array = state_array
# kwargs = kwargs_local
# def worker_Rollout_with_array(i):
# """
# Used for storing intermediate results when performing multiple rollouts in parallel.
# Dropped at the moment due to the necessity of isolating RDkit processes in their own workers.
# - define multiple workers, each for a Rollout policy
# - they would need to not require arguments, no I'd have to duplicate the biochemical ones
# - the worker only takes the idnex of the array it is going to work on
# - the array itself (shared memory) and the kwargs will be defined globallly
# """
#
# # kwargs = kwargs["kwargs"]
# RolloutPolicy_name = kwargs["RolloutPolicy_name"]
# if RolloutPolicy_name == "Rollout_policy_first":
# RolloutPolicy = Rollout_policy_first()
# elif RolloutPolicy_name == "Rollout_policy_chemical_best":
# RolloutPolicy = Rollout_policy_chemical_best()
# elif RolloutPolicy_name == "Rollout_policy_biological_best":
# RolloutPolicy = Rollout_policy_biological_best()
# elif RolloutPolicy_name == "Rollout_policy_biochemical_addition_best":
# RolloutPolicy = Rollout_policy_biochemical_addition_best()
# elif RolloutPolicy_name == "Rollout_policy_biochemical_multiplication_best":
# RolloutPolicy = Rollout_policy_biochemical_multiplication_best()
# elif RolloutPolicy_name == "Rollout_policy_random_uniform":
# RolloutPolicy = Rollout_policy_random_uniform()
# elif RolloutPolicy_name == "Rollout_policy_random_uniform_on_chem_score":
# RolloutPolicy = Rollout_policy_random_uniform_on_chem_score()
# elif RolloutPolicy_name == "Rollout_policy_random_uniform_on_bio_score":
# RolloutPolicy = Rollout_policy_random_uniform_on_bio_score()
# elif RolloutPolicy_name == "Rollout_policy_random_uniform_on_biochemical_addition_score":
# RolloutPolicy = Rollout_policy_random_uniform_on_biochemical_addition_score()
# elif RolloutPolicy_name == "Rollout_policy_random_uniform_on_biochemical_multiplication_score":
# RolloutPolicy = Rollout_policy_random_uniform_on_biochemical_multiplication_score()
# else:
# raise NotImplementedError
# state = kwargs["state"]
# rewarding = kwargs["rewarding"]
# rollout_number = kwargs["rollout_number"]
# main_layer = kwargs["main_layer"]
# current_rollout = 0
# state = state.clone() # initial state before rollout
# available_moves = state.GetRolloutMoves(top_x=1)
# if retrosynthesis:
# state_result = state.GetResults_from_InChI_Keys(rewarding=rewarding, main_layer=main_layer)
# elif biosensor:
# state_result = state.GetResultsForBiosensors(rewarding=rewarding, main_layer=main_layer)
# else:
# raise NotImplementedError
#
# in_chassis = (state_result == rewarding.full_state_reward)
# shared_array[i] = state_result
# while (current_rollout < rollout_number and available_moves != {} and not in_chassis):
# move = RolloutPolicy.select_best_move(available_moves=available_moves)
# # move = list(available_moves.keys())[0] #Warning: Rollout Policy needs to be pickled
# state.ApplyMove(move)
# state = state.clone()
# if retrosynthesis:
# state_result = state.GetResults_from_InChI_Keys(rewarding=rewarding, main_layer=main_layer)
# elif biosensor:
# state_result = state.GetResultsForBiosensors(rewarding=rewarding, main_layer=main_layer)
# else:
# raise NotImplementedError
# in_chassis = (state_result == rewarding.full_state_reward)
# current_rollout = current_rollout + 1
# available_moves = state.GetRolloutMoves(top_x=1)
# shared_array[i] = state_result
# return state_result
class Tree(object):
"""
Defines a search on the Tree according to
- defined policy
- organism
Useful methods include:
- running the search (key method of this object)
- extracting the best pathway
- extracting all pathways
- visualising the tree
- extending the tree with more tolerant settings or simply more iterations.
- tree summary
Numerous utilities has been developped for exporting results.
"""
logger = logging.getLogger(__name__)
def __init__(self,
root_state, # starting chemical compound state (contains the target Compound only)
itermax=2, # Iteration budget
time_budget=20, # Time budget
expansion_width=10, # Number of allwoed children
available_rules=None, # Rule dataset that can be used
rewarding=Basic_Rollout_Reward, # How to reward the chemical state after rollout
max_depth=5, # Maximum number of reactions to be used
max_rollout=3,
number_rollout=1, # if parallel, number of different rollouts performed. NOT USED
UCT_policy="Classical_UCT",
UCT_parameters={"UCTK": 2, "bias_k": 0},
Rollout_policy="Rollout_policy_first",
Rollout_parameters={"rollout_timeout": 0.2},
print_tree_information=True,
parallel=False,
main_layer_tree=False,
main_layer_chassis=True,
organism=ecoli_chassis_H,
chemical_scorer="RandomChemicalScorer",
biological_scorer="RandomBiologicalScorer",
folder_to_save="tests/generated_jsons",
virtual_visits=0,
progressive_bias_strategy=None,
progressive_widening=False,
heavy_saving=False,
minimal_visit_counts=1,
use_RAVE=False,
pathway_scoring="null_pathway_scoring"):
# Chemical equality between nodes in the stree: only main layer or full inchi
self.main_layer_tree = main_layer_tree
self.main_layer_chassis = main_layer_chassis
self.organism = organism
self.organism.set_main_layer(main_layer_chassis)
self.root_state = root_state
self.root_state.set_organism(self.organism)
self.root_state.set_main_layer(self.main_layer_tree) # Chassis only used in the chassis
# Defaut rules for pytest - small subset
if available_rules is None:
self.available_rules = applicable_rules_10_dict
else:
self.available_rules = available_rules
# Define rules and scores settings for the root state.
self.root_state.set_available_rules(self.available_rules)
self.root_state.set_chemical_scorer(chemical_scorer)
self.root_state.set_biological_scorer(biological_scorer)
self.scorer_info = "Chemical scoring is {}\n. Biological scoring is {}\n".format(chemical_scorer,
biological_scorer)
# Define initial node of the Tree with all previous information
self.root_node = MCTS_node(root_state,
rewarding=rewarding,
expansion_width=expansion_width,
maximum_depth=max_depth,
main_layer_tree=self.main_layer_tree,
main_layer_chassis=self.main_layer_chassis,
chemical_scorer=chemical_scorer,
biological_scorer=biological_scorer,
virtual_visits=virtual_visits,
progressive_bias_strategy=progressive_bias_strategy,
minimal_visit_counts=minimal_visit_counts,
use_RAVE=use_RAVE)
# Defining attributes from init
self.expansion_width = expansion_width
self.progressive_widening = progressive_widening
self.itermax = itermax
self.time_budget = time_budget
self.rewarding = rewarding
self.UCT_policy = UCT_policy
self.UCT_parameters = UCT_parameters
self.max_depth = max_depth
self.max_rollout = max_rollout
self.Rollout_policy = Rollout_policy
self.Rollout_parameters = Rollout_parameters
self.pathway_scoring = pathway_scoring
# Saving settings
self.folder_to_save = folder_to_save
self.folder_to_save_pickles = "{}/{}".format(folder_to_save, "pickles")
self.heavy_saving = heavy_saving
self.print_tree_information = True
self.parallel = parallel
if self.parallel:
"""
Should not be used at the moment.
Used to conduct multiple rollouts in parallel.
Impossible with current RDKit lack of timeout
"""
self.worker = worker_Rollout_with_array
self.number_rollout = number_rollout
else:
self.number_rollout = 1 # When not doing in parallel
self.recap = None # Used for storing results and information that will be outputed in simplified foramt.
def set_folder_to_save(self, folder_to_save):
self.folder_to_save = folder_to_save
self.folder_to_save_pickles = "{}/{}".format(folder_to_save, "pickles")
def set_heavy_saving(self, heavy_saving):
self.heavy_saving = heavy_saving
def set_rules(self, rules):
self.available_rules = rules
# Change also for all nodes.
nodes_to_treat = [self.root_node]
while nodes_to_treat != []:
node = nodes_to_treat[0]
del nodes_to_treat[0]
node.state.set_available_rules(rules)
for child in node.children:
nodes_to_treat.append(child)
def __len__(self):
length = 0
nodes_to_treat = [self.root_node]
while nodes_to_treat != []:
node = nodes_to_treat[0]
del nodes_to_treat[0]
length = length + 1
for child in node.children:
nodes_to_treat.append(child)
return length
def set_itermax(self, itermax):
self.itermax = itermax
def run_search(self, stop_at_first_result=False):
"""
Main method for using RetroPath 3.
Runs a tree search for itermax iterations:
- starts from root
- while node have children, select the best
- expand the leaf if possible. Select the best child of the expanded node
- rollout from this node
- update all results
- save pathways as they are found
"""
UCT_policy = self._get_UCT_policy()
pathway_scoring = self._get_pathway_scoring()
if self.print_tree_information:
self._print_tree_information_beginning()
# Signal below is dropped in favour of checking at the beginning of an iteration if there is time left.
# signal.signal(signal.SIGALRM, timeout_tree_search)
# signal.alarm(self.time_budget)
selection_time = 0
expansion_time = 0
rollout_time = 0
update_time = 0
raise_stop = False
start_tree_search_time = time.time()
try:
for i in range(self.root_node.visits - self.root_node.virtual_visits,
self.itermax + self.root_node.visits - self.root_node.virtual_visits):
# exploration and EXPANSION
if time.time() - start_tree_search_time > self.time_budget:
raise myTimeoutException(iteration=i)
self.logger.debug("Currently performing iteration {}".format(i))
if i % int(round(self.itermax / 10)) == 0:
self.logger.info("Performing iteration {} out of {}".format(i, self.itermax))
if self.heavy_saving:
# Saving Tree for further analysis during teh search.
self.find_full_tree(iteration=i)
self.save(file_name="{}_iteration_{}".format(self.root_state.compound_list[0], i),
folder_address=self.folder_to_save_pickles)
self.jsonify_full_tree(file_name="{}_iteration_{}".format(self.root_state.compound_list[0], i))
# A new iteration starts from the root node.
node = self.root_node
start_selection_time = time.time()
while node.children != [] and not node.terminal:
if node.flag_for_extension:
# When extending a previous tree.
node.expand_later_iteration(extension_length = node.flag_extension_length,
maximum_depth = node.flag_maximum_depth,
chemical_scoring_configuration = node.flag_chemical_scoring_configuration)
if not self.progressive_widening and node.moves == []:
# Go down the tree while all moves from a node has been expanded.
node = node.UCTSelectChild(UCT_policy=UCT_policy)
state = node.state
elif self.progressive_widening:
if node.moves == []: # No moves are available for PW.
node = node.UCTSelectChild(UCT_policy=UCT_policy)
state = node.state
else: # there are still available moves, apply PW condition
if node.visits <= len(node.children) ^ 2:
node = node.UCTSelectChild(UCT_policy=UCT_policy)
state = node.state
else:
break
else:
break
selection_time = selection_time + time.time() - start_selection_time
start_expansion_time = time.time()
if node.moves != [] and not node.terminal: # This node can be expanded.
move = node.moves[0]
looping_move = False
for product in move.product_list:
if product.in_list(node.history.compound_list, main_layer=node.main_layer_chassis):
looping_move = True
self.logger.info("Looping move in node {}-{} for move {}".format(node.state, node.level, move))
node.moves.remove(move)
break
if not looping_move:
node.AddChild(move, node.state)
node = node.UCTSelectChild(UCT_policy=UCT_policy)
state = node.state
expansion_time = expansion_time + time.time() - start_expansion_time
# Perform rollout on the selected node
if not node.terminal:
start_rollout_time = time.time()
allowed_rollout = min(self.max_rollout, self.max_depth - node.level)
if self.parallel:
"""
Not in use at the moment.
Made for performing multiple rollouts on the same node.
Was temporarily suspended due to the necessity of encapsulating Rdkit preocesses.
"""
shared_array_for_rollout = mp.Array('d', self.number_rollout)
kwargs_local = {"state": node.state,
"rewarding": self.rewarding,
"rollout_number": allowed_rollout,
"RolloutPolicy_name": self.Rollout_policy,
"main_layer": self.main_layer_chassis}
_pool = mp.Pool(processes=4, initializer=worker_init_array,
initargs=(shared_array_for_rollout, kwargs_local))
try:
_pool.map(worker_Rollout_with_array, range(self.number_rollout))
except mp.TimeoutError as e:
self.logger.warning("Time out in parllel workers for node \n{}".format(node))
kill(_pool)
result, solved = np.mean(shared_array_for_rollout[:]), self.rewarding.full_state_reward in shared_array_for_rollout[:]
else:
# Perform rollout without parallelisation.
RolloutPolicy = self._get_Rollout_policy()
state = node.rollout(rollout_number=allowed_rollout, RolloutPolicy=RolloutPolicy)
if retrosynthesis:
result = state.GetResults_from_InChI_Keys(rewarding=self.rewarding,
main_layer=self.main_layer_chassis)
solved = state.GetResults_from_InChI_Keys(rewarding=self.rewarding,
main_layer=self.main_layer_chassis) == self.rewarding.full_state_reward
elif biosensor:
result = state.GetResultsForBiosensors(rewarding=self.rewarding,
main_layer=self.main_layer_chassis)
solved = state.GetResultsForBiosensors(rewarding=self.rewarding,
main_layer=self.main_layer_chassis) == self.rewarding.full_state_reward
else:
raise NotImplementedError
self.logger.info("Rollout results are {}, {}".format(result, solved))
rollout_time = rollout_time + time.time() - start_rollout_time
else:
# Node is already terminal.
start_rollout_time = time.time()
state = node.state
if retrosynthesis:
result = state.GetResults_from_InChI_Keys(rewarding=self.rewarding,
main_layer=self.main_layer_chassis)
solved = state.GetResults_from_InChI_Keys(rewarding=self.rewarding,
main_layer=self.main_layer_chassis) == self.rewarding.full_state_reward
elif biosensor:
result = state.GetResultsForBiosensors(rewarding=self.rewarding,
main_layer=self.main_layer_chassis)
solved = state.GetResultsForBiosensors(rewarding=self.rewarding,
main_layer=self.main_layer_chassis) == self.rewarding.full_state_reward
else:
raise NotImplementedError
if solved and not node.has_a_solved_child:
# Extract pathway if encountered from the first time and fully solved.
self.logger.info("Pathway is found at iteration {}".format(i))
found_pathway = self.extract_pathway_from_bottom(node, iteration=i)
if len(found_pathway) == 1:
name = str(self.root_state.compound_list[0]) + "iteration_{}".format(i)
if self.heavy_saving:
found_pathway[0]["pathway"].save(name, folder_address=self.folder_to_save_pickles)
result = pathway_scoring.calculate(found_pathway[0]["pathway"])
else:
best_path = None
for path in found_pathway:
name = str(self.root_state.compound_list[0]) + "iteration_{}_{}".format(i,
path["number"])
if self.heavy_saving:
path["pathway"].save(name, folder_address=self.folder_to_save_pickles)
result = pathway_scoring.calculate(path["pathway"])
if best_path is None:
best_path = path
best_result = result
else:
if best_result < result:
best_path = path
best_result = result
if stop_at_first_result:
raise_stop = True
# Backpropagate:
start_update_time = time.time()
while node is not None: # backpropagate from the expanded node and work back to the root node
node.update(result,
solved=solved,
visit_number=self.number_rollout,
iteration=i)
node = node.parent
update_time = update_time + time.time() - start_update_time
if raise_stop:
time_spent = time.time() - start_tree_search_time
raise FirstResultException(
file_to_save="{}/{}_execution_time.txt".format(self.folder_to_save, self.root_state.state_name),
name=self.root_state.state_name,
time_spent=time_spent,
iteration=i)
except myTimeoutException as e:
self.logger.warning(
"Timeout happened on Tree search after {} iterations for a budget of {}s".format(i, self.time_budget))
self.recap = {"TIME_EXECUTION": round(e.time - start_tree_search_time, 2),
"STOP_REASON": "timeout",
"NUMBER_ITERATION": e.iteration}
except FirstResultException as e:
self.logger.warning(e.message)
self.recap = {"TIME_EXECUTION": round(e.time, 2),
"STOP_REASON": "first_result",
"NUMBER_ITERATION": e.iteration}
if self.print_tree_information:
self._print_tree_information_end(selection_time, expansion_time, rollout_time, update_time)
logging.info("At the end of this tree search, the cache contains {}".format(len(home_made_cache.keys())))
if self.recap is None:
self.recap = {"TIME_EXECUTION": round(time.time() - start_tree_search_time, 2),
"STOP_REASON": "iteration",
"NUMBER_ITERATION": i}
self.logger.warning("RECAP TIME_EXECUTION={}".format(self.recap["TIME_EXECUTION"]))
self.logger.warning("RECAP STOP_REASON={}".format(self.recap["STOP_REASON"]))
self.logger.warning("RECAP NUMBER_ITERATION={}".format(self.recap["NUMBER_ITERATION"]))
if self.heavy_saving:
self.find_full_tree(iteration=i)
self.save(file_name="{}_iteration_{}".format(self.root_state.compound_list[0], i),
folder_address=self.folder_to_save_pickles)
self.jsonify_full_tree(file_name="{}_iteration_{}".format(self.root_state.compound_list[0], i))
def _get_UCT_policy(self):
if self.UCT_policy == "Classical_UCT":
policy = Classical_UCT(self.UCT_parameters)
elif self.UCT_policy == "Classical_UCT_with_bias":
policy = Classical_UCT_with_bias(self.UCT_parameters)
elif self.UCT_policy == "Classical_UCT_RAVE":
policy = Classical_UCT_RAVE(parameters=self.UCT_parameters)
elif self.UCT_policy == "Nature_UCT":
policy = Nature_UCT(self.UCT_parameters)
elif self.UCT_policy == "Biochemical_UCT_1":
policy = Biochemical_UCT_1(self.UCT_parameters)
elif self.UCT_policy == "Biochemical_UCT_with_progressive_bias":
policy = Biochemical_UCT_with_progressive_bias(self.UCT_parameters)
elif self.UCT_policy == "Biochemical_UCT_1_with_RAVE":
policy = Biochemical_UCT_1_with_RAVE(self.UCT_parameters)
elif self.UCT_policy == "Chemical_UCT_1":
policy = Chemical_UCT_1(self.UCT_parameters)
elif self.UCT_policy == "Biological_UCT_1":
policy = Biological_UCT_1(self.UCT_parameters)
elif self.UCT_policy == "Biochemical_UCT_with_toxicity":
policy = Biochemical_UCT_with_toxicity(self.UCT_parameters)
else:
raise NotImplementedError(self.UCT_policy)
return policy
def _get_Rollout_policy(self):
if self.Rollout_policy == "Rollout_policy_first":
policy = Rollout_policy_first()
elif self.Rollout_policy == "Rollout_policy_chemical_best":
policy = Rollout_policy_chemical_best()
elif self.Rollout_policy == "Rollout_policy_biological_best":
policy = Rollout_policy_biological_best()
elif self.Rollout_policy == "Rollout_policy_biochemical_addition_best":
policy = Rollout_policy_biochemical_addition_best()
elif self.Rollout_policy == "Rollout_policy_biochemical_multiplication_best":
policy = Rollout_policy_biochemical_multiplication_best()
elif self.Rollout_policy == "Rollout_policy_random_uniform":
policy = Rollout_policy_random_uniform()
elif self.Rollout_policy == "Rollout_policy_random_uniform_on_chem_score":
policy = Rollout_policy_random_uniform_on_chem_score()
elif self.Rollout_policy == "Rollout_policy_random_uniform_on_bio_score":
policy = Rollout_policy_random_uniform_on_bio_score()
elif self.Rollout_policy == "Rollout_policy_random_uniform_on_biochemical_addition_score":
policy = Rollout_policy_random_uniform_on_biochemical_addition_score()
elif self.Rollout_policy == "Rollout_policy_random_uniform_on_biochemical_multiplication_score":
policy = Rollout_policy_random_uniform_on_biochemical_multiplication_score()
else:
raise NotImplementedError(self.RolloutPolicy)
return policy
def _get_pathway_scoring(self):
self.pathway_scoring_logs = False
if self.pathway_scoring == "RandomPathwayScorer":
pathway_scoring = RandomPathwayScorer
elif self.pathway_scoring == "constant_pathway_scoring":
pathway_scoring = constant_pathway_scoring
elif self.pathway_scoring == "biological_pathway_scoring":
pathway_scoring = biological_pathway_scoring
elif self.pathway_scoring == "null_pathway_scoring":
pathway_scoring = null_pathway_scoring
else:
raise NotImplementedError(self.pathway_scoring)
return pathway_scoring
def _print_tree_information_beginning(self):
test_block = "---------------Beginning of search informations------------------ \n"
text_block = test_block + "UCT policy is : {} \n".format(str(self.UCT_policy))
text_block = text_block + "Rollout policy is : {} \n".format(str(self.Rollout_policy))
text_block = text_block + "Rewarding policy is : {} \n".format(str(self.rewarding))
text_block = text_block + 'Maximum number of iterations {} \n'.format(self.itermax)
start_time = time.localtime()
self.starttime = time.time()
text_block = text_block + 'Tree search started running at {}h {}min {}s \n'.format(start_time.tm_hour,
start_time.tm_min,
start_time.tm_sec)
text_block = text_block + 'Your tree search is currently running ... \n \n'
self.logger.info(text_block)
def _print_tree_information_end(self, selection_time=0, expansion_time=0, rollout_time=0, update_time=0):
end_time = time.localtime()
test_block = "---------------End of search informations------------------ \n"
text_block = test_block + 'Tree search finished running at {}h {}min {}s \n'.format(end_time.tm_hour,
end_time.tm_min,
end_time.tm_sec)
text_block = text_block + 'Your tree search took {:.1e}s \n \n'.format(time.time() - round(self.starttime))
text_block = text_block + 'Time was spent in selection: {:.1e}s, expansion: {:.1e}s, rollout: {:.1e}s, update: {:.1e}s \n'.format(
selection_time, expansion_time, rollout_time, update_time)
if self.root_node.has_a_solved_child:
text_block = text_block + "CONGRATULATIONS, THATS A WIN"
else:
text_block = text_block + "You just lost the game"
self.logger.info(text_block)
def __repr__(self):
"""
Represents the tree horizontally for small cases
"""
rep = ''
node_list = [self.root_node]
while node_list != []:
current_node = node_list[-1]
del node_list[-1]
rep = rep + str(current_node.level) + str(current_node) + "\n"
for child in current_node.children:
node_list.append(child)
return rep
def __eq__(self, other):
"""
Verifying whether 2 Trees are identical. Will be useful for comparison of UCT methods
- Trees are identical if all their nodes are recursively identical
"""
self_pile = [self.root_node]
other_pile = [other.root_node]
equal = (self.root_node == other.root_node)
if not equal:
return False
while self_pile != [] and other_pile != [] and equal:
current_node_self = self_pile[-1]
del self_pile[-1]
self_pile = self_pile + current_node_self.children
found = False
for node in other_pile:
if node == current_node_self:
current_node_other = node
found = True
if not found:
# Quits the loop with the return statement.
return False
other_pile.remove(current_node_other)
equal = (current_node_other == current_node_self) # it's been selected for this
other_pile = other_pile + current_node_other.children
return equal
def jsonify_full_tree(self, file_name=None, folder_to_save=None):
"""
- prints the whole tree. Useful to see where the search got lost.
- uses the json format for node and moves
- create a Tree viewer object
"""
if file_name is None:
file_name = self.root_state.state_name
if folder_to_save is None:
folder_to_save = self.folder_to_save
file_to_save = folder_to_save + "/{}_full_tree_for_MCTS.json".format(file_name)
# First, assign IDs to all moves and compounds
id_move = 0
id_node = 0
nodes_to_treat = [self.root_node]
while nodes_to_treat != []:
node = nodes_to_treat[0]
del nodes_to_treat[0]
if node.move is not None:
node.move.set_id(id_move)
id_move = id_move + 1
node.set_id(id_node)
id_node = id_node + 1
for child in node.children:
nodes_to_treat.append(child)
tree_viewer = Tree_viewer(file_to_save=file_to_save)
nodes_to_treat = [self.root_node]
while nodes_to_treat != []:
node = nodes_to_treat[0]
del nodes_to_treat[0]
tree_viewer.add_node(node)
for child in node.children:
nodes_to_treat.append(child)
tree_viewer.jsonify_tree_viewer()
def save(self, file_name=None, folder_address="pickled_data"):
if self.__class__.__module__ == "__main__":
self.logger.warning("Tree should not be in main for pickling")
if file_name is None:
base_name = self.root_state.state_name
i = 1
self.logger.info("Tree is saved at {}/tree_{}_{}.pkl".format(folder_address, base_name, i))
while os.path.exists("{}/tree_{}_{}.pkl".format(folder_address, base_name, i)):
i += 1
file_name = base_name + '_' + str(i)
file_saving = open('{}/tree_{}.pkl'.format(folder_address, file_name), 'wb')
pickle.dump(self, file_saving)
def equality_visited_states(self, other):
"""
Verifying whether 2 Trees explored the same states. Will be useful for comparison of UCT methods
- Trees are identical if all their nodes are recursively identical
- contrary to identify function, checks states but not visit counts.
"""
self_pile = [self.root_node]
other_pile = [other.root_node]
equal = (self.root_node.state == other.root_node.state)
if not equal:
return False
while self_pile != [] and other_pile != [] and equal:
current_node_self = self_pile[-1]
del self_pile[-1]
self_pile = self_pile + current_node_self.children
found = False
for node in other_pile:
if node.state == current_node_self.state:
current_node_other = node
found = True
if not found:
return False
other_pile.remove(current_node_other)
equal = (current_node_other.state == current_node_self.state)
other_pile = other_pile + current_node_other.children
return equal
def extract_pathway_from_bottom(self, node, name=None, iteration=-1):
"""
Extract pathways from found state (and not from the top down)
"""
bottom_up_pathway = Pathway(first_iteration=iteration, target=None,
compounds=[], moves=[],
main_layer=self.main_layer_chassis,
organism=self.organism,
edges=[],
nodes_compounds=[],
nodes_transformations=[])
target = self.root_state.compound_list[0]
bottom_up_pathway.add_compound(target, is_source=1)
if name is None:
name = str(target)
file_to_save = self.folder_to_save + "/{}_iteration_{}.json".format(name, iteration)
bottom_up_pathway.set_file_to_save(file_to_save)
if use_transpositions:
complete_pathways = []
pathways_to_treat = [{"pathway": bottom_up_pathway, "number": "a", "node_list": [node]}]
while pathways_to_treat != []:
current_pathway_node = pathways_to_treat[0]
del pathways_to_treat[0]
pathway = current_pathway_node["pathway"].clone()
number = current_pathway_node["number"]
node_list = current_pathway_node["node_list"]
node = node_list[-1]
if not node.parent is None:
node_parents = transposition_table[node.parent.hash]
if len(node_parents) == 1:
node_list.append(node.parent)
new_pathway = {"pathway": pathway,
"number": number,
"node_list": node_list}
pathways_to_treat.append(new_pathway)
else:
for i in range(len(node_parents)):
parent = node_parents[i]
new_node_list = copy.deepcopy(node_list)
new_pathway = pathway.clone()
new_node_list.append(parent)
new_pathway = {"pathway": new_pathway,
"number": number + '_' + list(string.ascii_lowercase)[i],
"node_list": new_node_list}
pathways_to_treat.append(new_pathway)
else:
complete_pathways.append(current_pathway_node)
for pathway_as_dict in complete_pathways:
pathway = pathway_as_dict["pathway"]
number = pathway_as_dict["number"]
node_list = pathway_as_dict["node_list"]
node_list.reverse()
for top_down_node in node_list[1:]:
pathway.add_reaction(top_down_node.move, depth=top_down_node.level)
file_to_save = self.folder_to_save + "/{}_iteration_{}_{}.json".format(name, iteration, number)
pathway.set_file_to_save(file_to_save)
pathway.jsonify_scope_viewer()
return complete_pathways
else:
nodelist = [node]
while node.parent is not None:
# Going up the tree to get the parents
nodelist.append(node.parent)
node = node.parent
nodelist.reverse()
for top_down_node in nodelist[1:]:
bottom_up_pathway.add_reaction(top_down_node.move, depth=top_down_node.level)
bottom_up_pathway.set_file_to_save(file_to_save)
bottom_up_pathway.jsonify_scope_viewer()
return [{"pathway": bottom_up_pathway}]
def find_single_best_pathway(self, policy="visits", folder_to_save="pathways", name=None):
"""
Currently, best according to number of visits.
"""
best_pathway = Pathway(first_iteration=-1, target=None,
compounds=[], moves=[],
main_layer=self.main_layer_chassis,
organism=self.organism,
edges=[],
nodes_compounds=[],
nodes_transformations=[])
target = self.root_state.compound_list[0]
best_pathway.add_compound(target, is_source=1)
if policy == "visits":
self.logger.info(
"According to Wikipedia, choosing the pathway with the most visists \n This could be replaced by the best score")
if name is None:
name = str(target)
file_to_save = folder_to_save + "/{}_best.json".format(name)
best_pathway.set_file_to_save(file_to_save)
node = self.root_node
while not node.terminal:
# Could be modified with children cashing
node = node.SelectBestChild(policy=policy)
best_pathway.add_reaction(node.move, depth=node.level)
best_pathway.jsonify_scope_viewer()
def find_multiple_best_pathways(self, folder_to_save="pathways",
name=None, return_result=False,
return_pathways = False, biochem_sorted = False):
"""
Returns all solved pathways during the search.
They are sorted according to biochemical score.
"""
# Have a pile of patwhays to test and add. Only add patwhays that are fully solved. Export them all
pathways_to_print = []
pathway_iteration = 1
if self.root_node.has_a_solved_child:
initial_pathway = Pathway(first_iteration=-1, target=None,
compounds=[], moves=[],
main_layer=self.main_layer_chassis,
organism=self.organism,
edges=[],
nodes_compounds=[],
nodes_transformations=[])
target = self.root_state.compound_list[0]
initial_pathway.add_compound(target, is_source=1)
if name is None:
name = str(target)
# Start by treating the initla pathway
max_number = 0
pathways_to_treat = [{"pathway": initial_pathway, "node": self.root_node, "number": 1}]
while pathways_to_treat != []:
# Obtain and delete patwhay
current_pathway_node = pathways_to_treat[0]
del pathways_to_treat[0]
node = current_pathway_node["node"]
pathway = current_pathway_node["pathway"]
number = current_pathway_node["number"]
if node.move is not None:
pathway.add_reaction(node.move, depth=node.level)
if node.terminal:
# If the node is terminal, add the creating move in the pwathway and stop there
if pathway in pathways_to_print:
self.logger.debug("Pathway is already present: \n {}".format(pathway))
else:
pathways_to_print.append(pathway)
else:
# Extracting the nodes that have solved children
nodes_to_treat = []
for child in node.children:
if child.has_a_solved_child:
nodes_to_treat.append(child)
children_with_solved_num = len(nodes_to_treat)
for i in range(len(nodes_to_treat)):
# for i in range(len(nodes_to_treat)):
new_pathway = pathway.clone()
new_number = max_number + i + number
pathways_to_treat.append(
{"pathway": new_pathway, "node": nodes_to_treat[i], "number": new_number})
max_number = new_number + 1
current_pile_length = len(pathways_to_treat)
self.logger.info("Found {} pathways for {}".format(len(pathways_to_print), str(target)))
else:
pathways_to_print = []
self.logger.info("No pathway was found for this compound")
if biochem_sorted:
sorted_pathways_couples = [(pathway, round(biochemical_pathway_scoring.calculate(pathway), 2)) for pathway in pathways_to_print]
sorted_pathways = sorted(sorted_pathways_couples, key=lambda item: item[1], reverse=True)
for j in range(len(sorted_pathways)):
pathway = sorted_pathways[j][0]
file_to_save = folder_to_save + "{}_{}.json".format(name, j + 1)
pathway.set_file_to_save(file_to_save)
pathway.jsonify_scope_viewer()
sorted_pathways = [patwhay for patwhay, score in sorted_pathways]
else:
sorted_pathways = pathways_to_print
for j in range(len(sorted_pathways)):
pathway = sorted_pathways[j]
file_to_save = folder_to_save + "/{}_{}.json".format(name, j + 1)
pathway.set_file_to_save(file_to_save)
pathway.jsonify_scope_viewer()
if return_result:
return len(sorted_pathways)
if return_pathways:
return sorted_pathways
def find_full_scope(self, folder_to_save="pathways", name=None):
"""
Returns the scope of the compound: all pathways leading to the chassis.
"""
pile_to_treat = []
pathways_to_print = []
pathway_iteration = 1
full_scope = Pathway(first_iteration=-1, target=None,
compounds=[], moves=[],
main_layer=self.main_layer_chassis,
organism=self.organism,
edges=[],
nodes_compounds=[],
nodes_transformations=[])
target = self.root_state.compound_list[0]
full_scope.add_compound(target, is_source=1)
if name is None:
name = str(target)
max_number = 0
nodes_to_treat = [self.root_node]
while nodes_to_treat != []:
node = nodes_to_treat[0]
del nodes_to_treat[0]