-
Notifications
You must be signed in to change notification settings - Fork 5
/
MoleculeViewer.m
executable file
·2019 lines (1612 loc) · 141 KB
/
MoleculeViewer.m
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
(* :Title: Molecule Viewer *)
(* :Author: J. M. *)
(* :Summary:
This package implements an improved molecule viewer derived from Mathematica's default viewer,
as well as providing a number of useful utility functions for obtaining and visualizing molecular models.
*)
(* :Copyright:
© 2017-2019 by J. M. (pleasureoffiguring(AT)gmail(DOT)com)
This work is free. It comes without any warranty, to the extent permitted by applicable law.
You can redistribute and/or modify it under the terms of the MIT License.
*)
(* :Package Version: 3.0 *)
(* :Mathematica Version: 8.0 *)
(* :History:
3.0 - now under MIT License, added PlotStyle for molecule depictions ("BallAndStick", etc.), added new multiple bond style,
added support for changing default units of length, added data access functions for PDB and ZINC,
added Imago OCR support, added support for structure drawing with Accelrys JDraw and JChemPaint,
added ChEMBL Beaker support functions, added molecule manipulation functions,
limited support of Entity objects and Molecule objects
2.1 - removed support for deprecated ChemSpider SOAP API
2.0 - improved handling of double bonds, added PubChem support, switched to new ChemSpider API, better handling of files and URLs
1.1 - fixed a few reported bugs, added explicit input dialog for $ChemSpiderAPIToken, support suboptions for RunOpenBabel
1.0 - initial release
*)
(* :Keywords:
3D, applet, Beaker, chemical structures, chemistry, ChemSpider, ChEMBL, graphics, Imago OCR, Java, JChemPaint,
JDraw, JME, models, molecules, OCR, Open Babel, PubChem *)
(* :Limitations:
currently limited handling of imported chemical file formats
needs Imago OCR and Open Babel to be installed for some functionality
*)
(* :Requirements:
Imago OCR (https://lifescience.opensource.epam.com/imago/index.html) for chemical structure OCR,
Open Babel (http://openbabel.org/) for 3D coordinate generation,
and whichever of JME (http://www.molinspiration.com/jme/), JChemPaint (http://jchempaint.github.io) or
Accelrys JDraw (http://accelrys.com/products/informatics/cheminformatics/draw/jdraw.php), for structure drawing, to be installed.
ChemSpider API key (https://developer.rsc.org/) needed for ChemSpider functionality.
*)
BeginPackage["MoleculeViewer`"]
Unprotect[MoleculeViewer, MoleculeRecognize, MakeMOL, MakeInChIKey,
GetCACTUS, GetChemicalData, GetChemSpider, GetPDB, GetProteinData, GetPubChem, GetZINC,
MoleculeDraw, GetMolecule, SetMolecule, JChemPaint, JDraw, JME,
ChEMBLMOLTo3D, ChEMBLSMILESTo3D, ChEMBLInChITo3D, ChEMBLInChIToMOL, ChEMBLSMILESToMOL,
ChEMBLAddHydrogens, ChEMBLSanitize, ChEMBLMakeLineNotation, ChEMBLMakeInChIKey, ChEMBLDescriptors,
RunImago, RunOpenBabel];
(* usage messages *)
MoleculeViewer::usage = "\!\(\*RowBox[{\"MoleculeViewer\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) displays a molecular model corresponding to \!\(\*StyleBox[\"expr\", \"TI\"]\). \!\(\*StyleBox[\"expr\", \"TI\"]\) can be a file name, a URL, a chemical name, a SMILES or an InChI string, or a list containing structural information."
MoleculeDraw::usage = "\!\(\*RowBox[{\"MoleculeDraw\", \"[\", \"]\"}]\) opens a blank instance of the default structure drawing applet.\n\!\(\*RowBox[{\"MoleculeDraw\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) opens the default structure drawing applet and sets the molecule displayed to \!\(\*StyleBox[\"expr\", \"TI\"]\).\n\!\(\*RowBox[{\"MoleculeDraw\", \"[\", RowBox[{StyleBox[\"\\\"Applet\\\"\",ShowStringCharacters->True], \"\[Rule]\", StyleBox[\"\\\"\\!\\(\\*StyleBox[\\\"applet\\\",\\\"TI\\\"]\\)\\\"\", ShowStringCharacters->True]}], \"]\"}]\) launches a specific structure drawing applet.\n\!\(\*RowBox[{\"MoleculeDraw\", \"[\", RowBox[{StyleBox[\"\\\"\\!\\(\\*StyleBox[\\\"applet\\\",\\\"TI\\\"]\\)\\\"\", ShowStringCharacters->True]}], \"]\"}]\) represents an operator form of MoleculeDraw that can be applied to an expression."
MoleculeRecognize::usage = "\!\(\*RowBox[{\"MoleculeRecognize\", \"[\", StyleBox[\"image\", \"TI\"], \"]\"}]\) recognizes molecular information in \!\(\*StyleBox[\"image\", \"TI\"]\) to generate structural information suitable for MoleculeViewer."
GetCACTUS::usage = "\!\(\*RowBox[{\"GetCACTUS\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) uses the NCI/CADD CACTUS Chemical Identifier Resolver to generate structural information suitable for MoleculeViewer."
GetChemicalData::usage = "\!\(\*RowBox[{\"GetChemicalData\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) uses the built-in ChemicalData function to generate structural information suitable for MoleculeViewer.\n\!\(\*RowBox[{\"GetChemicalData\", \"[\", RowBox[{StyleBox[\"expr\", \"TI\"],\",\", StyleBox[\"\\\"SMILES\\\"\",ShowStringCharacters->True]}], \"]\"}]\) or \!\(\*RowBox[{\"GetChemicalData\", \"[\", RowBox[{StyleBox[\"expr\", \"TI\"],\",\", StyleBox[\"\\\"InChI\\\"\",ShowStringCharacters->True]}], \"]\"}]\) will generate the corresponding line notation."
GetChemSpider::usage = "\!\(\*RowBox[{\"GetChemSpider\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) uses the ChemSpider API to generate structural information suitable for MoleculeViewer.\n\!\(\*RowBox[{\"ChemSpider\", \"[\", RowBox[{StyleBox[\"expr\", \"TI\"],\",\", StyleBox[\"\\\"SMILES\\\"\",ShowStringCharacters->True]}], \"]\"}]\) or \!\(\*RowBox[{\"GetChemSpider\", \"[\", RowBox[{StyleBox[\"expr\", \"TI\"],\",\", StyleBox[\"\\\"InChI\\\"\",ShowStringCharacters->True]}], \"]\"}]\) will generate the corresponding line notation."
GetMolecule::usage = "\!\(\*RowBox[{\"GetMolecule\", \"[\", \"]\"}]\) extracts structural information from the molecule currently displayed in the default structure drawing applet.\n\!\(\*RowBox[{\"GetMolecule\", \"[\", RowBox[{StyleBox[\"\\\"\\!\\(\\*StyleBox[\\\"applet\\\",\\\"TI\\\"]\\)\\\"\", ShowStringCharacters->True]}], \"]\"}]\) or \!\(\*RowBox[{\"GetMolecule\", \"[\", RowBox[{StyleBox[\"\\\"Applet\\\"\",ShowStringCharacters->True], \"->\", StyleBox[\"\\\"\\!\\(\\*StyleBox[\\\"applet\\\",\\\"TI\\\"]\\)\\\"\", ShowStringCharacters->True]}], \"]\"}]\) extracts structural information from a specific applet."
GetPDB::usage = "\!\(\*RowBox[{\"GetPDB\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) uses the RCSB PDB API to generate structural information suitable for MoleculeViewer."
GetProteinData::usage = "\!\(\*RowBox[{\"GetProteinData\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) uses the built-in ProteinData function to generate structural information suitable for MoleculeViewer."
GetPubChem::usage = "\!\(\*RowBox[{\"GetPubChem\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) uses the PubChem API to generate structural information suitable for MoleculeViewer.\n\!\(\*RowBox[{\"GetPubChem\", \"[\", RowBox[{StyleBox[\"expr\", \"TI\"],\",\", StyleBox[\"\\\"SMILES\\\"\",ShowStringCharacters->True]}], \"]\"}]\) or \!\(\*RowBox[{\"GetPubChem\", \"[\", RowBox[{StyleBox[\"expr\", \"TI\"],\",\", StyleBox[\"\\\"InChI\\\"\",ShowStringCharacters->True]}], \"]\"}]\) will generate the corresponding line notation."
GetZINC::usage = "\!\(\*RowBox[{\"GetZINC\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) uses the ZINC API to generate structural information suitable for MoleculeViewer.\n\!\(\*RowBox[{\"GetZINC\", \"[\", RowBox[{StyleBox[\"expr\", \"TI\"],\",\", StyleBox[\"\\\"SMILES\\\"\",ShowStringCharacters->True]}], \"]\"}]\) or \!\(\*RowBox[{\"GetZINC\", \"[\", RowBox[{StyleBox[\"expr\", \"TI\"],\",\", StyleBox[\"\\\"InChI\\\"\",ShowStringCharacters->True]}], \"]\"}]\) will generate the corresponding line notation."
MakeInChIKey::usage = "\!\(\*RowBox[{\"MakeInChIKey\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) constructs the InChI key corresponding to \!\(\*StyleBox[\"expr\", \"TI\"]\)."
MakeMOL::usage = "\!\(\*RowBox[{\"MakeMOL\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) constructs an MDL MOL file corresponding to \!\(\*StyleBox[\"expr\", \"TI\"]\)."
MoleculeCentroid::usage = "\!\(\*RowBox[{\"MoleculeCentroid\", \"[\", StyleBox[\"mol\", \"TI\"], \"]\"}]\) computes the center of mass of the molecule \!\(\*StyleBox[\"mol\", \"TI\"]\)."
MoleculeJoin::usage = "\!\(\*RowBox[{\"MoleculeJoin\", \"[\", RowBox[{SubscriptBox[StyleBox[\"mol\", \"TI\"], StyleBox[\"1\", \"TR\"]], \",\", SubscriptBox[StyleBox[\"mol\", \"TI\"], StyleBox[\"2\", \"TR\"]], \",\", StyleBox[\"\[Ellipsis]\", \"TR\"]}], \"]\"}]\) concatenates two or more molecules."
MoleculeNormalize::usage = "\!\(\*RowBox[{\"MoleculeNormalize\", \"[\", StyleBox[\"mol\", \"TI\"], \"]\"}]\) reorients the molecule \!\(\*StyleBox[\"mol\", \"TI\"]\) so that its center of mass is at the origin, and it lies along its plane of best fit."
MoleculeSplit::usage = "\!\(\*RowBox[{\"MoleculeSplit\", \"[\", StyleBox[\"mol\", \"TI\"], \"]\"}]\) splits the molecule \!\(\*StyleBox[\"mol\", \"TI\"]\) into its connected components."
MoleculeTransform::usage = "\!\(\*RowBox[{\"MoleculeTransform\", \"[\", RowBox[{StyleBox[\"mol\", \"TI\"], \",\", StyleBox[\"tfun\", \"TI\"]}], \"]\"}]\) transforms the molecule \!\(\*StyleBox[\"mol\", \"TI\"]\) with the transformation function \!\(\*StyleBox[\"tfun\", \"TI\"]\)."
RunImago::usage = "\!\(\*RowBox[{\"RunImago\", \"[\", StyleBox[\"image\", \"TI\"], \"]\"}]\) is an interface to Imago OCR, for generating an MDL MOL file for further use."
RunOpenBabel::usage = "\!\(\*RowBox[{\"RunOpenBabel\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) is an interface to Open Babel, for generating structural information suitable for MoleculeViewer."
SetDrawingApplet::usage = "\!\(\*RowBox[{\"SetDrawingApplet\", \"[\", RowBox[{StyleBox[\"\\\"\\!\\(\\*StyleBox[\\\"applet\\\",\\\"TI\\\"]\\)\\\"\", ShowStringCharacters->True]}], \"]\"}]\) sets the default Java chemical drawing applet used by MoleculeDraw, GetMolecule, and SetMolecule."
SetMolecule::usage = "\!\(\*RowBox[{\"SetMolecule\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) sets the chemical stucture in the applet opened by MoleculeDraw to \!\(\*StyleBox[\"expr\", \"TI\"]\).\n\!\(\*RowBox[{\"SetMolecule\", \"[\", RowBox[{StyleBox[\"\\\"\\!\\(\\*StyleBox[\\\"applet\\\",\\\"TI\\\"]\\)\\\"\", ShowStringCharacters->True]}], \"]\"}]\) represents an operator form of SetMolecule that can be applied to an expression."
BondRotate::usage = "\!\(\*RowBox[{\"BondRotate\", \"[\", RowBox[{StyleBox[\"mol\", \"TI\"], \",\", StyleBox[\"bond\", \"TI\"], \",\", StyleBox[\"\[Theta]\", \"TR\"]}], \"]\"}]\) rotates the molecule \!\(\*StyleBox[\"mol\", \"TI\"]\) counterclockwise around \!\(\*StyleBox[\"bond\", \"TI\"]\) by \!\(\*StyleBox[\"\[Theta]\", \"TR\"]\) radians."
ShiftIsolatedAtoms::usage = "\!\(\*RowBox[{\"ShiftIsolatedAtoms\", \"[\", StyleBox[\"mol\", \"TI\"], \"]\"}]\) moves the isolated atoms in molecule \!\(\*StyleBox[\"mol\", \"TI\"]\) closer to the connected components."
ChEMBLAddHydrogens::usage = "\!\(\*RowBox[{\"ChEMBLAddHydrogens\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) uses the ChEMBL Beaker API to add hydrogen atoms to \!\(\*StyleBox[\"expr\", \"TI\"]\)."
ChEMBLDescriptors::usage = "\!\(\*RowBox[{\"ChEMBLDescriptors\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) uses the ChEMBL Beaker API to generate chemical descriptors for \!\(\*StyleBox[\"expr\", \"TI\"]\)."
ChEMBLInChITo3D::usage = "\!\(\*RowBox[{\"ChEMBLInChITo3D\", \"[\", StyleBox[\"inchi\", \"TI\"], \"]\"}]\) uses the ChEMBL Beaker API to generate structural information from the InChI string \!\(\*StyleBox[\"inchi\", \"TI\"]\)."
ChEMBLInChIToMOL::usage = "\!\(\*RowBox[{\"ChEMBLInChIToMOL\", \"[\", StyleBox[\"inchi\", \"TI\"], \"]\"}]\) uses the ChEMBL Beaker API to generate an MDL MOL file from the InChI string \!\(\*StyleBox[\"inchi\", \"TI\"]\)."
ChEMBLMakeInChIKey::usage = "\!\(\*RowBox[{\"ChEMBLMakeInChIKey\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) uses the ChEMBL Beaker API to generate an InChI key from \!\(\*StyleBox[\"expr\", \"TI\"]\)."
ChEMBLMakeLineNotation::usage = "\!\(\*RowBox[{\"ChEMBLMakeLineNotation\", \"[\", RowBox[{StyleBox[\"expr\", \"TI\"], \",\", StyleBox[\"\\\"\\!\\(\\*StyleBox[\\\"type\\\",\\\"TI\\\"]\\)\\\"\", ShowStringCharacters->True]}], \"]\"}]\) uses the ChEMBL Beaker API to generate line notation from \!\(\*StyleBox[\"expr\", \"TI\"]\), where \!\(\*RowBox[{StyleBox[\"\\\"\\!\\(\\*StyleBox[\\\"type\\\",\\\"TI\\\"]\\)\\\"\", ShowStringCharacters->True]}]\) can be either of \"SMILES\" or \"InChI\"."
ChEMBLMOLTo3D::usage = "\!\(\*RowBox[{\"ChEMBLMOLTo3D\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) uses the ChEMBL Beaker API to generate structural information from \!\(\*StyleBox[\"expr\", \"TI\"]\) in MDL MOL format."
ChEMBLSanitize::usage = "\!\(\*RowBox[{\"ChEMBLSanitize\", \"[\", StyleBox[\"expr\", \"TI\"], \"]\"}]\) uses the ChEMBL Beaker API to sanitize \!\(\*StyleBox[\"expr\", \"TI\"]\)."
ChEMBLSMILESTo3D::usage = "\!\(\*RowBox[{\"ChEMBLSMILESTo3D\", \"[\", StyleBox[\"smiles\", \"TI\"], \"]\"}]\) uses the ChEMBL Beaker API to generate structural information from the SMILES string \!\(\*StyleBox[\"smiles\", \"TI\"]\)."
ChEMBLSMILESToMOL::usage = "\!\(\*RowBox[{\"ChEMBLSMILESToMOL\", \"[\", StyleBox[\"smiles\", \"TI\"], \"]\"}]\) uses the ChEMBL Beaker API to generate an MDL MOL file from the SMILES string \!\(\*StyleBox[\"smiles\", \"TI\"]\)."
$ChemSpiderAPIToken::usage = "$ChemSpiderAPIToken is the API token used by the ChemSpider API."
$DefaultLengthUnit::usage = "$DefaultLengthUnit is the default unit of length used by MoleculeViewer and related functions."
$DrawingApplets::usage = "$DrawingApplets gives the list of chemical structure drawing Java applets currently supported by MoleculeViewer."
$OpenBabelVersion::usage = "$OpenBabelVersion displays the version of Open Babel available."
OPSINNameToStructure;
$JME; JME; $JDraw; JDraw; $JChemPaint; JChemPaint;
GetJMEMOL; SetJMEMOL; GetJMESMILES; LaunchJME; (* for future removal; retained for backward compatibility *)
(* declare symbols for older versions *)
Highlighted; MemoryConstraint; PlotLegends;
RunProcess; ProcessEnvironment; ProcessDirectory;
(* error/warning messages *)
MoleculeViewer::badchem = "Invalid structural information given to MoleculeViewer.";
MoleculeViewer::badfile = "Valid structural information could not be generated from the file.";
MoleculeViewer::badstrng = "Valid structural information could not be generated from the input string.";
MoleculeViewer::ftconv = "The file `1` is not in a format supported by Import. Conversion with OpenBabel will be attempted.";
MoleculeViewer::is2d = "Two-dimensional coordinates detected; embedding to 3D.";
MoleculeViewer::nbnd = "Incomplete or missing bond information for PlotStyle \[Rule] `1`; using default PlotStyle instead.";
MoleculeViewer::nstl = "PlotStyle \[Rule] `1` is not supported; using default PlotStyle instead.";
$DefaultLengthUnit::badunit = "Invalid unit of length `1` assigned to $DefaultLengthUnit.";
GetChemSpider::token = "ChemSpider API key in $ChemSpiderAPIToken not detected or invalid. Please obtain one from https://developer.rsc.org/.";
GetChemSpider::obsmet = "Method \[Rule] \"SOAP\" is now obsolete. Please obtain a new API key from https://developer.rsc.org/.";
GetChemSpider::noconv = "Cannot convert input of type `1` into `2`.";
MoleculeDraw::nopre = "No preprocessing method supported.";
MoleculeDraw::noapp = GetMolecule::noapp = SetMolecule::noapp = "The `1` applet could not be loaded.";
GetMolecule::nopost = "No postprocessing method supported.";
GetMolecule::nsupo = "`1` output is not supported for the `2` applet.";
SetMolecule::nsupi = "`1` input is not natively supported for the `2` applet. Conversion will be attempted.";
RunOpenBabel::nobab = "Open Babel not installed; please download from http://openbabel.org/ or check Environment[\"PATH\"].";
RunOpenBabel::bdmtd = "Value of option Method \[Rule] `1` is not Automatic, \"Conformer\", \"Generate\", or \"Minimize\". The default method `2` will be used.";
RunOpenBabel::bdff = "Value of option \"ForceField\" \[Rule] `1` is not Automatic, \"GAFF\", \"Ghemical\", \"MMFF94\", \"MMFF94s\", or \"UFF\".";
MoleculeViewer::mem = RunOpenBabel::mem = "Memory allocated by Open Babel exceeded `1` bytes, and was then aborted. Increasing the value of the MemoryConstraint option may yield a result.";
MoleculeViewer::time = RunOpenBabel::time = "Time spent by Open Babel exceeded `1` seconds, and was then aborted. Increasing the value of the TimeConstraint option may yield a result.";
RunImago::noimg = "Imago OCR not installed; please download from https://lifescience.opensource.epam.com/download/imago.html or check Environment[\"PATH\"].";
RunImago::mem = "Memory allocated by Imago OCR exceeded `1` bytes, and was then aborted. Increasing the value of the MemoryConstraint option may yield a result.";
RunImago::time = "Time spent by Imago OCR exceeded `1` seconds, and was then aborted. Increasing the value of the TimeConstraint option may yield a result.";
MoleculeRecognize::noocr = "No suitable OCR method found.";
MoleculeRecognize::badimg = "Valid structural information could not be generated from the image.";
ChEMBLMOLTo3D::bdmtd = ChEMBLSMILESTo3D::bdmtd = "Value of option Method \[Rule] `1` is not Automatic, \"ETKDG\", \"KDG\", \"MMFF\", or \"UFF\". The default method `2` will be used.";
MakeMOL::ncnv = "Unable to convert to MOL file.";
BondRotate::mult = "Cannot rotate molecule about the `1` bond `2`.";
BondRotate::nobnd = "Bond `1` cannot be found in the input molecule.";
BondRotate::ring = "Cannot rotate molecule about the bond `1` in a ring.";
MoleculeTransform::notort = "Matrix `1` is not an orthogonal matrix.";
MoleculeTransform::notrgd = "Matrix `1` does not correspond to a rigid transformation; stereochemistry might be affected.";
Begin["`Private`"]
Needs["Utilities`URLTools`"]
(* some variables for internal use *)
$debug = False;
$adjustNormals = True;
$getAllPDBComponents = True;
(* length unit for coordinates and labels *)
If[$VersionNumber >= 9.,
Quantity[$DefaultLengthUnit = If[$VersionNumber >= 12., "Angstroms", "Picometers"]];
$ValidLengthUnitQ := Quiet[TrueQ[UnitDimensions[$DefaultLengthUnit] === {{"LengthUnit", 1}}], {Quantity::unkunit}];
conversionFactor[uIn_, uOut_] := QuantityMagnitude[UnitConvert[Quantity[uIn], uOut]];
$conversionFactor := If[$ValidLengthUnitQ, conversionFactor["Picometers", $DefaultLengthUnit],
Message[$DefaultLengthUnit::badunit, $DefaultLengthUnit]; Return[$Failed]];
unitLabel[u_] := With[{s = QuantityUnits`Private`QuantityLabel[u, "Format" -> "UnitLabel"]}, If[StringQ[s], StringTrim[s, "\""], DisplayForm[s]]],
Needs["Units`"];
$DefaultLengthUnit = Units`Pico Units`Meter;
$ValidLengthUnitQ := Quiet[Variables[Units`SI[$DefaultLengthUnit]] === {Units`Meter}];
conversionFactor[uIn_, uOut_] := Units`Convert[uIn, uOut]/uOut;
$conversionFactor := If[$ValidLengthUnitQ, conversionFactor[Units`Pico Units`Meter, $DefaultLengthUnit],
Message[$DefaultLengthUnit::badunit, $DefaultLengthUnit]; Return[$Failed]];
unitLabel[u_] := Which[u === Units`Pico Units`Meter, "pm", u === Units`Angstrom, "\[Angstrom]", True, u]
];
(* utility functions *)
If[$VersionNumber < 10.2, Nothing := Unevaluated[]];
$atoms = Array[ElementData[#, "Symbol"] &, 118] ~Join~ {"D", "T"};
validAtomQ[s_] := StringQ[s] && MemberQ[$atoms, s]
(* CPK-type colors extracted from ElementData[elem, "IconColor"] *)
$colorRules = Thread[$atoms -> ((Apply[RGBColor, IntegerDigits[FromDigits[#, 16], 256, 3]/255.] & /@
ImportString[Uncompress["1:eJw9Ur25HDEIfIEbcQdIiB+1YadOQEKp23G51sLeOwU3HywwzPDT//76/e/H11fsc39/\
oPVNH7SW+olE4zD4g85xcnrQhOc9aJhAYFUgYsvs2Mb6INu390ikElsSwZ4tY4HWLLscW\
PqiowCJQo70/iCeEd0epL6lpqmye3YR82g5Lfh5D/Kz+qppfF+yV5uzYvfPCgUwIxaDCcWA\
YAMlWqpQWdkKDq8upjltmrWZWb/ZYhVm2pLzZJx9Jvt92aSmvGjM1I/QqDirfBQXCovckq\
8PpdU4C1Zuicvcc0bXyZaoDYWZWQB2zc3v9/eVkntqdvbrEa/sTHIFTH7BWF5uEAQs3+DtR\
83eLBGqpH7Xwnh92y5UaLhT1u7tVKpttnsAyeVMH6nBmrpGViyUGPmdhwBm50t9YO7rSLM\
Utz0OQjk4pO/ybUDPPTRwVUwmWq+LFb8vu7i65ZYWtKz8MArNmBI3Se2l02EuDTbER7Urdr\
Fy3S8DGrURCU2uG49xSiFzWnWxV5QzMoaqY5aDrXHNAJAJyZ66yyl0XT1QzhhE1nJM2nkHwv\
feq3NoW1TsRb00WHy8dut8NU+k94iyYm7iYmB9RN3Bo6RWbI6mtdtCLzUskCT7OfTD5Ux/li9nL\
sXzok5WqEXdgffm5b63piNr7TQaNW01HOXqbG28mjbAVfzgoL0ovtFG+w/xJTNp"], "List", "Numeric" -> False]) ~Join~
{RGBColor[0.6925, 0.715, 0.828], RGBColor[0.6925, 0.8092, 0.715]})];
(* D and T colors: {Blend[{ColorData["Atoms", "H"], RGBColor[0, 0, 0.753]}, 1/4], Blend[{ColorData["Atoms", "H"], RGBColor[0, 0.628, 0]}, 1/4]} *)
(* Pyykkö's covalent radii; https://doi.org/10.1002/chem.200800987 ; entries for deuterium and tritium were slightly reduced from hydrogen *)
$elementCovalentRadii = {32, 46, 133, 102, 85, 75, 71, 63, 64, 67, 155, 139, 126, 116, 111,
103, 99, 96, 196, 171, 148, 136, 134, 122, 119, 116, 111, 110, 112,
118, 124, 121, 121, 116, 114, 117, 210, 185, 163, 154, 147, 138,
128, 125, 125, 120, 128, 136, 142, 140, 140, 136, 133, 131, 232,
196, 180, 163, 176, 174, 173, 172, 168, 169, 168, 167, 166, 165,
164, 170, 162, 152, 146, 137, 131, 129, 122, 123, 124, 133, 144,
144, 151, 145, 147, 142, 223, 201, 186, 175, 169, 170, 171, 172,
166, 166, 168, 168, 165, 167, 173, 176, 161, 157, 149, 143, 141,
134, 129, 128, 121, 122, 136, 143, 162, 175, 165, 157, (* D and T *) 30, 28};
$sizeRules = Thread[$atoms -> N[$elementCovalentRadii/2]];
(* Alvarez's van der Waals radii; https://doi.org/10.1039/C3DT50599E ; missing entries given a value of 250 (sodium radius) *)
$vdWRadii = N[{120, 143, 212, 198, 191, 177, 166, 150, 146, 158, 250, 251, 225, 219, 190,
189, 182, 183, 273, 262, 258, 246, 242, 245, 245, 244, 240, 240, 238, 239,
232, 229, 188, 182, 186, 225, 321, 284, 275, 252, 256, 245, 244, 246, 244,
215, 253, 249, 243, 242, 247, 199, 204, 206, 348, 303, 298, 288, 292, 295,
250, 290, 287, 283, 279, 287, 281, 283, 279, 280, 274, 263, 253, 257, 249,
248, 241, 229, 232, 245, 247, 260, 254, 250, 250, 250, 250, 250, 280, 293,
288, 271, 282, 281, 283, 305, 340, 305, 270, 250, 250, 250, 250, 250, 250,
250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, (* D and T *) 120, 120}];
$vdWRules = Thread[$atoms -> $vdWRadii];
(* for making translucent colors *)
If[$VersionNumber >= 10.,
translucentColorQ[col_] := ColorQ[col] && With[{l = Length[col]}, Switch[Head[col],
GrayLevel, l == 2,
RGBColor | Hue, l == 4,
CMYKColor, l == 5,
XYZColor | LABColor | LUVColor | LCHColor, l == 4,
_, False] && 0 <= Last[col] < 1],
translucentColorQ[col_] := With[{l = Length[col]},
Switch[Head[col],
GrayLevel, l == 2,
RGBColor | Hue, l == 4,
CMYKColor, l == 5,
_, False] && 0 <= Last[col] < 1]
]
makeTranslucent[dir_] := If[translucentColorQ[dir] || Head[dir] === Opacity, dir, Opacity[0.6, dir]]
(* Hill system order for atoms *)
hillOrder["C", _] = 1; hillOrder[_, "C"] = -1;
hillOrder["H", _] = 1; hillOrder[_, "H"] = -1;
hillOrder["D", _] = 1; hillOrder[_, "D"] = -1;
hillOrder["T", _] = 1; hillOrder[_, "T"] = -1;
hillOrder[s1_, s2_] := Order[s1, s2];
(* impose time and memory constraints on an evaluation *)
SetAttributes[constrainedEvaluate, HoldFirst];
constrainedEvaluate[expr_, fun_, mem_, time_] := Module[{m = mem, t = time},
Switch[m,
_Quantity, m = Check[QuantityMagnitude[UnitConvert[m, "Bytes"]], Return[$Failed, Module], Quantity::compat],
_?NumericQ | Infinity, m = Round[Abs[m]],
_, Return[$Failed, Module]];
Switch[t,
_Quantity, t = Check[QuantityMagnitude[UnitConvert[t, "Seconds"]], Return[$Failed, Module], Quantity::compat],
_?NumericQ | Infinity, t = Round[Abs[t]],
_, Return[$Failed, Module]];
TimeConstrained[MemoryConstrained[expr, m, Message[fun::mem, m]; $Failed], t, Message[fun::time, t]; $Failed]]
(* percent-encoding for URLs *)
percentEncode[s_String] := If[$VersionNumber >= 10., StringReplace[URLEncode[s], "+" -> "%20"],
StringReplace[s, RegularExpression["[^\\w/\\?=:._~]"] :>
StringJoin["%", ToUpperCase[IntegerString[First[ToCharacterCode["$0"]], 16]]]]]
(* find normal of best-fit plane *)
getNormal[mat_?MatrixQ, sv : (True | False) : False] := With[{svd = SingularValueDecomposition[Standardize[mat, Mean, 1 &], {-1}, Tolerance -> 0]},
If[TrueQ[sv], FlattenAt[Flatten[Rest[svd], {1, 3}], 1], Flatten[Last[svd]]]]
(* validate input format for viewer *)
validateChem[{vertexTypes_, edgeRules_, edgeTypes_, atomPositions_}] :=
With[{dim = Dimensions[atomPositions], e = Length[edgeRules], v = Length[vertexTypes]},
(e == Length[edgeTypes] && v == First[dim]) &&
VectorQ[vertexTypes, StringQ] && Complement[vertexTypes, $atoms] === {} &&
MatchQ[edgeRules, {(_Integer?Positive -> _Integer?Positive) ..} | {}] && Max[List @@@ edgeRules] <= v &&
MatchQ[edgeTypes, {("Single" | "Double" | "Triple" | "Aromatic") ..} | {}] &&
((MatrixQ[atomPositions, NumberQ] ||
(MatrixQ[atomPositions, QuantityUnits`NumberQuantityQ] &&
MatrixQ[QuantityUnit[atomPositions], UnitDimensions[#] === {{"LengthUnit", 1}} &])) &&
MatchQ[Last[dim], 2 | 3] && Positive[Norm[atomPositions, Infinity]])]
validateChem[__] := False
(* for XYZ, PDB, CIF formats *)
inferBonds[vertexTypes_List, atomPositions_List?MatrixQ] := inferBonds[vertexTypes, atomPositions, 40. $conversionFactor, 25. $conversionFactor, 8]
inferBonds[vertexTypes_List, atomPositions_List?MatrixQ, minDistance_, bondTolerance_, maxNeighbors_Integer] /; Length[vertexTypes] == Length[atomPositions] :=
Module[{pos = atomPositions, atomP, curAtom, maxD, near, nearD, neighbors, nF, rads},
If[MatrixQ[pos, QuantityUnits`NumberQuantityQ], pos = QuantityMagnitude[UnitConvert[pos, $DefaultLengthUnit]]];
pos = SetPrecision[pos, MachinePrecision];
rads = N[vertexTypes /. Thread[$atoms -> ($elementCovalentRadii $conversionFactor)]];
maxD = Max[rads] + bondTolerance;
nF = Nearest[pos -> If[$VersionNumber >= 11.1, "Index", Automatic]];
neighbors = Function[idx,
curAtom = rads[[idx]]; atomP = pos[[idx]];
near = DeleteCases[nF[atomP, {maxNeighbors, curAtom + maxD}], idx];
nearD = SquaredEuclideanDistance[#, atomP] & /@ pos[[near]];
Pick[near, MapThread[minDistance < #1 < #2 &,
{nearD, (curAtom + rads[[near]] + bondTolerance)^2}]]];
Union[Sort /@ Flatten[Array[Thread[# -> neighbors[#]] &, Length[vertexTypes]]]]]
(* regular expressions for sanity-checking InChI and InChIKey *)
inchirx = RegularExpression["^(InChI=1)(S*)/([a-zA-Z0-9.])+/(.+)"];
inkeyrx = RegularExpression["^(InChIKey=)?([A-Z]{14})-([A-Z]{10})-([A-Z])$"];
(* SMILES sanity check *)
smilesElems = With[{syms = Drop[$atoms, -2], pos = Transpose[{{1, 5, 6, 7, 8, 9, 15, 16, 19, 23, 39, 53, 74, 92}}]}, Delete[syms, pos] ~Join~ Extract[syms, pos]];
validSymbols = smilesElems ~Join~ {"c", "n", "o", "p", "s", "as", "se"} ~Join~ {"-", "=", "#", ":", "(", ")", "[", "]", "%", ".", "/", "\\", "@", "+", DigitCharacter};
validSMILESQ[s_] := StringQ[s] && ! StringFreeQ[s, LetterCharacter] && s === StringJoin[StringCases[s, validSymbols]]
(* format numbers for Tooltip *)
numDisplay[x_?NumberQ] := If[0.001 < Abs[x] < 999., x, ScientificForm[x, ExponentStep -> If[Abs[x] > 1, 3, 1]]]
(* incircle of a polygon, for rendering aromatic rings *)
incirc[pts_?MatrixQ, scale_: 1] := Block[{cen, cp, nrm, psh, rad, tf},
cen = Mean[pts]; psh = Standardize[pts, Mean, 1 &];
rad = scale Mean[Norm /@ psh] Cos[Pi/Length[pts]];
nrm = Flatten[Last[SingularValueDecomposition[psh, {-1}, Tolerance -> 0]]];
tf = Quiet[Composition[TranslationTransform[cen], RotationTransform[{{0, 0, 1}, nrm}]], RotationTransform::spln];
cp = tf[rad {{1, 0, 0}, {1, 1, 0}, {-1, 1, 0}, {-1, 0, 0}, {-1, -1, 0}, {1, -1, 0}, {1, 0, 0}}];
BSplineCurve[cp, SplineDegree -> 2, SplineKnots -> {0, 0, 0, 1/4, 1/2, 1/2, 3/4, 1, 1, 1}, SplineWeights -> {1, 1/2, 1/2, 1, 1/2, 1/2, 1}]]
(* construct molecular formula *)
buildFormula[alist : {__String}] := Row[Subscript @@@ Sort[Tally[alist], hillOrder[#1[[1]], #2[[1]]] == 1 &] /. Subscript[s_, 1] :> s]
(* for computing molecular weight *)
SetAttributes[atomicMass, Listable];
atomicMass[s_String] := With[{u = If[$VersionNumber >= 9., Quantity["AtomicMassUnit"], 1]}, Switch[s, "D", 2. u, "T", 3. u, _, ElementData[s, "AtomicMass"]]]
buildMolarMass[alist : {__String}] := With[{s = Sum[at[[2]] atomicMass[at[[1]]], {at, Tally[alist]}]},
If[$VersionNumber >= 9., UnitConvert[s Quantity["AvogadroConstant"], "Grams"/"Moles"], ToString[s] <> " g/mol"]]
(* molecule manipulation utilities *)
(* centroid of a molecule *)
MoleculeCentroid[{atoms : {__String}, edgeRules : ({} | None), edgeTypes : ({} | None), coords_?MatrixQ}, opts___] :=
With[{wts = If[$VersionNumber >= 9., QuantityMagnitude, Identity][atomicMass[atoms]]}, wts.coords/Total[wts]]
MoleculeCentroid[{atoms : {__String}, edgeRules : {__Rule}, edgeTypes_List, coords_?MatrixQ}, opts : OptionsPattern[{"IncludeIsolatedAtoms" -> True}]] :=
Module[{al = atoms, pts = coords, pos, wts},
If[! TrueQ[OptionValue["IncludeIsolatedAtoms"]],
pos = Transpose[{Complement[Range[Length[atoms]], Union[Flatten[List @@@ edgeRules]]]}];
al = Delete[al, pos]; pts = Delete[pts, pos]];
wts = If[$VersionNumber >= 9., QuantityMagnitude, Identity][atomicMass[al]];
wts.pts/Total[wts]]
(* center and reorient a molecule *)
MoleculeNormalize[mol : {{__String}, {__Rule}, _List, _?MatrixQ}] :=
With[{cen = MoleculeCentroid[mol], nrm = getNormal[QuantityMagnitude[Last[mol]]]},
Quiet[MapAt[Composition[RotationTransform[{nrm, {0, 0, 1}}], TranslationTransform[-cen],
If[MatrixQ[#, QuantityUnits`NumberQuantityQ],
QuantityMagnitude[UnitConvert[#, $DefaultLengthUnit]], #] &], mol, 4], RotationTransform::spln]]
(* split molecule into connected components *)
MoleculeSplit[mol : {{__String}, {} | None, {} | None, _?MatrixQ}, _] := mol
MoleculeSplit[{atoms : {__String}, edgeRules : {__Rule}, edgeTypes_List, coords_?MatrixQ}] :=
Module[{mcs, molExtract, skel},
skel = Graph[Range[Length[atoms]], edgeRules, DirectedEdges -> False, EdgeWeight -> edgeTypes, GraphLayout -> None];
molExtract[g_Graph] := With[{id = VertexList[g], ed = EdgeList[g]},
{atoms[[id]], Composition[Sort, Rule] @@@ (ed /. MapIndexed[#1 -> First[#2] &, id]),
PropertyValue[{skel, #}, EdgeWeight] & /@ ed, coords[[id]]}];
molExtract /@ ConnectedGraphComponents[skel]]
(* join two or more molecules *)
MoleculeJoin[mols : (({{__String}, {__Rule} | {} | None, {__String} | {} | None, _?MatrixQ} | {} | $Failed | _Missing) ..)] :=
Module[{molList = DeleteCases[{mols}, {} | $Failed | _Missing, {1}], atoms},
atoms = molList[[All, 1]];
{Flatten[atoms],
Flatten[MapThread[Replace[#1, k_Integer :> k + #2, {2}] &,
{molList[[All, 2]], Prepend[Accumulate[Length /@ Most[atoms]], 0]}]],
Flatten[molList[[All, 3]]],
Flatten[If[MatrixQ[#, QuantityUnits`NumberQuantityQ], QuantityMagnitude[UnitConvert[#, $DefaultLengthUnit]], #] & /@
molList[[All, 4]], 1]}]
(* bring distant isolated atoms closer *)
ShiftIsolatedAtoms[mol : {{__String}, {} | None, {} | None, _?MatrixQ}, _] := mol
ShiftIsolatedAtoms[{atoms : {__String}, edgeRules : {__Rule}, edgeTypes_List, coords_?MatrixQ}, h_: 1.6] :=
Module[{al = atoms, pts = coords, cent, dist, isd, isf, isol, pos, wts},
pos = Transpose[{Complement[Range[Length[atoms]], Union[Flatten[List @@@ edgeRules]]]}];
al = Delete[al, pos]; pts = Delete[pts, pos];
wts = If[$VersionNumber >= 9., QuantityMagnitude, Identity][atomicMass[al]];
cent = wts.pts/Total[wts]; dist = Max[Norm[cent - #] & /@ pts];
isol = Extract[coords, pos]; isd = Norm[cent - #] & /@ isol; isf = Clip[isd, {0, h dist}]/isd;
{atoms, edgeRules, edgeTypes, ReplacePart[coords, Thread[pos -> (1 - isf) ConstantArray[cent, Length[isol]] + isf isol]]}]
(* rotate about a single bond *)
BondRotate[{atoms : {__String}, edgeRules : {__Rule}, edgeTypes_List, coords_?MatrixQ}, bond : (_Integer -> _Integer), th_?NumericQ] :=
Module[{b0, b1, bpos, btyp, cc, ed, p0, sel},
bpos = Position[edgeRules, bond | Reverse[bond]];
If[bpos =!= {}, bpos = First[bpos], Message[BondRotate::nobnd, bond]; Return[$Failed, Module]];
If[(btyp = Extract[edgeTypes, bpos]) =!= "Single",
Message[BondRotate::mult, ToLowerCase[btyp], bond]; Return[$Failed, Module]];
If[Length[edgeRules] == 1, Return[{atoms, edgeRules, edgeTypes, coords}, Module]];
{b0, b1} = List @@ bond; ed = Delete[edgeRules, bpos];
cc = ConnectedComponents[Graph[ed, DirectedEdges -> False, GraphLayout -> None]];
If[Length[cc] > 1, sel = Flatten[Select[cc, MemberQ[#, b1] &]],
Message[BondRotate::ring, bond]; Return[$Failed, Module]];
p0 = coords[[b0]];
{atoms, edgeRules, edgeTypes,
ReplacePart[coords, Thread[sel -> RotationTransform[th, coords[[b1]] - p0, p0][coords[[sel]]]]]}]
(* apply a geometric transform to a molecule *)
MoleculeTransform[mol : {{__String}, {__Rule} | {} | None, {__String} | {} | None, _?MatrixQ}, tfun_TransformationFunction] := Module[{pos, tmat},
pos = Last[mol];
If[MatrixQ[pos, QuantityUnits`NumberQuantityQ],
pos = QuantityMagnitude[UnitConvert[pos, $DefaultLengthUnit]]];
tmat = Drop[TransformationMatrix[tfun], -1, -1];
If[Last[Dimensions[pos]] != Length[tmat], Message[MoleculeTransform::icdims, tmat]; Return[$Failed, Module]];
If[! OrthogonalMatrixQ[tmat], Message[MoleculeTransform::notort, tmat]; Return[$Failed, Module]];
If[Det[tmat] != 1, Message[MoleculeTransform::notrgd, tmat]];
ReplacePart[mol, {-1} -> tfun[pos]]]
MoleculeTransform[mol_, vec_?VectorQ] := With[{pos = Last[mol]},
If[Length[vec] == Last[Dimensions[pos]],
MoleculeTransform[mol, TranslationTransform[vec]], Message[MoleculeTransform::icdims, vec]; $Failed]]
MoleculeTransform[mol_, mat_?MatrixQ] := With[{pos = Last[mol]},
If[(Equal @@ Dimensions[mat]) && Length[mat] == Last[Dimensions[pos]],
MoleculeTransform[mol, AffineTransform[mat]], Message[MoleculeTransform::icdims, mat]; $Failed]]
MoleculeTransform[mol_, {mat_?MatrixQ, vec_?VectorQ}] :=
With[{pos = Last[mol], tf = Check[AffineTransform[{mat, vec}], $Failed, AffineTransform::idimr]},
If[tf =!= $Failed && Length[vec] == Last[Dimensions[pos]], MoleculeTransform[mol, tf],
Message[MoleculeTransform::icdims, Drop[TransformationMatrix[tf], -1, -1]]; $Failed]]
(* basic importing functions *)
molFromFile[mol_String, type_String : "MOL"] := Block[{res},
If[$VersionNumber < 12.,
res = Check[Import[mol, {type, {"VertexTypes", "EdgeRules", "EdgeTypes", "VertexCoordinates"}}],
Message[MoleculeViewer::badfile]; Return[$Failed, Block]];
res = MapAt[(# $conversionFactor) &, res, {4}];
If[validateChem[res], res, Message[MoleculeViewer::badfile]; $Failed],
res = Check[Import[mol, type], Message[MoleculeViewer::badfile]; Return[$Failed, Block]];
processMoleculeObject[res]]]
molFromString[mol_String] := Block[{res},
If[$VersionNumber < 12.,
res = Check[ImportString[mol, {"MOL", {"VertexTypes", "EdgeRules", "EdgeTypes", "VertexCoordinates"}}], Return[$Failed, Block]];
res = MapAt[(# $conversionFactor) &, res, {4}];
If[validateChem[res], res, $Failed],
processMoleculeObject[ImportString[mol, "MOL"]]]]
processChemicalFile[fName_String, type : (_String | Automatic) : Automatic] := Module[{atoms, bonds, ext, fileName, het, ida, idx, pos, prop, prts, res},
If[FileExistsQ[fName], fileName = fName,
fileName = FindFile[fName];
If[fileName === $Failed, Message[MoleculeViewer::fnfnd, fName]; Return[$Failed, Module]]];
ext = type;
If[ext === Automatic, ext = FileFormat[fileName];
If[ext === "", Message[MoleculeViewer::fftype, fName]; Return[$Failed, Module]]];
(* special handling for CIF *)
If[StringMatchQ[ext, "CIF", IgnoreCase -> True], ext = "MMCIF"]; If[TrueQ[$debug], Print[ext]];
prop = Quiet[Import[fileName, {ext, "Elements"}]];
If[prop === $Failed || FreeQ[prop, "VertexTypes" | "EdgeRules" | "EdgeTypes" | "VertexCoordinates"],
Message[MoleculeViewer::ftconv, fName]; Return[openBabelConvert[fileName, FileExtension[fileName], True, Automatic, 60], Module]];
If[FreeQ[prop, "EdgeRules" | "EdgeTypes"],
(* xyz, CIF or PDB format *)
If[TrueQ[$debug], Print["XYZ/PDB/CIF"]];
prts = {"VertexTypes", "VertexCoordinates"};
If[StringMatchQ[ext, "PDB", IgnoreCase -> True],
If[TrueQ[$getAllPDBComponents], AppendTo[prts, "ResidueIndex"], prts = Join[prts, {"ResidueIndex", "AdditionalIndex"}]]];
res = Check[Import[fileName, {ext, prts}], Message[MoleculeViewer::badfile]; Return[$Failed, Module]];
{atoms, pos, idx, ida} = PadRight[res, 4, Missing["NotAvailable"]];
pos = If[MatrixQ[pos, NumberQ], pos $conversionFactor, QuantityMagnitude[UnitConvert[pos, $DefaultLengthUnit]]];
If[ListQ[idx], idx = Transpose[{Sort[Flatten[idx]]}]; (* separate out main and additional atoms for PDB *)
If[TrueQ[$getAllPDBComponents], het = {Delete[atoms, idx], Delete[pos, idx]},
If[ListQ[ida], ida = Transpose[{Sort[Flatten[ida]]}];
het = {Extract[atoms, ida], Extract[pos, ida]},
het = {{}, {}}]];
If[het =!= {{}, {}},
res = {Extract[atoms, idx], Extract[pos, idx]};
If[VectorQ[atoms, StringQ] && MatrixQ[pos], {res, het}, Message[MoleculeViewer::badfile]; $Failed],
If[VectorQ[atoms, StringQ] && MatrixQ[pos], {{atoms, pos}, Missing["NotAvailable"]}, Message[MoleculeViewer::badfile]; $Failed]],
bonds = inferBonds[atoms, pos];
res = {atoms, bonds, ConstantArray["Single", Length[bonds]], pos};
If[validateChem[res], res, Message[MoleculeViewer::badfile]; $Failed]],
(* normal mode *)
Which[StringMatchQ[ext, "MOL", IgnoreCase -> True], If[TrueQ[$debug], Print["MOL"]]; molFromFile[fileName], (* special treatment for MOL files *)
StringMatchQ[ext, "HIN", IgnoreCase -> True],
If[TrueQ[$debug], Print["HIN"]];
res = Check[Import[fileName, {ext, {"VertexTypes", "EdgeRules", "EdgeTypes", "VertexCoordinates"}}],
Message[MoleculeViewer::badfile]; Return[$Failed, Module]];
(* extra factor for Å *) res = Map[Function[r, MapAt[(100 $conversionFactor #) &, r, -1]], Transpose[res]];
If[validateChem[#], #, Message[MoleculeViewer::badfile]; $Failed] & /@ res,
True,
If[TrueQ[$debug], Print["SDF/MOL2"]];
If[$VersionNumber < 12.,
res = Check[Import[fileName, {ext, {"VertexTypes", "EdgeRules", "EdgeTypes", "VertexCoordinates"}}],
Message[MoleculeViewer::badfile]; Return[$Failed, Module]];
If[StringMatchQ[ext, "MOL2" | "SDF", IgnoreCase -> True],
res = Map[Function[r, MapAt[(# $conversionFactor) &, r, -1]], Transpose[res]]];
If[StringMatchQ[ext, "MOL2", IgnoreCase -> True], res = res /. "Amide" -> "Single"; (* special treatment for MOL2 unconventional bonds *)
If[! FreeQ[res, "Dummy" | "Unknown" | "Not Connected"],
res = With[{bp = Table[! MatchQ[bb, "Dummy" | "Unknown" | "Not Connected"], {bb, #[[3]]}]},
ReplacePart[#, Thread[{2, 3} -> {Pick[#[[2]], bp], Pick[#[[3]], bp]}]]] & /@ res]];
If[validateChem[#], #, Message[MoleculeViewer::badfile]; $Failed] & /@ res,
res = Check[Import[fileName, ext], Message[MoleculeViewer::badfile]; Return[$Failed, Module]];
processMoleculeObject /@ res]]]]
processChemicalURL[url_String, type : (_String | Automatic) : Automatic, fileName : (_String | Automatic) : Automatic] := Block[{fName = fileName, fnrx, tmp, urlrx},
(* regular expression for parsing a URL, from https://tools.ietf.org/html/rfc3986#appendix-B *)
urlrx = RegularExpression["^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"];
(* regular expression for invalid filename characters *)
fnrx = RegularExpression["[\":|\\\\<*>/?]+"];
If[fName === Automatic,
fName = StringReplace[If[$VersionNumber >= 10.,
Last[Lookup[URLParse[url], "Path"]],
Last[StringSplit[First[StringCases[url, urlrx -> "$5"]], {"/", "\\"}]]], fnrx -> "_"]];
fName = FileNameJoin[{$TemporaryDirectory, fName}]; If[TrueQ[$debug], Print[{url, fName}]];
Internal`WithLocalSettings[tmp = Check[If[$VersionNumber >= 9., URLSave, Utilities`URLTools`FetchURL][url, fName], $Failed],
If[TrueQ[$debug], Print[{Round[FileByteCount[fName]/1024., 0.01], IntegerString[FileHash[fName, "MD5"], 16, 32]}]];
If[tmp =!= $Failed, Quiet[processChemicalFile[tmp, type], {MoleculeViewer::fnfnd}], $Failed],
If[tmp =!= $Failed, Quiet[DeleteFile[tmp], General::fdnfnd]]]]
If[$VersionNumber >= 10., (* handling for Entity objects in version 10+ *)
processEntity[ent_Entity] := Module[{res},
If[EntityTypeName[ent] =!= "Chemical", Return[$Failed, Module]];
res = EntityValue[ent, EntityProperty["Chemical", #] & /@ {"VertexTypes", "EdgeRules", "EdgeTypes", "AtomPositions"}];
res = MapAt[(# $conversionFactor) &, res, {4}];
If[validateChem[res], res, $Failed]];
processEntity[__] := $Failed
]
If[$VersionNumber >= 12., (* handling for native Molecule objects in version 12+ *)
processMoleculeObject[mol_Molecule] := Block[{res},
res = MoleculeValue[Molecule[mol, IncludeAromaticBonds -> False, IncludeHydrogens -> True],
{"AtomList", "BondList", "AtomCoordinates"}];
If[! (Head[Last[res]] === StructuredArray && StringMatchQ[Last[res]["Structure"], "QuantityArray"]) ||
! MatrixQ[Last[res]], Return[$Failed, Block]];
res = Replace[res, {Atom[s_] :> s, Bond[i_, t_] :> {Rule @@ i, t}}, {2}];
res = MapAt[QuantityMagnitude[UnitConvert[#, $DefaultLengthUnit]] &, res, {3}];
res = MapAt[Composition[Apply[Sequence], Transpose], res, {2}];
If[validateChem[res], res, $Failed]];
processMoleculeObject[__] := $Failed
]
Options[MakeMOL] = {Method -> Automatic};
MakeMOL[s_String, OptionsPattern[]] := Block[{babQ},
If[! (testOpenBabel || PacletManager`$AllowInternet), Return[$Failed, Block]];
babQ = Switch[System`Utilities`StringName[OptionValue[Method]],
"Automatic", testOpenBabel || (! PacletManager`$AllowInternet),
"OpenBabel", True,
"Beaker" | "ChEMBL", False,
_, Return[$Failed, Block]];
If[babQ, obMakeString[s, "MOL"],
Which[validSMILESQ[s], ChEMBLSMILESToMOL[s],
StringMatchQ[s, inchirx], ChEMBLInChIToMOL[s],
True, $Failed]]]
MakeMOL[mol_List?validateChem, opts___?OptionQ] := Block[{pts = Last[mol], raw},
raw = Which[MatrixQ[pts, QuantityUnits`NumberQuantityQ],
Check[MapAt[QuantityMagnitude[UnitConvert[#, "Picometers"]] &, mol, {4}], Return[$Failed, Block], Quantity::compat],
MatrixQ[pts, NumberQ], MapAt[(#/$conversionFactor) &, mol, {4}],
True, Message[MakeMOL::ncnv]; Return[$Failed, Block]];
ExportString[Thread[{"VertexTypes", "EdgeRules", "EdgeTypes", "VertexCoordinates"} -> raw], {"MOL", "Rules"}]]
MakeMOL[mol_List?validateChem, fn_String, opts___?OptionQ] := Block[{pts = Last[mol], raw},
raw = Which[MatrixQ[pts, QuantityUnits`NumberQuantityQ],
Check[MapAt[QuantityMagnitude[UnitConvert[#, "Picometers"]] &, mol, {4}], Return[$Failed, Block], Quantity::compat],
MatrixQ[pts, NumberQ], MapAt[(#/$conversionFactor) &, mol, {4}],
True, Message[MakeMOL::ncnv]; Return[$Failed, Block]];
Export[fn, Thread[{"VertexTypes", "EdgeRules", "EdgeTypes", "VertexCoordinates"} -> raw], {"MOL", "Rules"}]]
Options[MakeInChIKey] = {Method -> Automatic};
MakeInChIKey[s_String, OptionsPattern[]] := Block[{babQ, res},
If[! (testOpenBabel || PacletManager`$AllowInternet), Return[$Failed, Block]];
If[StringMatchQ[s, inkeyrx], Return[s, Block]];
babQ = Switch[System`Utilities`StringName[OptionValue[Method]],
"Automatic", testOpenBabel || (! PacletManager`$AllowInternet),
"OpenBabel", True,
"Beaker" | "ChEMBL", False,
_, Return[$Failed, Block]];
If[babQ, res = If[validSMILESQ[s] || StringMatchQ[s, inchirx], obMakeString[s, "InChIKey"], obLineNotation[s, "InChIKey"]];
If[StringQ[res], StringTrim[res], res],
ChEMBLMakeInChIKey[s]]]
MakeInChIKey[mol_List?validateChem, opts___] := MakeInChIKey[MakeMOL[mol, opts], opts]
(* OpenBabel interfacing routines *)
testOpenBabel := testOpenBabel = Quiet[Check[Import["!obabel -H", "Text"] =!= "", Message[RunOpenBabel::nobab]; False]]
$OpenBabelVersion := $OpenBabelVersion = Quiet[Check[StringReplace[Import["!obabel -V", "Text"], " -- " -> "\n"], Message[RunOpenBabel::nobab]; $Failed]]
(* defaults for Open Babel methods *)
$obConOpts = {"GeneratedConformers" -> 20, "Method" -> "Genetic"};
$obConGOpts = {"Children" -> Automatic, "Mutability" -> Automatic, "Converge" -> Automatic, "Score" -> Automatic};
$obMinOpts = {"CutOff" -> Automatic, "ForceField" -> "MMFF94s", "MaxIterations" -> 2000, "Newton" -> Automatic, "SteepestDescent" -> Automatic, "Tolerance" -> Automatic, "UpdateNonBondedFrequency" -> 10};
$obForceFields = {"GAFF", "Ghemical", "MMFF94", "MMFF94s", "UFF"};
makeStringRules[expr_List] := Block[{o, s}, Flatten[expr /. (o_ -> s_) :> (System`Utilities`StringName[o] -> s)]]
makeOBSwitches[met_, mopt_List] := Module[{mok, mon, res, tmp},
If[! StringQ[met], Message[RunOpenBabel::bdmtd, met]; Return[$Failed, Module]];
mon = makeStringRules[mopt]; res = {"--" <> ToLowerCase[met]};
Switch[met,
"Generate", res = {},
"Conformer",
mok = FilterRules[Join[mon, $obConOpts], $obConOpts];
AppendTo[res, "--nconf " <> IntegerString[Round["GeneratedConformers" /. mok]]];
tmp = "Method" /. mok;
tmp = If[! ListQ[tmp], System`Utilities`StringName[tmp],
MapAt[System`Utilities`StringName, tmp, {1}]];
Switch[tmp,
"Automatic",
AppendTo[res, "--weighted"],
"Random" | "Systematic" | "Weighted",
AppendTo[res, "--" <> ToLowerCase[tmp]],
"ForceField",
AppendTo[res, "--ff MMFF94s"],
{"ForceField", _Rule},
tmp = makeStringRules[Rest[tmp]];
AppendTo[res, "--ff " <> ("Method" /. tmp /. Automatic | "Automatic" -> "MMFF94s")],
Alternatives @@ $obForceFields,
AppendTo[res, "--ff " <> tmp],
"Genetic" | {"Genetic", __Rule},
If[ListQ[tmp],
tmp = makeStringRules[Rest[tmp]];
tmp = FilterRules[Join[tmp, $obConGOpts], $obConGOpts],
tmp = $obConGOpts];
AppendTo[res, "--score " <> ToLowerCase["Score" /. tmp /. Automatic -> "Energy"]];
tmp = DeleteCases[MapThread[If[MatchQ[#2, Automatic | "Automatic"], "", #1 <> IntegerString[Max[0, Round[#2]]]] &,
{{"--children ", "--mutability ", "--converge "}, {"Children", "Mutability", "Converge"} /. tmp}], ""];
res = Join[res, tmp],
_, Message[RunOpenBabel::nsupm, tmp, "Conformer"]; Return[$Failed, Module]],
"Minimize",
mok = FilterRules[Join[mon, $obMinOpts], $obMinOpts];
tmp = "ForceField" /. mok /. Automatic | "Automatic" -> "MMFF94s";
If[MemberQ[$obForceFields, tmp], AppendTo[res, "--ff " <> tmp],
Message[RunOpenBabel::bdff, tmp]; Return[$Failed, Module]];
tmp = Round["MaxIterations" /. mok];
If[Internal`PositiveIntegerQ[tmp], AppendTo[res, "--steps " <> IntegerString[tmp]],
Message[RunOpenBabel::ioppm, "MaxIterations", tmp]; Return[$Failed, Module]];
tmp = "Tolerance" /. mok /. Automatic -> 1*^-7;
If[NumberQ[tmp] && Positive[tmp], AppendTo[res, "--crit " <> ToString[CForm[tmp], InputForm]],
Message[RunOpenBabel::tol2, tmp]; Return[$Failed, Module]];
tmp = Round["UpdateNonBondedFrequency" /. mok];
If[Internal`PositiveIntegerQ[tmp], AppendTo[res, "--freq " <> IntegerString[tmp]],
Message[RunOpenBabel::ioppm, "UpdateNonBondedFrequency", tmp]; Return[$Failed, Module]];
If[TrueQ["SteepestDescent" /. mok /. Automatic -> False], AppendTo[res, "--sd"]];
If[TrueQ["Newton" /. mok /. Automatic -> False], AppendTo[res, "--newton"]];
If[(tmp = "CutOff" /. mok /. Automatic -> False) =!= False,
Switch[tmp,
True, AppendTo[res, "--cut"],
{_?NumberQ} | {_?NumberQ, _?NumberQ},
res = Join[res, Prepend[MapThread[StringJoin, {{"--rvdw ", "--rele "}, ToString /@ PadRight[tmp, 2, 10]}], "--cut"]],
_, Message[RunOpenBabel::erropts, tmp, "CutOff"]; Return[$Failed, Module]]],
_, Message[RunOpenBabel::bdmtd, met, Automatic]; res = $Failed];
res]
(* format conversion *)
openBabelConvert[fileName_String, Rule[ex_String, out_String], make3D : (True | False) : True, mc_: Automatic, tc_: Automatic, msgQ : (True | False) : True] :=
Module[{ext = ToLowerCase[ex], fmt = ToLowerCase[out], pars = {"-c", "-h"}, args, ec, msg, proc, res},
If[! testOpenBabel, Return[$Failed, Module]];
If[make3D, PrependTo[pars, "--gen3d"], If[MatchQ[fmt, "smiles" | "inchi" | "inchikey"], pars = {}, PrependTo[pars, "--gen2d"]]];
constrainedEvaluate[If[$VersionNumber >= 10.,
args = {"obabel", "-i", ext, fileName, "-o" <> fmt} ~Join~ pars;
proc = Check[RunProcess[args], Return[$Failed, Module]];
res = proc["StandardOutput"]; ec = proc["ExitCode"]; msg = proc["StandardError"];
If[ec == 0 && res =!= "",
If[make3D, Check[molFromString[res], If[msgQ, Echo[StringTrim[msg]]]; $Failed], res],
msg = StringTrim[StringReplace[msg, {"0 molecules converted" -> "", "\r" | "\n" -> " "}]];
If[msgQ,
If[msg =!= "", Echo[msg],
If[ec != 0, Echo["OpenBabel exit code: " <> IntegerString[ec]]]]]; $Failed],
args = StringJoin[Riffle[{"!obabel", "-i", ext, fileName, "-o" <> fmt} ~Join~ pars, " "]];
If[make3D, Check[molFromFile[args], If[msgQ, Print[StringTrim[msg]]]; $Failed], res]], RunOpenBabel,
mc /. Automatic -> 536870912 (* 512 MB *), tc /. Automatic -> 120 (* 2 min. *)]]
openBabelConvert[fileName_String, ex_String, rest___] := openBabelConvert[fileName, ex -> "MOL", rest]
(* generate data from MOL string *)
obConvertMOL[mol_String, out_String, rest___] := Block[{tmp = FileNameJoin[{$TemporaryDirectory, IntegerString[Hash[mol, "MD5"], 16, 32] <> ".mol"}]},
Internal`WithLocalSettings[tmp = Check[Export[tmp, mol, "Text"], $Failed],
If[tmp =!= $Failed, openBabelConvert[tmp, "MOL" -> out, rest], $Failed],
If[tmp =!= $Failed, Quiet[DeleteFile[tmp], General::fdnfnd]]]]
obConvertMOL[mol_List?validateChem, rest___] := obConvertMOL[MakeMOL[mol], rest]
(* generate 3D coordinates from MOL string *)
obMOLTo3D[mol_String, rest___] := obConvertMOL[mol, "MOL", True, rest]
obMOLTo3D[mol_List?validateChem, rest___] := obMOLTo3D[MakeMOL[mol], rest]
(* generate line notation from MOL string *)
obLineNotation[mol_String, type : ("SMILES" | "InChI" | "InChIKey") : "SMILES", rest___] := With[{res = obConvertMOL[mol, type, False, rest]}, If[StringQ[res], StringTrim[res], res]]
obLineNotation[mol_List?validateChem, rest__] := obLineNotation[MakeMOL[mol], rest]
(* generate InChIKey or 2D MOL string from line notation *)
obMakeString[chem_String, type : ("InChIKey" | "MOL") : "InChIKey", mc_: Automatic, tc_: Automatic] := Module[{args, ec, incq, msg, otyp, proc, res, sw},
If[! testOpenBabel, Return[$Failed, Module]];
incq = If[StringMatchQ[chem, inchirx], "-iinchi", Nothing]; otyp = ToLowerCase[type];
sw = If[StringMatchQ[type, "MOL"], {"--gen2d", "-c", "-h"}, {}];
constrainedEvaluate[If[$VersionNumber >= 10.,
args = {"obabel", incq, "-:" <> chem, "-o" <> otyp} ~Join~ sw;
proc = Check[RunProcess[args], Return[$Failed, Module]];
res = proc["StandardOutput"]; ec = proc["ExitCode"]; msg = proc["StandardError"];
If[ec == 0 && res =!= "",
Check[ImportString[res, "Text"], Echo[StringTrim[msg]]; $Failed],
msg = StringTrim[StringReplace[msg, {"0 molecules converted" -> "", "\r" | "\n" -> " "}]];
If[msg =!= "", Echo[msg],
If[ec != 0, Echo["OpenBabel exit code: " <> IntegerString[ec]]]]; $Failed],
args = StringJoin[Riffle[{"!obabel", incq, "-:" <> chem, "-o" <> otyp} ~Join~ sw, " "]];
Check[Import[args, "Text"], Print[StringTrim[msg]]; $Failed]], RunOpenBabel,
mc /. Automatic -> 67108864 (* 64 MB *), tc /. Automatic -> 30 (* 30 sec. *)]]
Options[RunOpenBabel] = {MemoryConstraint -> Automatic, Method -> Automatic, ProcessDirectory -> Inherited,
ProcessEnvironment -> Inherited, RunProcess -> Automatic, TimeConstraint -> Automatic, Verbose -> True};
RunOpenBabel[mol_List?validateChem, opts : OptionsPattern[]] := obMOLTo3D[MakeMOL[mol], OptionValue[MemoryConstraint], OptionValue[TimeConstraint], OptionValue[Verbose]]
RunOpenBabel[list : {__String}, opts___] := RunOpenBabel[#, opts] & /@ list
RunOpenBabel[file_String /; Quiet[FindFile[file] =!= $Failed], opts : OptionsPattern[]] :=
With[{fn = FindFile[file]}, openBabelConvert[fn, FileExtension[fn], True, OptionValue[MemoryConstraint], OptionValue[TimeConstraint], OptionValue[Verbose]]]
RunOpenBabel[chem_String, opts : OptionsPattern[]] := Module[{args, autoSet, ec, incq, met, mopt, msg, opo, pars, proc, res},
If[! testOpenBabel, Return[$Failed, Module]];
autoSet = {"Minimize", {"ForceField" -> "MMFF94s", "MaxIterations" -> 2000, "Tolerance" -> 1.*^-7}};
met = OptionValue[Method];
If[ListQ[met],
{met, mopt} = {First[met], Flatten[Rest[met]]},
mopt = {}];
met = System`Utilities`StringName[met];
If[met === "Automatic", {met, mopt} = autoSet];
pars = makeOBSwitches[met, mopt];
If[pars === $Failed, pars = makeOBSwitches @@ autoSet];
incq = If[StringMatchQ[chem, inchirx], "-iinchi", Nothing];
constrainedEvaluate[If[TrueQ[OptionValue[RunProcess] /. Automatic -> True] && $VersionNumber >= 10.,
args = {"obabel", incq, "-:"<> chem, "-omol", "--gen3d", "-c", "-h"} ~Join~ pars;
If[TrueQ[$debug], Print[Defer[RunProcess][args]]];
proc = Check[RunProcess[args, FilterRules[Join[{opts}, Options[RunOpenBabel]], Options[RunProcess]]],
Return[$Failed, Module]];
res = proc["StandardOutput"]; ec = proc["ExitCode"]; msg = proc["StandardError"];
If[ec == 0 && res =!= "",
opo = StringPosition[res, "OpenBabel"];
If[opo =!= {},
res = molFromString[StringDrop[res, opo[[1, 1]] - 3]];
If[validateChem[res], res, $Failed],
$Failed],
If[TrueQ[OptionValue[Verbose] /. Automatic -> True],
msg = StringTrim[StringReplace[msg, {"0 molecules converted" -> "", "\r" | "\n" -> " "}]];
If[msg =!= "", Echo[msg],
If[ec != 0, Echo["OpenBabel exit code: " <> IntegerString[ec]]]]]; $Failed],
args = StringJoin[Riffle[{"!obabel", incq, "-:" <> chem, "-omol", "--gen3d", "-c", "-h"} ~Join~ pars, " "]];
If[TrueQ[$debug], Print[Defer[Import][args, "Text"]]];
res = Check[Import[args, "Text"], $Failed];
If[res =!= $Failed,
opo = StringPosition[res, "OpenBabel"];
If[opo =!= {},
res = molFromString[StringDrop[res, opo[[1, 1]] - 3]];
If[validateChem[res], res, $Failed],
$Failed],
$Failed]], RunOpenBabel,
OptionValue[MemoryConstraint] /. Automatic -> 536870912 (* 512 MB *),
OptionValue[TimeConstraint] /. Automatic -> 120 (* 2 min. *)]]
(* Imago OCR interfacing routines *)
testImago := testImago = Quiet[Check[Import["!imago_console", "Text"] =!= "", Message[RunImago::noimg]; False]]
Options[RunImago] = {ImageResolution -> Automatic, ImageSize -> Automatic, MemoryConstraint -> Automatic, ProcessDirectory -> Inherited,
ProcessEnvironment -> Inherited, RasterSize -> Automatic, RunProcess -> Automatic, TimeConstraint -> Automatic, Verbose -> Automatic};
RunImago[x_, opts___] := RunImago[Rasterize[x, "Image", FilterRules[Join[{ColorSpace -> "Grayscale", opts}, Options[RunImago]], Options[Rasterize]]], opts];
RunImago[img_Image, opts : OptionsPattern[{RunImago, Rasterize}]] := Module[{fn, fnIn, fnOut, msg, proc},
If[! testImago, Return[$Failed]];
fn = IntegerString[Hash[img, "MD5"], 16, 32];
fnIn = FileNameJoin[{$TemporaryDirectory, fn <> ".png"}];
fnOut = FileNameJoin[{$TemporaryDirectory, fn <> ".mol"}];
Internal`WithLocalSettings[Export[fnIn, If[ImageColorSpace[img] =!= "Grayscale", ColorConvert[img, "Grayscale"], img], "PNG"],
constrainedEvaluate[If[TrueQ[OptionValue[RunProcess] /. Automatic -> True] && $VersionNumber >= 10.,
proc = Check[RunProcess[{"imago_console", "-images", "-o", fnOut, fnIn},
FilterRules[Join[{opts}, Options[RunImago]], Options[RunProcess]]],
Return[$Failed, Module]];
If[proc["ExitCode"] == 0, Check[Import[fnOut, "Text"], $Failed],
If[TrueQ[OptionValue[Verbose] /. Automatic -> True],
If[(msg = proc["StandardError"]) =!= "", Echo[msg],
Echo[ToString[proc["StandardOutput"]] <> "\n" <>
"Imago exit code: " <> IntegerString[proc["ExitCode"]]]]];
$Failed],
proc = Check[Run["imago_console -images -o", fnOut, fnIn], Return[$Failed, Module]];
If[proc == 0, Check[Import[fnOut, "Text"], $Failed], $Failed]], RunImago,
OptionValue[MemoryConstraint] /. Automatic -> 536870912 (* 512 MB *),
OptionValue[TimeConstraint] /. Automatic -> 120 (* 2 min. *)],
Quiet[DeleteFile[{fnIn, fnOut}], General::fdnfnd]]]
(* CACTUS *)
SetAttributes[GetCACTUS, Listable];
GetCACTUS[arg_String] := Module[{in, url},
If[$VersionNumber < 9., Message[GetCACTUS::unavail, GetCACTUS]; Return[$Failed, Module]];
url = "https://cactus.nci.nih.gov/chemical/structure/``/file?format=sdf&get3d=true";
in = If[StringMatchQ[arg, inchirx], arg, percentEncode[arg]];
If[TrueQ[$debug], Print[Defer[Import][ToString[StringForm[url, in]], "MOL"]]];
molFromFile[If[$VersionNumber >= 10., StringTemplate[url] @ in, ToString[StringForm[url, in]]]]]
SetAttributes[GetChemicalData, Listable];
Options[GetChemicalData] = {"MaxResults" -> 1};
GetChemicalData[str_String, out : (Automatic | "SMILES" | "InChI") : Automatic, OptionsPattern[]] := Module[{chk, name, res, tmp},
name = StringJoin[StringReplacePart[#, ToUpperCase[StringTake[#, 1]], {1, 1}] & /@ StringSplit[str, " " | "-"]];
If[TrueQ[$debug], Print[Defer[ChemicalData][name]]];
If[! StringFreeQ[name, "*"],
chk = Table[ChemicalData[c, "StandardName"], {c, ChemicalData[name]}];
If[chk === {}, Return[$Failed, Module]],
If[(chk = ChemicalData[name, "StandardName"]) === $Failed, Return[chk, Module]]];
chk = Take[Flatten[{chk}], Max[1, Round[OptionValue["MaxResults"] /. All -> Infinity]] /. Infinity -> All];
If[out === Automatic,
res = Table[ChemicalData[c, prop], {c, chk}, {prop, {"VertexTypes", "EdgeRules", "EdgeTypes", "AtomPositions"}}];
res = If[$VersionNumber >= 9.,
MapAt[If[FreeQ[#, _Missing], QuantityMagnitude[UnitConvert[#, $DefaultLengthUnit]], #] &, res, {All, -1}],
Function[r, MapAt[If[FreeQ[#, _Missing], # $conversionFactor, #] &, r, -1]] /@ res];
res = Replace[res, x_ /; ! validateChem[x] :> $Failed, {1}],
res = Table[If[out === "SMILES",
tmp = Cases[ChemicalData[c, #] & /@ {"IsomericSMILES", "SMILES"}, _String];
If[Length[tmp] > 0, First[tmp], $Failed],
ChemicalData[c, out] /. Except[_String] -> $Failed], {c, chk}]];
If[Length[res] == 1, First[res], res]]
(* **ADVANCED USERS**:
You can remove the code sandwiched by the row of dashes below and
permanently assign your API token to $ChemSpiderAPIToken instead
by editing this package file and uncommenting the line below:
$ChemSpiderAPIToken = ;
*)
(* ---------------- *)
$dir := DirectoryName[$InputFileName];
$ChemSpiderAPIToken := $ChemSpiderAPIToken = loadToken["RESTful"];
reloadToken["RESTful"] := ($ChemSpiderAPIToken = loadToken["RESTful"]);
loadToken[type_] := Block[{key = FileNameJoin[{$dir, "apikey-restful"}], res},
If[FileExistsQ[key], Uncompress[Get[key]],
res = DialogInput[DynamicModule[{api},
Column[{Style["Please enter your ChemSpider API key:", Bold, 16],
InputField[Dynamic[api, (api = #) &], String, FieldSize -> 25],
Item[Row[{DefaultButton[DialogReturn[api]], CancelButton[DialogReturn[$Failed]]}],
Alignment -> Right]}, Left]]];
If[StringQ[res], Put[Compress[res], key]; res, $Failed]]]
(* ---------------- *)
Options[GetChemSpider] = {"MaxResults" -> 1, Method -> Automatic};
GetChemSpider[arg_, out : (Automatic | "SMILES" | "InChI") : Automatic, OptionsPattern[]] := Block[{met, n},
If[$VersionNumber < 9., Message[GetChemSpider::unavail, GetChemSpider]; Return[$Failed, Block]];
met = OptionValue[Method];
If[met === Automatic, met = "RESTful",
met = met /. {"Legacy" -> "SOAP", _ -> "RESTful"}];
n = Round[OptionValue["MaxResults"]];
Switch[met,
"RESTful", gCSRESTful[arg, out, "MaxResults" -> n],
"SOAP", Message[MoleculeViewer::obsmet]; $Failed, (* for future removal *)
_, $Failed]]
SetAttributes[csconv, Listable];
csconv[str_String, in_String, out_String] := Block[{p, q, r, url},
url = "https://api.rsc.org/compounds/v1/tools/convert";
p = {"Method" -> "POST", "Headers" -> {"apikey" -> $ChemSpiderAPIToken, "Content-Type" -> "application/json"},
"Body" -> ExportString[{"input" -> str, "inputFormat" -> in, "outputFormat" -> out}, "JSON"]};
If[$VersionNumber >= 11.,
q = HTTPRequest[url, Association[p]];
If[TrueQ[$debug], Print[Defer[URLExecute][InputForm[q], "JSON"]]];
r = URLExecute[q, "JSON"],
If[TrueQ[$debug], Print[Defer[URLFetch][url, p]]];
r = ImportString[URLFetch[url, p], "JSON"]];
If[r =!= $Failed && Head[r] =!= Failure, r = "output" /. r;
If[r =!= "output", r, Message[GetChemSpider::noconv, in, out]; $Failed], Message[GetChemSpider::noconv, in, out]; $Failed]]
gCSRESTful[csid_Integer?Positive, out : (Automatic | "SMILES" | "InChI") : Automatic, opts___] := Module[{pars, req, rsp, type, url},
If[! ValueQ[$ChemSpiderAPIToken] || ! StringQ[$ChemSpiderAPIToken],
Message[GetChemSpider::token]; Return[$Failed, Module]];
url = "https://api.rsc.org/compounds/v1/records/" <> IntegerString[csid] <> "/details";
type = If[out === Automatic, "mol3D", "smiles"];
pars = {"Method" -> "GET", "Headers" -> {"apikey" -> $ChemSpiderAPIToken, "Content-Type" -> "application/json"}};
If[$VersionNumber >= 11.,
AppendTo[pars, "Query" -> {"fields" -> type}];
req = HTTPRequest[url, Association[pars]];
If[TrueQ[$debug], Print[Defer[URLExecute][InputForm[req], "JSON"]]];
rsp = URLExecute[req, "JSON"],
AppendTo[pars, "Parameters" -> {"fields" -> type}];
If[TrueQ[$debug], Print[Defer[URLFetch][url, pars]]];
rsp = ImportString[URLFetch[url, pars], "JSON"]];
If[rsp =!= $Failed && Head[rsp] =!= Failure, rsp = type /. rsp;
If[! StringMatchQ[rsp, type],
Which[out === Automatic, molFromString[rsp],
out === "InChI", csconv[rsp, "SMILES", "InChI"],
True, rsp],
$Failed], $Failed]]
gCSRESTful[csidList_List /; VectorQ[csidList, Composition[Through, IntegerQ && Positive]], out : (Automatic | "SMILES" | "InChI") : Automatic, opts___] :=
Module[{cnv, pars, req, rsp, type, url},
If[! ValueQ[$ChemSpiderAPIToken] || ! StringQ[$ChemSpiderAPIToken],
Message[GetChemSpider::token]; Return[$Failed, Module]];
url = "https://api.rsc.org/compounds/v1/records/batch";
type = If[out === Automatic, "mol3D", "smiles"];
pars = {"Method" -> "POST", "Headers" -> {"apikey" -> $ChemSpiderAPIToken, "Content-Type" -> "application/json"},
"Body" -> ExportString[{"recordIds" -> csidList, "fields" -> {type}}, "JSON"]};
If[$VersionNumber >= 11.,
req = HTTPRequest[url, Association[pars]];