-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathdatabaseTest.py
More file actions
2081 lines (1885 loc) · 96.1 KB
/
Copy pathdatabaseTest.py
File metadata and controls
2081 lines (1885 loc) · 96.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# #
# Copyright (c) 2002-2019 Prof. William H. Green (whgreen@mit.edu), #
# Prof. Richard H. West (r.west@neu.edu) and the RMG Team (rmg_dev@mit.edu) #
# #
# Permission is hereby granted, free of charge, to any person obtaining a #
# copy of this software and associated documentation files (the 'Software'), #
# to deal in the Software without restriction, including without limitation #
# the rights to use, copy, modify, merge, publish, distribute, sublicense, #
# and/or sell copies of the Software, and to permit persons to whom the #
# Software is furnished to do so, subject to the following conditions: #
# #
# The above copyright notice and this permission notice shall be included in #
# all copies or substantial portions of the Software. #
# #
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING #
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER #
# DEALINGS IN THE SOFTWARE. #
# #
###############################################################################
"""
This scripts runs tests on the database
"""
import itertools
import logging
from copy import copy
from collections import defaultdict
import pytest
import numpy as np
import quantities as pq
import rmgpy.kinetics
import rmgpy.constants
from rmgpy import settings
from rmgpy.data.base import LogicOr
from rmgpy.data.rmg import RMGDatabase
from rmgpy.exceptions import ImplicitBenzeneError, UnexpectedChargeError
from rmgpy.molecule import Group
from rmgpy.molecule.atomtype import ATOMTYPES
from rmgpy.molecule.pathfinder import find_shortest_path
from rmgpy.quantity import ScalarQuantity
from rmgpy.kinetics.model import KineticsModel
# allow asserts to 'fail' and then continue - this test file relies on a lot
# of asserts in each test and we want them all to run
from pytest_check import check
@pytest.mark.database
class TestDatabase:
"""
Contains unit tests for the database for rigorous error checking.
"""
@classmethod
def setup_class(cls):
"""
Load the database before running the tests.
"""
database_directory = settings["database.directory"]
cls.database = RMGDatabase()
cls.database.load(database_directory, kinetics_families="all")
# calls the methods below
def test_kinetics(self):
for family_name, family in self.database.kinetics.families.items():
with check:
assert self.kinetics_check_correct_number_of_nodes_in_rules(
family_name
), "Kinetics family {0}: rules have correct number of nodes?".format(family_name)
with check:
assert self.kinetics_check_nodes_in_rules_found_in_groups(
family_name
), "Kinetics family {0}: rules' nodes exist in the groups?".format(family_name)
with check:
assert self.kinetics_check_groups_found_in_tree(
family_name
), "Kinetics family {0}: groups are in the tree with proper parents?".format(family_name)
if not family.auto_generated:
with check:
assert self.kinetics_check_groups_nonidentical(family_name), "Kinetics family {0}: groups are not identical?".format(family_name)
with check:
assert self.kinetics_check_child_parent_relationships(
family_name
), "Kinetics family {0}: parent-child relationships are correct?".format(family_name)
with check:
assert self.kinetics_check_siblings_for_parents(family_name), "Kinetics family {0}: sibling relationships are correct?".format(
family_name
)
with check:
assert self.kinetics_check_cd_atom_type(family_name), "Kinetics family {0}: Cd, CS, CO, and Cdd atomtype used correctly?".format(
family_name
)
with check:
assert self.kinetics_check_reactant_and_product_template(
family_name
), "Kinetics family {0}: reactant and product templates correctly defined?".format(family_name)
with check:
assert self.kinetics_check_num_reactant_and_product(
family_name
), "Kinetics family {0}: number of reactant and product defined?".format(family_name)
# tests for surface families
if "surface" in family_name.lower():
with check:
assert self.kinetics_check_surface_training_reactions_can_be_used(
family_name
), "Kinetics surface family {0}: entries can be used to generate rate rules?".format(family_name)
with check:
assert self.kinetics_check_training_reactions_have_surface_attributes(
family_name
), "Kinetics surface family {0}: entries have surface attributes?".format(family_name)
if family_name not in {
"Surface_Proton_Electron_Reduction_Alpha",
"Surface_Proton_Electron_Reduction_Alpha_vdW",
"Surface_Proton_Electron_Reduction_Beta",
"Surface_Proton_Electron_Reduction_Beta_vdW",
"Surface_Proton_Electron_Reduction_Beta_Dissociation",
}:
with check:
assert self.kinetics_check_coverage_dependence_units_are_correct(
family_name
), "Kinetics surface family {0}: check coverage dependent units are correct?".format(family_name)
# these families have some sort of difficulty which prevents us from testing accessibility right now
# See RMG-Py PR #2232 for reason why adding Bimolec_Hydroperoxide_Decomposition here. Basically some nodes
# #need to be in a ring, but the sampled molecule is not.
difficult_families = [
"Diels_alder_addition",
"Intra_R_Add_Exocyclic",
"Intra_R_Add_Endocyclic",
"Retroene",
"Bimolec_Hydroperoxide_Decomposition",
]
if len(family.forward_template.reactants) < len(family.groups.top) and family_name not in difficult_families:
with check:
assert self.kinetics_check_unimolecular_groups(
family_name
), "Kinetics family {0} check that unimolecular group is formatted correctly?".format(family_name)
if family_name not in difficult_families and not family.auto_generated:
with check:
assert self.kinetics_check_sample_descends_to_group(family_name), "Kinetics family {0}: Entry is accessible?".format(family_name)
with check:
assert self.kinetics_check_sample_can_react(family_name), "Kinetics family {0}: Recipe applies to group entry?".format(
family_name
)
for depository in family.depositories:
with check:
assert self.kinetics_check_adjlists_nonidentical(
depository
), "Kinetics depository {0}: check adjacency lists are nonidentical?".format(depository.label)
with check:
assert self.kinetics_check_rate_units_are_correct(
depository, tag="depository"
), "Kinetics depository {0}: check rates have correct units?".format(depository.label)
for library_name, library in self.database.kinetics.libraries.items():
with check:
assert self.kinetics_check_adjlists_nonidentical(library), "Kinetics library {0}: check adjacency lists are nonidentical?".format(
library_name
)
with check:
assert self.kinetics_check_rate_units_are_correct(library), "Kinetics library {0}: check rates have correct units?".format(
library_name
)
with check:
assert self.kinetics_check_library_rates_are_reasonable(library), "Kinetics library {0}: check rates are reasonable?".format(
library_name
)
# tests for surface families
if "surface" in library_name.lower():
with check:
assert self.kinetics_check_surface_library_reactions_have_surface_attributes(
library
), "Kinetics surface library {0}: entries have surface attributes?".format(library_name)
def test_thermo(self):
for group_name, group in self.database.thermo.groups.items():
with check:
assert self.general_check_nodes_found_in_tree(
group_name, group
), "Thermo groups {0}: nodes are in the tree with proper parents?".format(group_name)
with check:
assert self.general_check_groups_nonidentical(group_name, group), "Thermo groups {0}: nodes are nonidentical?".format(group_name)
with check:
assert self.general_check_child_parent_relationships(
group_name, group
), "Thermo groups {0}: parent-child relationships are correct?".format(group_name)
with check:
assert self.general_check_siblings_for_parents(group_name, group), "Thermo groups {0}: sibling relationships are correct?".format(
group_name
)
with check:
assert self.general_check_cd_atom_type(group_name, group), "Thermo groups {0}: Cd atomtype used correctly?".format(group_name)
with check:
assert self.general_check_sample_descends_to_group(group_name, group), "Thermo groups {0}: Entry is accessible?".format(group_name)
# tests for adsorption groups
if "adsorption" in group_name.lower():
with check:
assert self.check_surface_thermo_groups_have_surface_attributes(
group_name, group
), "Thermo surface groups {0}: Entry has metal attributes?".format(group_name)
for library_name, library in self.database.thermo.libraries.items():
if "surface" in library_name.lower():
with check:
assert self.check_surface_thermo_libraries_have_surface_attributes(
library_name, library
), "Thermo surface libraries {0}: Entry has metal attributes?".format(library_name)
def test_solvation(self):
for group_name, group in self.database.solvation.groups.items():
with check:
assert self.general_check_nodes_found_in_tree(
group_name, group
), "Solvation groups {0}: nodes are in the tree with proper parents?".format(group_name)
with check:
assert self.general_check_groups_nonidentical(group_name, group), "Solvation groups {0}: nodes are nonidentical?".format(group_name)
with check:
assert self.general_check_child_parent_relationships(
group_name, group
), "Solvation groups {0}: parent-child relationships are correct?".format(group_name)
with check:
assert self.general_check_siblings_for_parents(group_name, group), "Solvation groups {0}: sibling relationships are correct?".format(
group_name
)
with check:
assert self.general_check_cd_atom_type(group_name, group), "Solvation groups {0}: Cd atomtype used correctly?".format(group_name)
with check:
assert self.general_check_sample_descends_to_group(group_name, group), "Solvation groups {0}: Entry is accessible?".format(group_name)
def test_statmech(self):
for group_name, group in self.database.statmech.groups.items():
with check:
assert self.general_check_nodes_found_in_tree(
group_name, group
), "Statmech groups {0}: nodes are in the tree with proper parents?".format(group_name)
with check:
assert self.general_check_groups_nonidentical(group_name, group), "Statmech groups {0}: nodes are nonidentical?".format(group_name)
with check:
assert self.general_check_child_parent_relationships(
group_name, group
), "Statmech groups {0}: parent-child relationships are correct?".format(group_name)
with check:
assert self.general_check_siblings_for_parents(group_name, group), "Statmech groups {0}: sibling relationships are correct?".format(
group_name
)
with check:
assert self.general_check_cd_atom_type(group_name, group), "Statmech groups {0}: Cd atomtype used correctly?".format(group_name)
with check:
assert self.general_check_sample_descends_to_group(group_name, group), "Statmech groups {0}: Entry is accessible?".format(group_name)
def test_transport(self):
for group_name, group in self.database.transport.groups.items():
with check:
assert self.general_check_nodes_found_in_tree(
group_name, group
), "Transport groups {0}: nodes are in the tree with proper parents?".format(group_name)
with check:
assert self.general_check_groups_nonidentical(group_name, group), "Transport groups {0}: nodes are nonidentical?".format(group_name)
with check:
assert self.general_check_child_parent_relationships(
group_name, group
), "Transport groups {0}: parent-child relationships are correct?".format(group_name)
with check:
assert self.general_check_siblings_for_parents(group_name, group), "Transport groups {0}: sibling relationships are correct?".format(
group_name
)
with check:
assert self.general_check_cd_atom_type(
group_name, group
), "Transport groups {0}: Cd, CS, CO, and Cdd atomtype used correctly?".format(group_name)
with check:
assert self.general_check_sample_descends_to_group(group_name, group), "Transport groups {0}: Entry is accessible?".format(group_name)
def test_metal_libraries(self):
for library_name, library in self.database.thermo.surface["metal"].libraries.items():
with check:
assert self.general_check_metal_database_has_catalyst_properties(
library
), "Metal library {0}: Entries have catalyst properties?".format(library_name)
with check:
assert self.general_check_metal_database_has_reasonable_labels(library), "Metal library {0}: Entries have reasonable labels?".format(
library_name
)
# These are the actual tests, that don't start with a "test_" name:
def kinetics_check_surface_training_reactions_can_be_used(self, family_name):
"""Test that surface training reactions can be averaged and used for generating rate rules"""
family = self.database.kinetics.families[family_name]
if not family.auto_generated:
family.add_rules_from_training(thermo_database=self.database.thermo)
family.fill_rules_by_averaging_up(verbose=True)
return True
def general_check_metal_database_has_catalyst_properties(self, library):
"""Test that each entry has catalyst properties"""
for entry in library.entries.values():
if not entry.binding_energies:
raise AttributeError("Entry {} has no binding energies".format(entry.label))
with check:
assert isinstance(entry.binding_energies, dict)
for element in "CHON":
if not entry.binding_energies[element]:
raise KeyError("Entry {} has no {} binding energy".format(entry.label, element))
if not isinstance(entry.binding_energies[element], ScalarQuantity):
raise TypeError(
"Entry {} binding energy value for {} should be a ScalarQuantity, but is type {}".format(
entry.label, element, type(entry.binding_energies[element])
)
)
if not isinstance(entry.binding_energies[element].value, float):
raise TypeError(
"Entry {} binding energy for {} should be a float, but is type {}".format(
entry.label,
element,
type(entry.binding_energies[element].value),
)
)
with check:
assert entry.binding_energies[element].value < 0.0 # binding energies should all be negative... probably
with check:
assert entry.binding_energies[element].units == "eV/molecule"
if not entry.surface_site_density:
raise AttributeError("Entry {} has no surface site density".format(entry.label))
with check:
assert isinstance(entry.surface_site_density, ScalarQuantity)
if not isinstance(entry.surface_site_density.value, float):
raise TypeError("Entry {} should be a float, but is type {}".format(entry.label, type(entry.surface_site_density.value)))
if not isinstance(entry.surface_site_density.units, str):
raise TypeError("Entry {} should be a str, but is type {}".format(entry.label, type(entry.surface_site_density.units)))
with check:
assert 1e-4 > entry.surface_site_density.value_si > 1e-6 # values should be reasonable
with check:
assert isinstance(entry.metal, str) # all entries should have a metal attribute, at minimum
if entry.facet:
with check:
assert isinstance(entry.facet, str)
if entry.site:
with check:
assert isinstance(entry.site, str)
return True
def general_check_metal_database_has_reasonable_labels(self, library):
"""Test that each entry has a reasonable label corresponding to its metal and facet"""
for entry in library.entries.values():
if entry.metal not in entry.label:
raise NameError("Entry {} with metal attribute {} does not have metal in its label".format(entry.label, entry.metal))
if entry.facet not in entry.label:
raise NameError("Entry {} with facet attribute {} does not have facet in its label".format(entry.label, entry.facet))
if not entry.label[0].isupper():
raise NameError("Entry {} should start with a capital letter".format(entry.label))
return True
def kinetics_check_coverage_dependence_units_are_correct(self, family_name):
"""Test that each surface training reaction that has coverage dependent parameters has acceptable units"""
family = self.database.kinetics.families[family_name]
training = family.get_training_depository().entries.values()
failed = False
for entry in training:
cov_dep = entry.data.coverage_dependence
if cov_dep:
with check:
assert isinstance(cov_dep, dict)
for species, parameters in cov_dep.items():
with check:
assert isinstance(species, str)
with check:
assert parameters["E"]
if parameters["a"].units:
"Should be dimensionless"
failed = True
logging.error(f"Entry {entry.label} has invalid units {parameters['a'].units} for a")
if parameters["m"].units:
"Should be dimensionless"
failed = True
logging.error(f"Entry {entry.label} has invalid units {parameters['m'].units} for m")
if failed:
raise ValueError("Surface coverage dependent parameters have incorrect units." "Please check log warnings for all error messages.")
return True
def kinetics_check_training_reactions_have_surface_attributes(self, family_name):
"""Test that each surface training reaction has surface attributes"""
family = self.database.kinetics.families[family_name]
training = family.get_training_depository().entries.values()
failed = False
for entry in training:
if not entry.metal:
logging.error(f"Expected a metal attribute for {entry} in {family} family but found {entry.metal!r}")
failed = True
else:
with check:
assert isinstance(entry.metal, str)
if entry.facet:
with check:
assert isinstance(entry.facet, str)
if entry.site:
with check:
assert isinstance(entry.site, str)
if failed:
raise ValueError("Error occured in databaseTest. Please check log warnings for all error messages.")
return True
def kinetics_check_surface_library_reactions_have_surface_attributes(self, library):
"""Test that each surface reaction library has surface attributes"""
entries = library.entries.values()
failed = False
if "_Pt" in library.label:
for entry in entries:
if entry.metal != "Pt":
logging.error(f"Expected {entry} metal attribute in {library} library to match Pt, but was {entry.metal}")
failed = True
if "_Ni" in library.label:
for entry in entries:
if entry.metal != "Ni":
logging.error(f"Expected {entry} metal attribute in {library} library to match Ni, but was {entry.metal}")
failed = True
for entry in entries:
if isinstance(entry.metal, type(None)):
logging.error(f"Expected a metal attribute in {library} library for {entry} but found None")
failed = True
if failed:
raise ValueError("Error occured in databaseTest. Please check log warnings for all error messages.")
return True
def kinetics_check_correct_number_of_nodes_in_rules(self, family_name):
"""
This test ensures that each rate rule contains the proper number of
nodes according to the family it originates.
"""
family = self.database.kinetics.families[family_name]
expected_number_nodes = len(family.get_root_template())
tst = []
for label, entries in family.rules.entries.items():
for entry in entries:
nodes = label.split(";")
tst.append(
(
len(nodes),
expected_number_nodes,
"Wrong number of groups or semicolons in family {family} rule {entry}. Should be "
"{num_nodes}".format(
family=family_name,
entry=entry,
num_nodes=expected_number_nodes,
),
)
)
boo = False
for item in tst:
if item[0] != item[1]:
boo = True
logging.error(item[2])
if boo:
raise ValueError("Error occured in databaseTest. Please check log warnings for all error messages.")
return True
def kinetics_check_nodes_in_rules_found_in_groups(self, family_name):
"""
This test ensures that each rate rule contains nodes that exist in the
groups and that they match the order of the forwardTemplate.
"""
family = self.database.kinetics.families[family_name]
# List of the each top node's descendants (including the top node)
top_descendants = []
for topNode in family.get_root_template():
nodes = [topNode]
nodes.extend(family.groups.descendants(topNode))
top_descendants.append(nodes)
top_group_order = ";".join(topNode.label for topNode in family.get_root_template())
tst1 = []
tst2 = []
for label, entries in family.rules.entries.items():
for entry in entries:
nodes = label.split(";")
for i, node in enumerate(nodes):
tst1.append(
(
node in family.groups.entries,
"In {family} family, no group definition found for label {label} in rule "
"{entry}".format(family=family_name, label=node, entry=entry),
)
)
tst2.append(
(
family.groups.entries[node] in top_descendants[i],
"In {family} family, rule {entry} was found with groups out of order. "
"The correct order for a rule should be subgroups of {top}.".format(family=family_name, entry=entry, top=top_group_order),
)
)
boo = False
for i in range(len(tst1)):
if not tst1[i][0]:
logging.error(tst1[i][1])
boo = True
if not tst2[i][0]:
logging.error(tst2[i][1])
boo = True
if boo:
raise ValueError("Error occured in databaseTest. Please check log warnings for all error messages.")
return True
def kinetics_check_groups_found_in_tree(self, family_name):
"""
This test checks whether groups are found in the tree, with proper parents.
"""
family = self.database.kinetics.families[family_name]
tst = []
tst1 = []
tst2 = []
tst3 = []
for nodeName, nodeGroup in family.groups.entries.items():
tst.append(
(
"[" in nodeName or "]" in nodeName,
"Group {group} in {family} family contains square brackets [ ] in the label, which are "
"not allowed.".format(group=nodeName, family=family_name),
)
)
ascend_parent = nodeGroup
# Check whether the node has proper parents unless it is the top reactant or product node
while ascend_parent not in family.groups.top and ascend_parent not in family.forward_template.products:
child = ascend_parent
ascend_parent = ascend_parent.parent
tst1.append(
(
ascend_parent is not None,
"Group {group} in {family} family was found in the tree without a proper parent.".format(group=child, family=family_name),
)
)
tst2.append(
(
child in ascend_parent.children,
"Group {group} in {family} family was found in the tree without a proper parent.".format(group=nodeName, family=family_name),
)
)
tst3.append(
(
child is ascend_parent,
"Group {group} in {family} family is a parent to itself".format(group=nodeName, family=family_name),
)
)
boo = False
for i in range(len(tst)):
if tst[i][0]:
logging.error(tst[i][1])
boo = True
for i in range(len(tst1)):
if not tst1[i][0]:
logging.error(tst1[i][1])
boo = True
if not tst2[i][0]:
logging.error(tst2[i][1])
boo = True
if tst3[i][0]:
logging.error(tst3[i][1])
boo = True
if boo:
raise ValueError("Error occured in databaseTest. Please check log warnings for all error messages.")
return True
def kinetics_check_groups_nonidentical(self, family_name):
"""
This test checks that the groups are non-identical.
"""
from rmgpy.data.base import Database
original_family = self.database.kinetics.families[family_name]
family = Database()
family.entries = original_family.groups.entries
entries_copy = copy(family.entries)
tst = []
for nodeName, nodeGroup in family.entries.items():
del entries_copy[nodeName]
for nodeNameOther, nodeGroupOther in entries_copy.items():
tst.append(
(
family.match_node_to_node(nodeGroup, nodeGroupOther),
"Group {group} in {family} family was found to be identical to group {groupOther}".format(
group=nodeName, family=family_name, groupOther=nodeNameOther
),
)
)
boo = False
for i in range(len(tst)):
if tst[i][0]:
logging.error(tst[i][1])
boo = True
if boo:
raise ValueError("Error occured in databaseTest. Please check log warnings for all error messages.")
return True
def kinetics_check_child_parent_relationships(self, family_name):
"""
This test checks that groups' parent-child relationships are correct in the database.
"""
from rmgpy.data.base import Database
original_family = self.database.kinetics.families[family_name]
family = Database()
family.entries = original_family.groups.entries
tst = []
for nodeName, childNode in family.entries.items():
# top nodes and product nodes don't have parents by definition, so they get an automatic pass:
if childNode in original_family.groups.top or childNode in original_family.forward_template.products:
continue
parent_node = childNode.parent
if parent_node is None:
# This is a mistake in the database, but it should be caught by kinetics_checkGroupsFoundInTree
# so rather than report it twice or crash, we'll just silently carry on to the next node.
continue
elif parent_node in original_family.forward_template.products:
# This is a product node made by training reactions which we do not need to heck
continue
# Check whether the node has proper parents unless it is the top reactant or product node
# The parent should be more general than the child
tst.append(
(
family.match_node_to_child(parent_node, childNode),
"In {family} family, group {parent} is not a proper parent of its child "
"{child}.".format(family=family_name, parent=parent_node, child=nodeName),
)
)
# check that parentNodes which are LogicOr do not have an ancestor that is a Group
# If it does, then the child_node must also be a child of the ancestor
if isinstance(parent_node.item, LogicOr):
ancestor_node = parent_node
while ancestor_node not in original_family.groups.top and isinstance(ancestor_node.item, LogicOr):
ancestor_node = ancestor_node.parent
if isinstance(ancestor_node.item, Group):
tst.append(
(
family.match_node_to_child(ancestor_node, childNode),
"In {family} family, group {ancestor} is not a proper ancestor of its child "
"{child}.".format(
family=family_name,
ancestor=ancestor_node,
child=nodeName,
),
)
)
boo = False
for i in range(len(tst)):
if not tst[i][0]:
logging.error(tst[i][1])
boo = True
if boo:
raise ValueError("Error occured in databaseTest. Please check log warnings for all error messages.")
return True
def kinetics_check_siblings_for_parents(self, family_name):
"""
This test checks that siblings in a tree are not actually parent/child
See general_checkSiblingsForParents comments for more detailed description
of the test.
"""
from rmgpy.data.base import Database
original_family = self.database.kinetics.families[family_name]
family = Database()
family.entries = original_family.groups.entries
tst = []
for nodeName, node in family.entries.items():
# Some families also construct a 2-level trees for the products
# (root with all entries down one level) We don't care about this
# tree as it is not used in searching, so we ignore products
if node in original_family.forward_template.products:
continue
for index, child1 in enumerate(node.children):
for child2 in node.children[index + 1 :]:
tst.append(
(
family.match_node_to_child(child1, child2),
"In family {0}, node {1} is a parent of {2}, but they are written as siblings.".format(family_name, child1, child2),
)
)
boo = False
for i in range(len(tst)):
if tst[i][0]:
logging.error(tst[i][1])
boo = True
if boo:
raise ValueError("Error occured in databaseTest. Please check log warnings for all error messages.")
return True
def kinetics_check_adjlists_nonidentical(self, database):
"""
This test checks whether adjacency lists of reactants in a KineticsDepository or KineticsLibrary
database object are nonidentical.
"""
species_dict = {}
entries = database.entries.values()
for entry in entries:
for reactant in entry.item.reactants:
if reactant.label not in species_dict:
species_dict[reactant.label] = reactant
for product in entry.item.products:
if product.label not in species_dict:
species_dict[product.label] = product
tst = []
boo = False
# Go through all species to make sure they are nonidentical
species_list = list(species_dict.values())
labeled_atoms = [species.molecule[0].get_all_labeled_atoms() for species in species_list]
for i in range(len(species_list)):
for j in range(i + 1, len(species_list)):
initial_map = {}
try:
atom_labels = set(list(labeled_atoms[i].keys()) + list(labeled_atoms[j].keys()))
for atomLabel in atom_labels:
initial_map[labeled_atoms[i][atomLabel]] = labeled_atoms[j][atomLabel]
except KeyError:
# atom labels did not match, therefore not a match
continue
m1 = species_list[i].molecule[0]
m2 = species_list[j].molecule[0]
if not m1.is_mapping_valid(m2, initial_map, equivalent=True):
# the mapping is invalid so they're not isomorphic
continue
if m1.is_isomorphic(m2, initial_map):
logging.error(
"Species {0} and species {1} in {2} database were found to be identical.".format(
species_list[i].label, species_list[j].label, database.label
)
)
boo = True
if boo:
raise ValueError("Error occured in databaseTest. Please check log warnings for all error messages.")
return True
def kinetics_check_rate_units_are_correct(self, database, tag="library"):
"""
This test ensures that every reaction has acceptable units on the A factor.
"""
boo = False
dimensionalities = {
1: (1 / pq.s).dimensionality,
2: (pq.m**3 / pq.mole / pq.s).dimensionality,
3: ((pq.m**6) / (pq.mole**2) / pq.s).dimensionality,
}
for entry in database.entries.values():
k = entry.data
rxn = entry.item
molecularity = len(rxn.reactants)
surface_reactants = sum([1 for s in rxn.reactants if s.contains_surface_site()])
try:
if isinstance(k, rmgpy.kinetics.StickingCoefficient):
"Should be dimensionless"
a_factor = k.A
if a_factor.units:
boo = True
logging.error("Reaction {0} from {1} {2}, has invalid units {3}".format(rxn, tag, database.label, a_factor.units))
elif isinstance(k, rmgpy.kinetics.SurfaceArrhenius):
a_factor = k.A
expected = copy(dimensionalities[molecularity])
# for each surface reactant but one, switch from (m3/mol) to (m2/mol)
for _ in range(surface_reactants - 1):
expected[pq.m] -= 1
if pq.Quantity(1.0, a_factor.units).simplified.dimensionality != expected:
boo = True
logging.error("Reaction {0} from {1} {2}, has invalid units {3}".format(rxn, tag, database.label, a_factor.units))
elif isinstance(k, rmgpy.kinetics.Arrhenius): # (but not SurfaceArrhenius, which came first)
a_factor = k.A
if pq.Quantity(1.0, a_factor.units).simplified.dimensionality != dimensionalities[molecularity]:
boo = True
logging.error("Reaction {0} from {1} {2}, has invalid units {3}".format(rxn, tag, database.label, a_factor.units))
elif isinstance(k, (rmgpy.kinetics.Lindemann, rmgpy.kinetics.Troe)):
a_factor = k.arrheniusHigh.A
if pq.Quantity(1.0, a_factor.units).simplified.dimensionality != dimensionalities[molecularity]:
boo = True
logging.error(
"Reaction {0} from {1} {2}, has invalid high-pressure limit units {3}".format(rxn, tag, database.label, a_factor.units)
)
elif isinstance(
k,
(
rmgpy.kinetics.Lindemann,
rmgpy.kinetics.Troe,
rmgpy.kinetics.ThirdBody,
),
):
a_factor = k.arrheniusLow.A
if pq.Quantity(1.0, a_factor.units).simplified.dimensionality != dimensionalities[molecularity + 1]:
boo = True
logging.error(
"Reaction {0} from {1} {2}, has invalid low-pressure limit units {3}".format(rxn, tag, database.label, a_factor.units)
)
elif hasattr(k, "highPlimit") and k.highPlimit is not None:
a_factor = k.highPlimit.A
if pq.Quantity(1.0, a_factor.units).simplified.dimensionality != dimensionalities[molecularity - 1]:
boo = True
logging.error(
"Reaction {0} from {1} {2}, has invalid high-pressure limit units {3}".format(rxn, tag, database.label, a_factor.units)
)
elif isinstance(k, rmgpy.kinetics.MultiArrhenius):
for num, arrhenius in enumerate(k.arrhenius):
a_factor = arrhenius.A
if pq.Quantity(1.0, a_factor.units).simplified.dimensionality != dimensionalities[molecularity]:
boo = True
logging.error(
"Reaction {0} from {1} {2}, has invalid units {3} on rate expression {4}".format(
rxn, tag, database.label, a_factor.units, num + 1
)
)
elif isinstance(k, rmgpy.kinetics.PDepArrhenius):
for pa, arrhenius in zip(k.pressures.value_si, k.arrhenius):
P = rmgpy.quantity.Pressure(1, k.pressures.units)
P.value_si = pa
if isinstance(arrhenius, rmgpy.kinetics.MultiArrhenius):
# A PDepArrhenius may have MultiArrhenius within it
# which is distinct (somehow) from MultiPDepArrhenius
for num, arrhenius2 in enumerate(arrhenius.arrhenius):
a_factor = arrhenius2.A
if pq.Quantity(1.0, a_factor.units).simplified.dimensionality != dimensionalities[molecularity]:
boo = True
logging.error(
"Reaction {0} from {1} {2}, has invalid units {3} on {4!r} rate expression "
"{5}".format(
rxn,
tag,
database.label,
a_factor.units,
P,
num + 1,
)
)
else:
a_factor = arrhenius.A
if pq.Quantity(1.0, a_factor.units).simplified.dimensionality != dimensionalities[molecularity]:
boo = True
logging.error(
"Reaction {0} from {1} {2}, has invalid {3!r} units {4}".format(rxn, tag, database.label, P, a_factor.units)
)
elif isinstance(k, rmgpy.kinetics.MultiPDepArrhenius):
for num, k2 in enumerate(k.arrhenius):
for pa, arrhenius in zip(k2.pressures.value_si, k2.arrhenius):
P = rmgpy.quantity.Pressure(1, k2.pressures.units)
P.value_si = pa
if isinstance(arrhenius, rmgpy.kinetics.MultiArrhenius):
# A MultiPDepArrhenius may have MultiArrhenius within it
for arrhenius2 in arrhenius.arrhenius:
a_factor = arrhenius2.A
if pq.Quantity(1.0, a_factor.units).simplified.dimensionality != dimensionalities[molecularity]:
boo = True
logging.error(
"Reaction {0} from {1} {2}, has invalid units {3} on {4!r} rate expression "
"{5!r}".format(
rxn,
tag,
database.label,
a_factor.units,
P,
arrhenius2,
)
)
else:
a_factor = arrhenius.A
if pq.Quantity(1.0, a_factor.units).simplified.dimensionality != dimensionalities[molecularity]:
boo = True
logging.error(
"Reaction {0} from {1} {2}, has invalid {3!r} units {4} in rate expression "
"{5}".format(
rxn,
tag,
database.label,
P,
a_factor.units,
num,
)
)
elif isinstance(k, rmgpy.kinetics.Chebyshev):
if pq.Quantity(1.0, k.kunits).simplified.dimensionality != dimensionalities[molecularity]:
boo = True
logging.error("Reaction {0} from {1} {2}, has invalid units {3}".format(rxn, tag, database.label, k.kunits))
else:
logging.warning("Reaction {0} from {1} {2}, did not have units checked.".format(rxn, tag, database.label))
except:
logging.error(
"Error when checking units on reaction {0} from {1} {2} with " "rate expression {3!r}.".format(rxn, tag, database.label, k)
)
raise
if boo:
raise ValueError("{0} {1} has some incorrect units".format(tag.capitalize(), database.label))
return True
def kinetics_check_library_rates_are_reasonable(self, library):
"""
This test ensures that every library reaction has reasonable kinetics at 1000 K, 1 bar
"""
T = 1000.0 # K
P = 100000.0 # 1 bar in Pa
Na = rmgpy.constants.Na # molecules/mol
h_rad_mass = 1.6737236e-27 # kg
h_rad_diam = 2.4e-10 # m
kB = rmgpy.constants.kB # m2 * kg *s^-2 * K^-1
h = rmgpy.constants.h # m2 kg / s
boo = False
tst_limit = (kB * T) / h
collision_limit = Na * np.pi * h_rad_diam**2 * np.sqrt(8 * kB * T / (np.pi * h_rad_mass / 2))
for entry in library.entries.values():
if entry.item.is_surface_reaction() or isinstance(entry.data, KineticsModel):
# Don't check surface reactions
continue
k = entry.data.get_rate_coefficient(T, P)
rxn = entry.item
if k < 0:
boo = True
logging.error("library reaction {0} from library {1}, had a negative rate at 1000 K, 1 bar".format(rxn, library.label))
if len(rxn.reactants) == 1 and not rxn.allow_max_rate_violation:
if k > tst_limit:
boo = True
logging.error(
"library reaction {0} from library {1}, exceeds the TST limit at 1000 K, 1 bar of "
"{2} mol/(m3*s) at {3} mol/(m3*s) and did not have allow_max_rate_violation=True"
"".format(rxn, library.label, tst_limit, k)
)
elif len(rxn.reactants) == 2 and not rxn.allow_max_rate_violation:
if k > collision_limit:
boo = True
logging.error(
"library reaction {0} from library {1}, exceeds the collision limit at 1000 K, 1 bar "