-
Notifications
You must be signed in to change notification settings - Fork 1
/
BalanceRxns.py
1919 lines (1842 loc) · 70.2 KB
/
BalanceRxns.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
# %load ./BalanceRxns.py
from typing import List, Union
import pandas as pd
from AnalgRxns import getspecdat_rxn, userefrxns
from MainFunctions import CustomError, getfragments, getcompdict, initray, molfromsmiles
# from func_timeout import func_timeout, FunctionTimedOut
from chempy import balance_stoichiometry
import copy
from collections import Counter, OrderedDict
from decimal import Decimal, ROUND_HALF_UP
from rdkit import Chem # Importing RDKit
from rdkit.Chem import rdChemReactions # Reaction processing
# from rdkit.Chem.rdMolDescriptors import CalcMolFormula
from rxnmapper import RXNMapper
from math import ceil
import modin.pandas as mpd
def balance_analogue_(
analoguerxns,
refbalrxns=None,
coefflim=6,
reaxys_updated=True,
includesolv=True,
usemapper=True,
helpprod=True,
helpreact=False,
addrctonly=False,
ignoreH=False,
ncpus=16,
restart=True,
):
"""
Applies balance_analogue across each row of a given dataframe
"""
# breakpoint()
if not analoguerxns.index.name and not analoguerxns.index.names:
idxreset = True
else:
idxreset = False
idxcol = []
if reaxys_updated:
idxcol = ["ReactionID", "Instance"]
else:
idxcol = ["ReactionID"]
if refbalrxns is not None:
analoguerxns, commondf = userefrxns(
analoguerxns, idxcol=idxcol, refanaloguerxns=refbalrxns
)
idxreset = False
if not analoguerxns.empty:
if ncpus > 1:
if restart:
initray(num_cpus=ncpus)
if not idxreset:
analoguerxns.reset_index(inplace=True)
idxreset = True
analoguerxnsdis = mpd.DataFrame(analoguerxns)
else:
analoguerxnsdis = analoguerxns
balrxns = analoguerxnsdis.apply(
balance_analogue,
coefflim=6,
includesolv=includesolv,
usemapper=usemapper,
helpprod=helpprod,
helpreact=helpreact,
addrctonly=addrctonly,
ignoreH=ignoreH,
axis=1,
result_type="reduce",
)
balrxns = pd.Series(
data=balrxns.values, index=balrxns.index
) # Optional convert modin back to pandas
analoguerxnsbal = pd.DataFrame(balrxns, columns=["rxnsmiles"])
analoguerxnsbal[
[
"rxnsmiles0",
"balrxnsmiles",
"msg",
"LHS",
"RHS",
"hcrct",
"hcprod",
"LHSdata",
"RHSdata",
]
] = pd.DataFrame(
analoguerxnsbal["rxnsmiles"].tolist(), index=analoguerxnsbal.index
)
analoguerxnsbal[["NumRefs", "NumSteps", "NumStages"]] = analoguerxns[
["NumRefs", "NumSteps", "NumStages"]
]
cols = [
"NumRefs",
"NumSteps",
"NumStages",
"rxnsmiles0",
"balrxnsmiles",
"msg",
"LHS",
"RHS",
"hcrct",
"hcprod",
"LHSdata",
"RHSdata",
]
if idxreset:
analoguerxnsbal[idxcol] = analoguerxns[idxcol]
cols = idxcol + cols
analoguerxnsbal = analoguerxnsbal[cols]
if idxreset:
analoguerxnsbal.set_index(idxcol, inplace=True)
if refbalrxns and not commondf.empty: # Indices need to match!
analoguerxnsbal = pd.concat([analoguerxnsbal, commondf])
else:
analoguerxnsbal = commondf
balrxns = []
return balrxns, analoguerxnsbal
def balance_analogue(
row,
basic=True,
balance=True,
coefflim=6,
includesolv=True,
usemapper=True,
helpprod=True,
helpreact=False,
addrctonly=False,
ignoreH=False,
): # More reliable
"""
Applies balancerxn function across a given dataframe row
"""
Rdata = {}
Pdata = {}
Rgtdata = {}
Solvdata = {}
Rgtid = []
hc_prod = {}
hc_react = {}
Rdata = copy.deepcopy(row["Rdata"])
Pdata = copy.deepcopy(row["Pdata"])
Rgtdata = copy.deepcopy(row["Rgtdata"])
if row["ReagentID"] != "NaN":
Rgtid = copy.deepcopy(row["ReagentID"])
if helpprod:
hc_prod = copy.deepcopy(row["hc_prod"])
if helpreact:
hc_react = copy.deepcopy(row["hc_react"])
if includesolv:
Solvdata = copy.deepcopy(row["Solvdata"])
if type(Rdata) != dict: # Error or compound invalid
if basic and balance:
return "Error", "Error", Rdata, "NaN", "NaN", [], [], "NaN", "NaN"
else:
return "Error", Rdata, "NaN", "NaN", [], [], "NaN", "NaN"
elif type(Pdata) != dict: # Error or compound invalid
if basic and balance:
return "Error", "Error", Pdata, "NaN", "NaN", [], [], "NaN", "NaN"
else:
return "Error", Pdata, "NaN", "NaN", [], [], "NaN", "NaN"
rxnsmiles0 = ">>".join(
[
getfragments([Rdata[r]["smiles"] for r in Rdata], smiles=True),
getfragments([Pdata[p]["smiles"] for p in Pdata], smiles=True),
]
)
if basic and not balance:
return rxnsmiles0, list(Rdata.keys()), list(Pdata.keys())
else:
# return False
# breakpoint()
return balancerxn(
Rdata,
Pdata,
Rgtdata=Rgtdata,
Solvdata=Solvdata,
rxnsmiles0=rxnsmiles0,
usemapper=usemapper,
coefflim=coefflim,
hc_prod=hc_prod,
hc_react=hc_react,
addrctonly=addrctonly,
ignoreH=ignoreH,
)
def balancerxn(
Rdata,
Pdata,
Rgtdata={},
Solvdata={},
rxnsmiles0=None,
first=True,
usemapper=True,
addedspecies=[],
addedhc=[],
hc_prod={},
hc_react={},
coefflim=6,
msg="",
mandrcts={},
addrctonly=False,
ignoreH=False,
):
"""
Balances reactions given reactant species information (Rdata) and product species information (Pdata)
Rgtdata is optional and refers to reagent species information
Solvdata is optional and refers to solvent species information
rxnsmiles0 refers to the reaction SMILES string as represented in Reaxys
first is True/False depending on whether it is the first time running through the code
usemapper is True if IBM RXN mapper is used to decide between possible reactants on LHS
addedspecies refers to new species added to the LHS
addedhc refers to small species (help reactants) added to the LHS
hc_prod is optional and is a dictionary of small species (help compounds) to use for balancing the RHS
hc_react is optional and is a dictionary of small species (help reactants) to use for balancing the LHS
coefflim refers to the maximum allowed stoichiometric coefficient after balancing
msg involves any warning messages or updates from the code
mandrcts is a list of mandatory reactants (To avoid balancer from removing them)
ignoreH refers to a boolean switch (True if all hydrogen species except H2 are ignored/not added)
"""
if Solvdata: # Add sovents
Rgtdata = {**Rgtdata, **Solvdata} # Newly added
#%% Initialize added species/addedhc (help compound) and add small species
if not mandrcts:
mandrcts = copy.deepcopy(Rdata)
if first:
addedspecies = []
addedhc = []
# if not mandrcts:
# mandrcts = copy.deepcopy(Rdata)
if Rgtdata:
# smallspecies=[spec for spec in Rgtdata if Rgtdata[spec]['formula'] in ['H2','O2','H2O','OH2','HOH'] if spec not in Solvdata]
# smallspecies=[spec for spec in Rgtdata if Rgtdata[spec]['formula'] in ['H2','O2','H2O','OH2','HOH']]
smallspecies = [
spec for spec in Rgtdata if Rgtdata[spec]["formula"] in ["H2", "O2"]
]
if smallspecies:
Rdata.update({spec: Rgtdata[spec] for spec in smallspecies})
addedspecies += smallspecies
#%% String output handling
addedstr = ""
if addedspecies:
addedstr = ",".join(
[str(species) for species in set(addedspecies) if species not in mandrcts]
)
if addedstr:
addedstr = " with species: " + addedstr
if addedhc:
addedstr2 = ",".join(
[
hc_react[species]["formula"]
for species in set(addedhc)
if species not in mandrcts
]
)
if addedstr2:
addedstr2 = " with help reactant(s): " + addedstr2
if addedstr:
addedstr = addedstr + ", " + addedstr2
else:
addedstr = addedstr2
# if 'Mandatory' in msg or 'Smiles discrepancy' in msg:
if "Smiles discrepancy" in msg:
msg = msg + addedstr
return update_rxn(
mandrcts,
Pdata,
hc_prod=hc_prod,
hcrct=addedhc,
rxnsmiles0=rxnsmiles0,
msg=msg,
)
if "Hydrogen carriers" in msg:
msg = msg + addedstr
return update_rxn(
Rdata, Pdata, hc_prod=hc_prod, hcrct=addedhc, rxnsmiles0=rxnsmiles0, msg=msg
)
Rcount = sum(
[
Counter(Rdata[ID]["atomdict"])
for ID in Rdata
for _ in range(Rdata[ID]["count"])
],
start=Counter(),
) # Sum of atom counts/types on LHS
Rcharge = sum(
[Rdata[ID]["charge"] for ID in Rdata for _ in range(Rdata[ID]["count"])]
)
Pcount = sum(
[
Counter(Pdata[ID]["atomdict"])
for ID in Pdata
for _ in range(Pdata[ID]["count"])
],
start=Counter(),
) # Sum of atom counts/types on RHS
Pcharge = sum(
[Pdata[ID]["charge"] for ID in Pdata for _ in range(Pdata[ID]["count"])]
)
#%% If reaction is balanced already
if Rcount == Pcount and Rcharge == Pcharge:
print("Reaction is fully balanced")
if first:
msg = "Already balanced"
elif msg:
msg = msg + ", " + "Balanced"
else:
msg = "Balanced"
if addedstr:
msg += addedstr
return update_rxn(Rdata, Pdata, hcrct=addedhc, rxnsmiles0=rxnsmiles0, msg=msg)
#%% Otherwise take difference between atom type/count RHS and LHS
rem = Counter() # Rem contains difference between product and reactant counters
rem.update(
Pcount
) # If atoms not balanced and same charge, attempt to balance. Can try if different charge but more tricky
rem.subtract(
Rcount
) # Subtracting reactant atom type index from product atom type index
postype = {
key: rem[key] for key in rem.keys() if rem[key] > 0
} # Finding only positive keys. Note that if counter is positive this means extra molecules need to be added on LHS (eg. reagent).
negtype = {
key: abs(rem[key]) for key in rem.keys() if rem[key] < 0
} # Finding only negative keys. If counter is negative this means extra molecules need to be added on RHS (eg. help compounds)
# breakpoint()
if postype: # Reactants, Reagents may be needed
status = [
mandrcts[ID0]["count"] > Rdata[ID0]["count"]
for ID0 in mandrcts
if ID0 in Rdata
] # if ID0 in Rdata
if any(status):
if msg:
msg = msg + ", " + "Mapping error" + addedstr
else:
msg = "Mapping error" + addedstr
return update_rxn(
Rdata,
Pdata,
hc_prod=hc_prod,
hcrct=addedhc,
rxnsmiles0=rxnsmiles0,
msg=msg,
)
#%% Initializing variables
candirxt = []
candirgt = []
candihc = []
matches = []
addedspecies_ = []
addedhc_ = []
#%% Get reactant match first
candirxt = [
rctid
for rctid in Rdata
if set(postype.keys()).issubset(set(Rdata[rctid]["atomdict"].keys()))
]
#%% Get reagent match
candirgt = [
rgtid
for rgtid in Rgtdata
if set(postype.keys()).issubset(set(Rgtdata[rgtid]["atomdict"].keys()))
and rgtid not in candirxt
]
#%% Get help compound match
if hc_react:
candihc = [
hcid
for hcid in hc_react
if set(postype.keys()).issubset(set(hc_react[hcid]["atomdict"].keys()))
]
# breakpoint()
if candirxt and not candirgt: # Only reactant matches
Rdata, addedspecies_, msg_ = resolvecandidates(
postype,
Rdata,
Rdata,
candirxt,
Pdata,
validate=False,
rctonly=addrctonly,
ignoreH=ignoreH,
)
elif candirgt and not candirxt:
Rdata, addedspecies_, msg_ = resolvecandidates(
postype,
Rdata,
Rgtdata,
candirgt,
Pdata,
validate=False,
rctonly=False,
ignoreH=ignoreH,
)
elif candirxt and candirgt:
Rdata, addedspecies_, msg_ = resolvecandidates(
postype,
Rdata,
copy.deepcopy({**Rdata, **Rgtdata}),
candirxt + candirgt,
Pdata,
validate=False,
rctonly=addrctonly,
ignoreH=ignoreH,
)
elif not candirxt and not candirgt:
combineddict = copy.deepcopy({**Rdata, **Rgtdata})
candispec = [
specid
for specid in combineddict
if set(combineddict[specid]["atomdict"].keys()).intersection(
set(postype.keys())
)
]
if not candispec:
msg_ = "LHS species insufficient"
else:
Rdata, addedspecies_, msg_ = resolvecandidates(
postype,
Rdata,
combineddict,
candispec,
Pdata,
rctonly=addrctonly,
ignoreH=ignoreH,
)
elif candihc and not candirxt and not candirgt:
Rdata, addedhc_, msg_ = resolvecandidates(
postype,
Rdata,
hc_react,
candihc,
Pdata,
validate=False,
rctonly=addrctonly,
ignoreH=ignoreH,
)
if (
"Hydrogen carriers" in msg_
): # Multiple candidates for hydrogen carriers (mapper won't help)
if msg:
msg = msg + ", " + msg_
else:
msg = msg_
elif msg_ != "Valid": # Atom surplus on RHS cannot be met by any LHS species
if msg:
msg = msg + ", " + msg_ + addedstr
else:
msg = msg_ + addedstr
return update_rxn(
Rdata,
Pdata,
hc_prod=hc_prod,
hcrct=addedhc,
rxnsmiles0=rxnsmiles0,
msg=msg,
)
else:
addedspecies += addedspecies_
if addedhc_:
adddedhc += addedhc_
# New#
if (
len(postype) == 1
and "H" in postype
and "With hydrogen carriers" not in msg
):
if msg:
msg = (
msg
+ ", "
+ "With hydrogen carriers: "
+ ",".join([str(addedspec) for addedspec in addedspecies_])
)
else:
msg = "With hydrogen carriers: " + ",".join(
[str(addedspec) for addedspec in addedspecies_]
)
# New#
# breakpoint()
return balancerxn(
Rdata,
Pdata,
Rgtdata=Rgtdata,
rxnsmiles0=rxnsmiles0,
first=False,
usemapper=usemapper,
addedspecies=addedspecies,
addedhc=addedhc,
hc_prod=hc_prod,
hc_react=hc_react,
coefflim=coefflim,
msg=msg,
mandrcts=mandrcts,
addrctonly=addrctonly,
ignoreH=ignoreH,
)
elif negtype:
# breakpoint()
if (
usemapper and len(set(addedspecies)) > 1
): # More than one choice or added small species, let the mapper decide
rxnsmiles = buildrxn(Rdata, Pdata)
mapped_rxn = maprxn([rxnsmiles])[0]
if mapped_rxn == "Error":
if not addrctonly:
addrctonly = True
candidates2 = [candi for candi in Rdata if candi in mandrcts]
if candidates2 and candidates2 != list(Rdata.keys()):
Rdata = {ID0: Rdata[ID0] for ID0 in candidates2}
addedspecies = [
addedspec
for addedspec in addedspecies
if addedspec in Rdata
]
if addedhc:
addedhc = [addedh for addedh in addedhc if addedh in Rdata]
return balancerxn(
Rdata,
Pdata,
rxnsmiles0=rxnsmiles0,
first=False,
usemapper=usemapper,
addedspecies=addedspecies,
addedhc=addedhc,
hc_prod=hc_prod,
hc_react=hc_react,
coefflim=coefflim,
msg=msg,
mandrcts=mandrcts,
addrctonly=addrctonly,
ignoreH=ignoreH,
)
if all([Rdata[ID0]["count"] == 1 for ID0 in Rdata]) or any(
[Rdata[ID0]["count"] >= 10 for ID0 in Rdata]
):
if msg:
msg = msg + ", " + "Mapping error" + addedstr
else:
msg = "Mapping error" + addedstr
return update_rxn(
Rdata,
Pdata,
hc_prod=hc_prod,
hcrct=addedhc,
rxnsmiles0=rxnsmiles0,
msg=msg,
)
else:
status = [
mandrcts[ID0]["count"] >= Rdata[ID0]["count"]
for ID0 in mandrcts
if ID0 in Rdata
] # if ID0 in Rdata
if any(status):
for ID0 in Rdata:
Rdata[ID0]["count"] = Rdata[ID0]["count"] - 1
else:
mandrcts = copy.deepcopy(Rdata)
mincount = min([Rdata[ID0]["count"] for ID0 in Rdata])
for ID0 in Rdata:
Rdata[ID0]["count"] = mincount
return balancerxn(
Rdata,
Pdata,
rxnsmiles0=rxnsmiles0,
first=False,
usemapper=usemapper,
addedspecies=addedspecies,
addedhc=addedhc,
hc_prod=hc_prod,
hc_react=hc_react,
coefflim=coefflim,
msg=msg,
mandrcts=mandrcts,
addrctonly=addrctonly,
ignoreH=ignoreH,
)
else:
mappedrxn = mapped_rxn.get("mapped_rxn")
if "With hydrogen carriers" in msg:
hcarriers = [
int(hcarrier)
for hcarrier in msg.split("With hydrogen carriers: ")[1]
.split(", ")[0]
.split(",")
]
else:
hcarriers = []
# breakpoint()
LHSdata, _, msg_ = checkrxn(
mappedrxn,
Rdata=Rdata,
updateall=False,
mandrcts=list(mandrcts.keys()),
hcarriers=hcarriers,
)
if (
"Mandatory" in msg_ and not addrctonly
): # Reactants are unmapped (Try again with a smaller candidate selection)
return balancerxn(
mandrcts,
Pdata,
Rgtdata=Rgtdata,
rxnsmiles0=rxnsmiles0,
first=True,
usemapper=usemapper,
addedspecies=addedspecies,
addedhc=addedhc,
hc_prod=hc_prod,
hc_react=hc_react,
coefflim=coefflim,
msg=msg,
addrctonly=True,
ignoreH=ignoreH,
)
if msg:
if msg_ != "Valid":
msg = msg_ + ", " + msg
msg = "Mapper used" + ", " + msg
else:
if msg_ != "Valid":
msg = "Mapper used" + ", " + msg_
else:
msg = "Mapper used"
if addedhc:
addedhc = [addedh for addedh in addedhc if addedh in LHSdata]
# breakpoint()
addedspecies = [
addedspec for addedspec in addedspecies if addedspec in LHSdata
]
return balancerxn(
LHSdata,
Pdata,
Rgtdata=Rgtdata,
rxnsmiles0=rxnsmiles0,
first=False,
usemapper=False,
addedspecies=addedspecies,
addedhc=addedhc,
hc_prod=hc_prod,
hc_react=hc_react,
coefflim=coefflim,
msg=msg,
mandrcts=mandrcts,
addrctonly=addrctonly,
ignoreH=ignoreH,
)
else:
# breakpoint()
# Find match with Rdata first
candidates = [
spec
for spec in Rdata
if Rdata[spec]["atomdict"] == negtype
if spec in addedspecies
]
if not candidates:
candidates = [
spec
for spec in Rdata
if set(Rdata[spec]["atomdict"].keys()) == set(negtype.keys())
if spec in addedspecies
]
if candidates:
specremoved = False
for candi in candidates:
matcharray = list(
set(
Counter(
{
k: negtype[k] / Rdata[candi]["atomdict"][k]
for k in negtype
}
).values()
)
)
if all([mult.is_integer() for mult in matcharray]):
mult = min(matcharray)
newcount = int(Rdata[candi]["count"] - mult)
if newcount < 0:
newcount = 0
if newcount == 0:
del Rdata[candi]
else:
Rdata[candi]["count"] = newcount
specremoved = True
break
if specremoved:
if addedhc:
addedhc = [addedh for addedh in addedhc if addedh in Rdata]
# refhc=Counter(addedhc)
# addedhc=[addedspec for addedspec in Rdata for _ in range(min([Rdata[addedspec]['count'],refhc[addedspec]])) if addedspec in addedhc]
addedspecies = [
addedspec for addedspec in addedspecies if addedspec in Rdata
]
# refspec=Counter(addedspecies)
# addedspecies=[addedspec for addedspec in Rdata for _ in range(min([Rdata[addedspec]['count'],refspec[addedspec]])) if addedspec in addedspecies if addedspec not in addedhc]
if "Mixture" in msg:
msglist = msg.split(",")
msglist2 = copy.copy(msglist)
for i, msg_ in enumerate(msglist):
if "Mixture" in msg_:
mixmsg = msg_.split(":")
refmixtures = mixmsg[1].split(",")
rmixtures = {
rmixture
for rmixture in refmixtures
if rmixture in Rdata
}
if rmixtures:
msglist2[i] = mixmsg[0] + ",".join(rmixtures)
else:
msglist2.remove(msglist2[i])
msg = ", ".join(msglist2)
return balancerxn(
Rdata,
Pdata,
Rgtdata=Rgtdata,
rxnsmiles0=rxnsmiles0,
first=False,
usemapper=False,
addedspecies=addedspecies,
addedhc=addedhc,
hc_prod=hc_prod,
hc_react=hc_react,
coefflim=coefflim,
msg=msg,
addrctonly=addrctonly,
ignoreH=ignoreH,
)
# Then try help compounds
if Rcharge == Pcharge:
hc_prod = {
hcid: hc_prod[hcid]
for hcid in hc_prod
if hc_prod[hcid]["charge"] == 0
} # Atom type for help compounds
hc_prod2 = {
hcid: hc_prod[hcid]
for hcid in hc_prod
if hc_prod[hcid]["atomdict"] == negtype
} # Exact match for 1 compound
if not hc_prod2:
hc_prod2 = {
hcid: hc_prod[hcid]
for hcid in hc_prod
if hc_prod[hcid]["atomdict"].keys() == negtype.keys()
} # Key match for 1 compound
if hc_prod2:
balbefore = False
else:
balbefore = True
reac = {}
prod = {}
hcid = []
try:
reac, prod, hcid, msg0 = balance(
Rdata,
Pdata,
hc_prod=hc_prod2,
balbefore=balbefore,
coefflim=coefflim,
addedspecies=[
addedspec
for addedspec in addedspecies
if addedspec not in mandrcts
],
addedhc=[addedh for addedh in addedhc if addedh not in mandrcts],
hc_react=hc_react,
)
if msg:
msg = msg + ", " + msg0
else:
msg = msg0
except Exception:
if not balbefore:
return balancerxn(
Rdata,
Pdata,
Rgtdata=Rgtdata,
rxnsmiles0=rxnsmiles0,
first=False,
usemapper=False,
addedspecies=addedspecies,
addedhc=addedhc,
hc_prod={},
hc_react=hc_react,
coefflim=coefflim,
msg=msg,
addrctonly=addrctonly,
ignoreH=ignoreH,
)
if Rcharge != Pcharge:
if msg:
msg = msg + ", " + "Charge imbalance"
else:
msg = "Charge imbalance"
if msg:
msg = msg + ", " + "RHS species insufficient" + addedstr
else:
msg = "RHS species insufficient" + addedstr
return update_rxn(
Rdata, Pdata, hcrct=addedhc, rxnsmiles0=rxnsmiles0, msg=msg
)
else:
if Rcharge != Pcharge:
if msg:
msg = msg + ", " + "Charge imbalance" + addedstr
else:
msg = "Charge imbalance" + addedstr
return update_rxn(
Rdata,
Pdata,
reac=reac,
prod=prod,
hcprod=hcid,
hc_prod=hc_prod2,
hcrct=addedhc,
rxnsmiles0=rxnsmiles0,
msg=msg,
)
else:
if Rcharge != Pcharge:
if msg:
msg = msg + ", " + "Charge imbalance" + addedstr
else:
msg = "Charge imbalance" + addedstr
return update_rxn(
Rdata, Pdata, hc_prod=hc_prod, hcrct=addedhc, rxnsmiles0=rxnsmiles0, msg=msg
)
def buildrxn(Rdata, Pdata):
"""
Takes reaction and product data, and concatenates smiles strings, forming
reaction smiles/smarts
"""
LHS = [Rdata[ID]["smiles"] for ID in Rdata for _ in range(Rdata[ID]["count"])]
RHS = [Pdata[ID]["smiles"] for ID in Pdata for _ in range(Pdata[ID]["count"])]
return ">>".join([getfragments(LHS, smiles=True), getfragments(RHS, smiles=True)])
def update_stoich(stoich, compdict, hcID=None, hc_Dict=None):
"""
Based on balanced stoichiometry output of balance_stoichiometry function from chempy, and given a
dictionary of help compounds and relevant help IDs, updates species dictionary
"""
usedid = []
formdict = {}
msg = ""
for ID in compdict:
form = compdict[ID]["formula"]
if form not in formdict:
formdict.update({form: [ID]})
else:
formdict[form].extend([ID])
# breakpoint()
if hcID:
if hc_Dict is None:
raise CustomError(
"Please supply help compound reference dictionary/dataframe"
)
for hcid in hcID:
form = hc_Dict[hcid]["formula"]
if form not in formdict:
formdict.update({form: [hcid]})
else:
formdict[form].extend([hcid])
for formula, coeff in stoich.items():
if formula in formdict:
for ID in formdict[formula]:
if ID not in compdict:
compdict.update({ID: hc_Dict[ID]})
compdict[ID]["count"] = coeff
usedid += [ID]
else:
msg = "Invalid balancing. Formula indicated in stoich outside compound dictionary"
break
if msg:
return "Error", msg, formdict
else:
valid = True
unusedid = set(compdict.keys()) - set(usedid)
if unusedid:
for ID in unusedid:
if "rxs_ids" not in compdict[ID]: # Identifying help compounds
valid = False
break
if valid:
for ID in unusedid:
del compdict[
ID
] # 'Reactants' that aren't reactants..these are removed
if valid and compdict:
return compdict, msg, formdict
else:
# breakpoint()
msg = "Invalid balancing. Species missing: " + ",".join(
[str(unused) for unused in unusedid]
)
return compdict, msg, formdict
def update_rxn(
Rdata,
Pdata,
reac=None,
prod=None,
hc_prod=None,
hcprod=[],
hcrct=[],
rxnsmiles0=None,
msg=None,
):
"""
Wrapper for calling update_stoich function
"""
stoichupdated = False
addmsgr = ""
addmsgp = ""
if reac is not None: # Switched order
stoichupdated = True
Rdata1, addmsgr, formdictr = update_stoich(reac, Rdata)
if prod is not None:
stoichupdated = True
Pdata1, addmsgp, formdictp = update_stoich(
prod, Pdata, hcID=hcprod, hc_Dict=hc_prod
)
if addmsgr and addmsgr != "Valid":
if msg is not None:
msg = addmsgr + " from LHS" + ", " + msg
else:
msg = addmsgr + " from LHS"
if addmsgp and addmsgp != "Valid":
if msg is not None:
msg = addmsgp + " from RHS" + ", " + msg
else:
msg = addmsgp + " from RHS"
if stoichupdated:
if Rdata1 != "Error" and Pdata1 != "Error":
Rdata = Rdata1
Pdata = Pdata1
try:
balrxnsmiles = buildrxn(Rdata, Pdata)
except Exception:
balrxnsmiles = "Error"
msg = (
"Invalid balancing. Species missing in database" + ", " + msg
) # Just to make sure, although this error should never happen
else:
balrxnsmiles = "Error"
else:
if (
("LHS species insufficient" in msg)
| ("Invalid" in msg)
| ("Mapping error" in msg)
| ("discrepancy" in msg)
):
balrxnsmiles = "Error"
else:
balrxnsmiles = buildrxn(Rdata, Pdata)
if hcrct:
LHSids = [
ID for ID in Rdata if ID not in hcrct for _ in range(Rdata[ID]["count"])
]
else:
LHSids = [ID for ID in Rdata for _ in range(Rdata[ID]["count"])]