1 #!/bin/env python
2 # File: MiscUtil.py
3 # Author: Manish Sud <msud@san.rr.com>
4 #
5 # Copyright (C) 2020 Manish Sud. All rights reserved.
6 #
7 # This file is part of MayaChemTools.
8 #
9 # MayaChemTools is free software; you can redistribute it and/or modify it under
10 # the terms of the GNU Lesser General Public License as published by the Free
11 # Software Foundation; either version 3 of the License, or (at your option) any
12 # later version.
13 #
14 # MayaChemTools is distributed in the hope that it will be useful, but without
15 # any warranty; without even the implied warranty of merchantability of fitness
16 # for a particular purpose. See the GNU Lesser General Public License for more
17 # details.
18 #
19 # You should have received a copy of the GNU Lesser General Public License
20 # along with MayaChemTools; if not, see <http://www.gnu.org/licenses/> or
21 # write to the Free Software Foundation Inc., 59 Temple Place, Suite 330,
22 # Boston, MA, 02111-1307, USA.
23 #
24
25 from __future__ import print_function
26
27 import os
28 import sys
29 import time
30 import re
31 import csv
32 import textwrap
33 import glob
34 import base64
35 import pickle
36 import multiprocessing as mp
37
38 __all__ = ["CheckFileExt", "CheckTextValue", "DoesSMILESFileContainTitleLine", "ExpandFileNames", "GetExamplesTextFromDocOptText", "GetExcelStyleColumnLabel", "GetMayaChemToolsLibDataPath", "GetTextLines", "GetTextLinesWords", "GetWallClockAndProcessorTime", "GetFormattedElapsedTime", "GetFormattedFileSize", "IsEmpty", "IsFloat", "IsInteger", "IsNumber", "JoinWords", "ObjectFromBase64EncodedString", "ObjectToBase64EncodedString", "ParseFileName", "PrintError", "PrintInfo", "PrintWarning", "ProcessOptionInfileParameters", "ProcessOptionMultiprocessingParameters", "ProcessOptionOutfileParameters", "ProcessOptionSeabornPlotParameters", "ReplaceHTMLEntitiesInText", "ValidateOptionsDistinctFileNames", "ValidateOptionFileExt", "ValidateOptionFilePath", "ValidateOptionFloatValue", "ValidateOptionIntegerValue", "ValidateOptionNumberValue", "ValidateOptionNumberValues", "ValidateOptionsOutputFileOverwrite", "ValidateOptionTextValue", "TruncateText", "WrapText"]
39
40 def CheckFileExt(FileName, FileExts):
41 """Check file type based on the specified file extensions delimited by spaces.
42
43 Arguments:
44 FileName (str): Name of a file.
45 FileExts (str): Space delimited string containing valid file extensions.
46
47 Returns:
48 bool : True, FileName contains a valid file extension; Otherwise, False.
49
50 """
51
52 for FileExt in FileExts.split():
53 if re.search(r"\.%s$" % FileExt, FileName, re.IGNORECASE):
54 return True
55
56 return False
57
58 def CheckTextValue(Value, ValidValues):
59 """Check text value based on the specified valid values delimited by spaces.
60
61 Arguments:
62 Value (str): Text value
63 ValidValues (str): Space delimited string containing valid values.
64
65 Returns:
66 bool : True, Value is valid; Otherwise, False.
67
68 """
69
70 ValidValues = re.sub(' ', '|', ValidValues)
71 if re.match("^(%s)$" % ValidValues, Value, re.IGNORECASE):
72 return True
73
74 return False
75
76 def GetTextLinesWords(TextFilePath, Delimiter, QuoteChar, IgnoreHeaderLine):
77 """Parse lines in the specified text file into words in a line and return a list containing
78 list of parsed line words.
79
80 Arguments:
81 TextFilePath (str): Text file name including file path.
82 Delimiter (str): Delimiter for parsing text lines.
83 QuoteChar (str): Quote character for line words.
84 IgnoreHeaderLine (bool): A flag indicating whether to ignore first
85 valid data line corresponding to header line.
86
87 Returns:
88 list : A list of lists containing parsed words for lines.
89
90 Notes:
91 The lines starting with # or // are considered comment lines and are
92 ignored during parsing along with any empty lines.
93
94 """
95 if not os.path.exists(TextFilePath):
96 PrintError("The text file file, %s, doesn't exist.\n" % (TextFilePath))
97
98 TextFile = open(TextFilePath, "r")
99 if TextFile is None:
100 PrintError("Couldn't open text file: %s.\n" % (TextFilePath))
101
102 # Collect text lines...
103 TextLines = []
104 FirstValidLine = True
105 for Line in TextFile:
106 Line = Line.rstrip()
107
108 # Ignore empty lines...
109 if not len(Line):
110 continue
111
112 # Ignore comments...
113 if re.match("^(#|\/\/)", Line, re.I):
114 continue
115
116 # Ignore header line...
117 if FirstValidLine:
118 FirstValidLine = False
119 if IgnoreHeaderLine:
120 continue
121
122 TextLines.append(Line)
123
124 TextFile.close()
125
126 # Parse text lines...
127 TextLinesWords = []
128
129 TextLinesReader = csv.reader(TextLines, delimiter = Delimiter, quotechar = QuoteChar)
130 for LineWords in TextLinesReader:
131 TextLinesWords.append(LineWords)
132
133 return TextLinesWords
134
135 def GetTextLines(TextFilePath):
136 """Read text lines from input file, remove new line characters and return a list containing
137 stripped lines.
138
139 Arguments:
140 TextFilePath (str): Text file name including file path.
141
142 Returns:
143 list : A list lines.
144
145 """
146 TextFile = open(TextFilePath, "r")
147 if TextFile is None:
148 PrintError("Couldn't open text file: %s.\n" % (TextFilePath))
149
150 # Collect text lines...
151 TextLines = [Line.rstrip() for Line in TextFile]
152
153 TextFile.close()
154
155 return TextLines
156
157 def DoesSMILESFileContainTitleLine(FileName):
158 """Determine whether the SMILES file contain a title line based on the presence
159 of a string SMILES, Name or ID in the first line.
160
161 Arguments:
162 FileName (str): Name of a file.
163
164 Returns:
165 bool : True, File contains title line; Otherwise, False.
166
167 """
168
169 Infile = open(FileName, "r")
170 if Infile is None:
171 return False
172
173 Line = Infile.readline()
174 Infile.close()
175
176 if re.search("(SMILES|Name|ID)", Line, re.I):
177 return True
178
179 return False
180
181 def ExpandFileNames(FilesSpec, Delimiter = ","):
182 """Expand files specification using glob module to process any * or ? wild
183 cards in file names and return a list of expanded file names.
184
185 Arguments:
186 FilesSpec (str): Files specifications
187 Delimiter (str): Delimiter for file specifications
188
189 Returns:
190 list : List of expanded file names
191
192 """
193 FileNames = []
194 if not len(FilesSpec):
195 return FileNames
196
197 for FileSpec in FilesSpec.split(Delimiter):
198 FileSpec = FileSpec.strip()
199 if re.search("(\*|\?)", FileSpec, re.I):
200 FileNames.extend(glob.glob(FileSpec))
201 else:
202 FileNames.append(FileSpec)
203
204 return FileNames
205
206 def GetExamplesTextFromDocOptText(DocOptText):
207 """Get script usage example lines from a docopt doc string. The example text
208 line start from a line containing `Examples:` keyword at the beginning of the line.
209
210 Arguments:
211 DocOptText (str): Doc string containing script usage examples lines starting with
212 a line marked by `Examples:` keyword at the beginning of a line.
213
214 Returns:
215 str : A string containing text lines retrieved from the examples section of
216 DocOptText parameter.
217
218 """
219
220 ExamplesStart = re.compile("^Examples:", re.IGNORECASE)
221 ExamplesEnd = re.compile("^(Author:|See also:|Copyright:)", re.IGNORECASE)
222
223 ExamplesText = 'Examples text is not available';
224 ExamplesTextFound = False
225
226 for Line in DocOptText.splitlines():
227 if ExamplesStart.match(Line):
228 ExamplesText = 'Examples:';
229 ExamplesTextFound = True
230 continue
231
232 if ExamplesEnd.match(Line):
233 break
234
235 if ExamplesTextFound:
236 ExamplesText += "\n" + Line;
237
238 return ExamplesText
239
240 def GetExcelStyleColumnLabel(ColNum):
241 """Return Excel style column label for a colum number.
242
243 Arguments:
244 ColNum (int): Column number
245
246 Returns:
247 str : Excel style column label.
248
249 """
250 Letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
251
252 ColLabelList = []
253 while ColNum:
254 ColNum, SubColNum = divmod(ColNum - 1, 26)
255 ColLabelList[:0] = Letters[SubColNum]
256
257 return ''.join(ColLabelList)
258
259 def GetWallClockAndProcessorTime():
260 """Get wallclock and processor times in seconds.
261
262 Returns:
263 float : Wallclock time.
264 float : Processor time.
265
266 """
267 return (time.time(), _GetProcessorTime())
268
269 def _GetProcessorTime():
270 """Get processor time """
271
272 if sys.version_info[0] >= 3 and sys.version_info[1] >= 3:
273 ProcessorTime = time.process_time()
274 else:
275 ProcessorTime = time.clock()
276
277 return ProcessorTime
278
279 def GetMayaChemToolsLibDataPath():
280 """Get location of MayaChemTools lib data directory.
281
282 Returns:
283 str : Location of MayaChemTools lib data directory.
284
285 Notes:
286 The location of MayaChemTools lib data directory is determined relative to
287 MayaChemTools python lib directory name available through sys.path.
288
289 """
290 MayaChemToolsDataPath = ""
291
292 for PathEntry in sys.path:
293 if re.search("MayaChemTools", PathEntry, re.I) and re.search("Python", PathEntry, re.I):
294 MayaChemToolsDataPath = os.path.join( PathEntry, "..", "data")
295 break
296 else:
297 PrintInfo("PathEntry didn't match")
298
299 if not len(MayaChemToolsDataPath):
300 PrintWarning("MayaChemTools lib directory location doesn't appear to exist in system search path specified by sys.path...")
301
302 return MayaChemToolsDataPath
303
304 def GetFormattedElapsedTime(StartingWallClockTime, StartingProcessorTime):
305 """Get elapsed wallclock and processor times as a string in the following
306 format: %d wallclock secs ( %.2f process secs).
307
308 Arguments:
309 StartingWallClockTime (float): Starting wallclock time in seconds.
310 StartingProcessorTime (float): Starting processor time in seconds.
311
312 Returns:
313 str : Elapsed time formatted as: %d wallclock secs ( %.2f process secs)
314
315 """
316
317 ElapsedWallClockTime = time.time() - StartingWallClockTime
318 ElapsedProcessorTime = _GetProcessorTime() - StartingProcessorTime
319
320 ElapsedTime = "%d wallclock secs ( %.2f process secs)" % (ElapsedWallClockTime, ElapsedProcessorTime)
321
322 return ElapsedTime
323
324 def GetFormattedFileSize(FileName, Precision = 1):
325 """Get file size as a string in the following format: %.*f <bytes, KB, MB,
326 GB>
327
328 Arguments:
329 FileName (str): File path.
330 Precision (int): File size precision.
331
332 Returns:
333 str : File size formatted as: %.2f <bytes, KB, MB, GB>
334
335 """
336
337 Size = os.path.getsize(FileName)
338
339 if Size < 1024:
340 SizeDenominator = 1
341 SizeSuffix = "bytes"
342 elif Size < (1024*1024):
343 SizeDenominator = 1024
344 SizeSuffix = "KB"
345 elif Size < (1024*1024*1024):
346 SizeDenominator = 1024*1024
347 SizeSuffix = "MB"
348 elif Size < (1024*1024*1024*1024):
349 SizeDenominator = 1024*1024*1024
350 SizeSuffix = "GB"
351 else:
352 SizeDenominator = 1
353 SizeSuffix = "bytes"
354
355 Size /= SizeDenominator
356
357 FormattedSize = "%.*f %s" % (Precision, Size, SizeSuffix)
358
359 return FormattedSize
360
361 def IsEmpty(Value):
362 """Determine whether the specified value is empty after converting
363 it in to a string and removing all leading and trailing white spaces. A value
364 of type None is considered empty.
365
366 Arguments:
367 Value (str, int or float): Text or a value
368
369 Returns:
370 bool : True, Text string is empty; Otherwsie, False.
371
372 """
373
374 if Value is None:
375 return True
376
377 TextValue = "%s" % Value
378 TextValue = TextValue.strip()
379
380 return False if len(TextValue) else True
381
382 def IsFloat(Value):
383 """Determine whether the specified value is a float by converting it
384 into a float.
385
386 Arguments:
387 Value (str, int or float): Text
388
389 Returns:
390 bool : True, Value is a float; Otherwsie, False.
391
392 """
393
394 return IsNumber(Value)
395
396 def IsInteger(Value):
397 """Determine whether the specified value is an integer by converting it
398 into an int.
399
400 Arguments:
401 Value (str, int or float): Text
402
403 Returns:
404 bool : True, Value is an integer; Otherwsie, False.
405
406 """
407
408 Status = True
409
410 if Value is None:
411 return False
412
413 try:
414 Value = int(Value)
415 Status = True
416 except ValueError:
417 Status = False
418
419 return Status
420
421 def IsNumber(Value):
422 """Determine whether the specified value is a number by converting it
423 into a float.
424
425 Arguments:
426 Value (str, int or float): Text
427
428 Returns:
429 bool : True, Value is a number; Otherwsie, False.
430
431 """
432
433 Status = True
434
435 if Value is None:
436 return Status
437
438 try:
439 Value = float(Value)
440 Status = True
441 except ValueError:
442 Status = False
443
444 return Status
445
446 def JoinWords(Words, Delimiter, Quote = False):
447 """Join words in a list using specified delimiter with optional quotes around words.
448
449 Arguments:
450 Words (list): List containing words to join.
451 Delimiter (string): Delimiter for joining words.
452 Quote (boolean): Put quotes around words.
453
454 Returns:
455 str : String containing joined words.
456
457 """
458
459 if Quote:
460 JoinedWords = Delimiter.join('"{0}"'.format(Word) for Word in Words)
461 else:
462 JoinedWords = Delimiter.join(Words)
463
464 return JoinedWords
465
466 def ObjectToBase64EncodedString(Object):
467 """Encode Python object into base64 encoded string. The object is
468 pickled before encoding.
469
470 Arguments:
471 object: Python object.
472
473 Returns:
474 str : Base64 encode object string or None.
475
476 """
477
478 return None if Object is None else base64.b64encode(pickle.dumps(Object)).decode()
479
480 def ObjectFromBase64EncodedString(EncodedObject):
481 """Generate Python object from a bas64 encoded and pickled
482 object string.
483
484 Arguments:
485 str: Base64 encoded and pickled object string.
486
487 Returns:
488 object : Python object or None.
489
490 """
491
492 return None if EncodedObject is None else pickle.loads(base64.b64decode(EncodedObject))
493
494 def ParseFileName(FilePath):
495 """Parse specified file path and return file dir, file name, and file extension.
496
497 Arguments:
498 FilePath (str): Name of a file with complete file path.
499
500 Returns:
501 str : File directory.
502 str : File name without file extension.
503 str : File extension.
504
505 """
506 FileDir, FileBaseName = os.path.split(FilePath)
507 FileName, FileExt = os.path.splitext(FileBaseName)
508
509 if re.match("^\.", FileExt):
510 FileExt = re.sub("^\.", "", FileExt)
511
512 return (FileDir, FileName, FileExt)
513
514 def PrintError(Msg, Status=1):
515 """Print message to stderr along with flushing stderr and exit with a specified
516 status. An `Error` prefix is placed before the message.
517
518 Arguments:
519 Msg (str): Text message.
520 Status (int): Exit status.
521
522 """
523
524 PrintInfo("Error: %s" % Msg)
525 sys.exit(Status)
526
527 def PrintInfo(Msg=''):
528 """Print message to stderr along with flushing stderr.
529
530 Arguments:
531 Msg (str): Text message.
532
533 """
534
535 print(Msg, sep=' ', end='\n', file=sys.stderr)
536 sys.stderr.flush()
537
538 def PrintWarning(msg):
539 """Print message to stderr along with flushing stderr. An `Warning` prefix
540 is placed before the message.
541
542 Arguments:
543 Msg (str): Text message.
544
545 """
546
547 PrintInfo("Warning: %s" % msg)
548
549 def ValidateOptionFileExt(OptionName, FileName, FileExts):
550 """Validate file type based on the specified file extensions delimited by spaces.
551
552 Arguments:
553 OptionName (str): Command line option name.
554 FileName (str): Name of a file.
555 FileExts (str): Space delimited string containing valid file extensions.
556
557 Notes:
558 The function exits with an error message for a file name containing
559 invalid file extension.
560
561 """
562
563 if not CheckFileExt(FileName, FileExts):
564 PrintError("The file name specified , %s, for option \"%s\" is not valid. Supported file formats: %s\n" % (FileName, OptionName, FileExts))
565
566 def ValidateOptionFilePath(OptionName, FilePath):
567 """Validate presence of the file.
568
569 Arguments:
570 OptionName (str): Command line option name.
571 FilePath (str): Name of a file with complete path.
572
573 Notes:
574 The function exits with an error message for a file path that doesn't exist.
575
576 """
577
578 if not os.path.exists(FilePath):
579 PrintError("The file specified, %s, for option \"%s\" doesn't exist.\n" % (FilePath, OptionName))
580
581 def ValidateOptionFloatValue(OptionName, OptionValue, CmpOpValueMap):
582 """Validate option value using comparison operater and value pairs in specified in
583 a map.
584
585 Arguments:
586 OptionName (str): Command line option name.
587 OptionValue (float or str): Command line option value.
588 CmpOpValueMap (dictionary): Comparison operator key and value pairs to
589 validate values specified in OptionValue.
590
591 Notes:
592 The function exits with an error message for an invalid option values specified
593 in OptionValue.
594
595 Examples:
596
597 ValidateOptionNumberValue("-b, --butinaSimilarityCutoff",
598 Options["--butinaSimilarityCutoff"],
599 {">": 0.0, "<=" : 1.0})
600
601 """
602
603 if not IsFloat(OptionValue):
604 PrintError("The value specified, %s, for option \"%s\" must be a float." % (OptionValue, OptionName))
605
606 return ValidateOptionNumberValue(OptionName, float(OptionValue), CmpOpValueMap)
607
608 def ValidateOptionIntegerValue(OptionName, OptionValue, CmpOpValueMap):
609 """Validate option value using comparison operater and value pairs in specified in
610 a map.
611
612 Arguments:
613 OptionName (str): Command line option name.
614 OptionValue (int or str): Command line option value.
615 CmpOpValueMap (dictionary): Comparison operator key and value pairs to
616 validate values specified in OptionValue.
617
618 Notes:
619 The function exits with an error message for an invalid option values specified
620 in OptionValue.
621
622 Examples:
623
624 ValidateOptionIntegerValue("--maxConfs", Options["--maxConfs"],
625 {">": 0})
626
627 """
628
629 if not IsInteger(OptionValue):
630 PrintError("The value specified, %s, for option \"%s\" must be an integer." % (OptionValue, OptionName))
631
632 return ValidateOptionNumberValue(OptionName, int(OptionValue), CmpOpValueMap)
633
634 def ValidateOptionNumberValue(OptionName, OptionValue, CmpOpValueMap):
635 """Validate option value using comparison operater and value pairs in specified in
636 a map.
637
638 Arguments:
639 OptionName (str): Command line option name.
640 OptionValue (int or float): Command line option value.
641 CmpOpValueMap (dictionary): Comparison operator key and value pairs to
642 validate values specified in OptionValue.
643
644 Notes:
645 The function exits with an error message for an invalid option values specified
646 in OptionValue.
647
648 Examples:
649
650 ValidateOptionNumberValue("--maxConfs", int(Options["--maxConfs"]),
651 {">": 0})
652 ValidateOptionNumberValue("-b, --butinaSimilarityCutoff",
653 float(Options["--butinaSimilarityCutoff"]),
654 {">": 0.0, "<=" : 1.0})
655
656 """
657
658 Status = True
659 for CmpOp in CmpOpValueMap:
660 Value = CmpOpValueMap[CmpOp]
661 if re.match("^>$", CmpOp, re.I):
662 if OptionValue <= Value:
663 Status = False
664 break
665 elif re.match("^>=$", CmpOp, re.I):
666 if OptionValue < Value:
667 Status = False
668 break
669 elif re.match("^<$", CmpOp, re.I):
670 if OptionValue >= Value:
671 Status = False
672 break
673 elif re.match("^<=$", CmpOp, re.I):
674 if OptionValue > Value:
675 Status = False
676 break
677 else:
678 PrintError("The specified comparison operator, %s, for function MiscUtil.ValidateOptionNumberValue is not supported\n" % (CmpOp))
679
680 if not Status:
681 FirstValue = True
682 SupportedValues = ""
683 for CmpOp in CmpOpValueMap:
684 Value = CmpOpValueMap[CmpOp]
685 if FirstValue:
686 FirstValue = False
687 SupportedValues = "%s %s" % (CmpOp, Value)
688 else:
689 SupportedValues = "%s and %s %s" % (SupportedValues, CmpOp, Value)
690
691 PrintError("The value specified, %s, for option \"%s\" is not valid. Supported value(s): %s " % (OptionValue, OptionName, SupportedValues))
692
693 def ValidateOptionNumberValues(OptionName, OptionValueString, OptionValueCount, OptionValueDelimiter, OptionValueType, CmpOpValueMap):
694 """Validate numerical option values using option value string, delimiter, value type,
695 and a specified map containing comparison operator and value pairs.
696
697 Arguments:
698 OptionName (str): Command line option name.
699 OptionValueString (str): Command line option value.
700 OptionValueCount (int): Number of values in OptionValueString.
701 OptionValueDelimiter (str): Delimiter used for values in OptionValueString.
702 OptionValueType (str): Valid number types (integer or float)
703 CmpOpValueMap (dictionary): Comparison operator key and value pairs to
704 validate values specified in OptionValueString.
705
706 Notes:
707 The function exits with an error message for invalid option values specified
708 in OptionValueString
709
710 Examples:
711
712 ValidateOptionNumberValues("-m, --molImageSize",
713 Options["--molImageSize"], 2, ",", "integer", {">": 0})
714
715 """
716 if not CheckTextValue(OptionValueType, "integer float"):
717 PrintError("The option value type specified, %s, for function MiscUtil.ValidateOptionNumberValues is not valid. Supported value: integer float " % (OptionValueType))
718
719 Values = OptionValueString.split(OptionValueDelimiter)
720 if len(Values) != OptionValueCount:
721 PrintError("The value specified, %s, for option \"%s\" is not valid. It must contain %d %s values separated by \"%s\"" % (OptionValueString, OptionName, OptionValueCount, OptionValueType, OptionValueDelimiter))
722
723 IsIntergerValue = True
724 if re.match("^float$", OptionValueType, re.I):
725 IsIntergerValue = False
726
727 for Value in Values:
728 if IsIntergerValue:
729 if not IsInteger(Value):
730 PrintError("The value specified, %s, for option \"%s\" in string \"%s\" must be an integer." % (Value, OptionName, OptionValueString))
731 Value = int(Value)
732 else:
733 if not IsFloat(Value):
734 PrintError("The value specified, %s, for option \"%s\" in string \"%s\" must be a float." % (Value, OptionName, OptionValueString))
735 Value = float(Value)
736 ValidateOptionNumberValue(OptionName, Value, CmpOpValueMap)
737
738 def ValidateOptionTextValue(OptionName, OptionValue, ValidValues):
739 """Validate option value based on the valid specified values separated by spaces.
740
741 Arguments:
742 OptionName (str): Command line option name.
743 OptionValue (str): Command line option value.
744 ValidValues (str): Space delimited string containing valid values.
745
746 Notes:
747 The function exits with an error message for an invalid option value.
748
749 """
750
751 if not CheckTextValue(OptionValue, ValidValues):
752 PrintError("The value specified, %s, for option \"%s\" is not valid. Supported value(s): %s " % (OptionValue, OptionName, ValidValues))
753
754 def ValidateOptionsOutputFileOverwrite(OptionName, FilePath, OverwriteOptionName, OverwriteStatus):
755 """Validate overwriting of output file.
756
757 Arguments:
758 OptionName (str): Command line option name.
759 FilePath (str): Name of a file with complete file path.
760 OverwriteOptionName (str): Overwrite command line option name.
761 OverwriteStatus (bool): True, overwrite
762
763 Notes:
764 The function exits with an error message for a file that is present and is not allowed
765 to be written as indicated by value of OverwriteStatus.
766
767 """
768
769 if os.path.exists(FilePath):
770 if not OverwriteStatus:
771 if len(OverwriteOptionName) > 4:
772 ShortOverwriteOptionName = OverwriteOptionName[:4]
773 else:
774 ShortOverwriteOptionName = OverwriteOptionName
775
776 PrintError("The file specified, %s, for option \"%s\" already exist. Use option \"%s\" or \"%s\" and try again.\n" % (FilePath, OptionName, ShortOverwriteOptionName, OverwriteOptionName))
777
778 def ValidateOptionsDistinctFileNames(OptionName1, FilePath1, OptionName2, FilePath2):
779 """Validate two distinct file names.
780
781 Arguments:
782 OptionName1 (str): Command line option name.
783 FilePath1 (str): Name of a file with complete file path.
784 OptionName2 (str): Command line option name.
785 FilePath2 (str): Name of a file with complete file path.
786
787 Notes:
788 The function exits with an error message for two non distinct file names.
789
790 """
791
792 FilePath1Pattern = r"^" + re.escape(FilePath1) + r"$";
793 if re.match(FilePath1Pattern, FilePath2, re.I):
794 PrintError("The file name specified, %s, for options \"%s\" and \"%s\" must be different.\n" % (FilePath1, OptionName1, OptionName2))
795
796 def ProcessOptionMultiprocessingParameters(ParamsOptionName, ParamsOptionValue):
797 """Process parameters for multiprocessing and return a map containing processed
798 parameter names and values.
799
800 Arguments:
801 ParamsOptionName (str): Command line multiprocessing parameters option name.
802 ParamsOptionValues (str): Comma delimited list of parameter name and value pairs.
803
804 Returns:
805 dictionary: Processed parameter name and value pairs.
806
807 Notes:
808 The parameter name and values specified in ParamsOptionValues are validated before
809 returning them in a dictionary.
810
811 """
812
813 ParamsInfo = {'ChunkSize': 'auto', 'InputDataMode' : 'Lazy', 'NumProcesses': 'auto'}
814
815 if re.match("^auto$", ParamsOptionValue, re.I):
816 # No specific parameters to process except for parameters with possible auto value...
817 _ProcessOptionMultiprocessingParameters(ParamsInfo, ParamsOptionName, ParamsOptionValue)
818 return ParamsInfo
819
820 ParamsOptionValue = re.sub(" ", "", ParamsOptionValue)
821 if not ParamsOptionValue:
822 PrintError("No valid parameter name and value pairs specified using \"%s\" option" % ParamsOptionName)
823
824 ParamsOptionValueWords = ParamsOptionValue.split(",")
825 if len(ParamsOptionValueWords) % 2:
826 PrintError("The number of comma delimited paramater names and values, %d, specified using \"%s\" option must be an even number." % (len(ParamsOptionValueWords), ParamsOptionName))
827
828 # Setup a canonical paramater names...
829 ValidParamNames = []
830 CanonicalParamNamesMap = {}
831 for ParamName in sorted(ParamsInfo):
832 ValidParamNames.append(ParamName)
833 CanonicalParamNamesMap[ParamName.lower()] = ParamName
834
835 # Validate paramater name and value pairs...
836 for Index in range(0, len(ParamsOptionValueWords), 2):
837 Name = ParamsOptionValueWords[Index]
838 Value = ParamsOptionValueWords[Index + 1]
839
840 CanonicalName = Name.lower()
841 if not CanonicalName in CanonicalParamNamesMap:
842 PrintError("The parameter name, %s, specified using \"%s\" is not a valid name. Supported parameter names: %s" % (Name, ParamsOptionName, " ".join(ValidParamNames)))
843
844 ParamName = CanonicalParamNamesMap[CanonicalName]
845 ParamValue = Value
846
847 if re.match("^InputDataMode$", ParamName, re.I):
848 if re.match("^Lazy$", Value, re.I):
849 ParamValue = "Lazy"
850 elif re.match("^InMemory$", Value, re.I):
851 ParamValue = "InMemory"
852 else:
853 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value. Supported values: Lazy or InMemory" % (Value, Name, ParamsOptionName))
854 elif re.match("^NumProcesses$", ParamName, re.I):
855 if not re.match("^Auto$", Value, re.I):
856 Value = int(Value)
857 if Value <= 0:
858 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value. Supported values: > 0" % (Value, Name, ParamsOptionName))
859 if Value > mp.cpu_count():
860 PrintWarning("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is greater than number of CPUs, %s, returned by mp.cpu_count()." % (Value, Name, ParamsOptionName, mp.cpu_count()))
861 else:
862 if not re.match("^Auto$", Value, re.I):
863 Value = int(Value)
864 if Value <= 0:
865 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value. Supported values: > 0" % (Value, Name, ParamsOptionName))
866
867 # Set value...
868 ParamsInfo[ParamName] = ParamValue
869
870 # Handle paramaters with possible auto values...
871 _ProcessOptionMultiprocessingParameters(ParamsInfo, ParamsOptionName, ParamsOptionValue)
872
873 return ParamsInfo
874
875 def _ProcessOptionMultiprocessingParameters(ParamsInfo, ParamsOptionName, ParamsOptionValue):
876 """Process parameters with possible auto values."""
877
878 # NumProcesses parameter...
879 Value = ParamsInfo["NumProcesses"]
880 ParamsInfo["NumProcesses"] = mp.cpu_count() if re.match("^auto$", Value, re.I) else int(Value)
881
882 # ChunkSize parameter...
883 Value = ParamsInfo["ChunkSize"]
884 if re.match("^auto$", Value, re.I):
885 Value = None if re.match("^InMemory$", ParamsInfo["InputDataMode"], re.I) else 1
886 else:
887 Value = int(Value)
888 ParamsInfo["ChunkSize"] = Value
889
890 def ProcessOptionInfileParameters(ParamsOptionName, ParamsOptionValue, InfileName = None, OutfileName = None):
891 """Process parameters for reading input files and return a map containing
892 processed parameter names and values.
893
894 Arguments:
895 ParamsOptionName (str): Command line input parameters option name.
896 ParamsOptionValues (str): Comma delimited list of parameter name and value pairs.
897 InfileName (str): Name of input file.
898 OutfileName (str): Name of output file.
899
900 Returns:
901 dictionary: Processed parameter name and value pairs.
902
903 Notes:
904 The parameter name and values specified in ParamsOptionValues are validated before
905 returning them in a dictionary.
906
907 """
908
909 ParamsInfo = {'RemoveHydrogens': True, 'Sanitize' : True, 'StrictParsing': True, 'SMILESColumn': 1, 'SMILESNameColumn' : 2, 'SMILESDelimiter': ' ', 'SMILESTitleLine': 'auto'}
910 _ProcessInfileAndOutfileParameters('Infile', ParamsInfo, ParamsOptionName, ParamsOptionValue, InfileName, OutfileName,)
911
912 return ParamsInfo
913
914 def ProcessOptionOutfileParameters(ParamsOptionName, ParamsOptionValue, InfileName = None, OutfileName = None):
915 """Process parameters for writing output files and return a map containing
916 processed parameter names and values.
917
918 Arguments:
919 ParamsOptionName (str): Command line input parameters option name.
920 ParamsOptionValues (str): Comma delimited list of parameter name and value pairs.
921 InfileName (str): Name of input file.
922 OutfileName (str): Name of output file.
923
924 Returns:
925 dictionary: Processed parameter name and value pairs.
926
927 Notes:
928 The parameter name and values specified in ParamsOptionValues are validated before
929 returning them in a dictionary.
930
931 The default value of some parameters may depend on type of input file. Consequently,
932 the input file name is also needed.
933
934 """
935 ParamsInfo = {'Compute2DCoords' : 'auto', 'Kekulize': False, 'SMILESDelimiter': ' ', 'SMILESIsomeric': True, 'SMILESTitleLine': True, 'SMILESMolName': True, 'SMILESMolProps': False}
936 _ProcessInfileAndOutfileParameters('Outfile', ParamsInfo, ParamsOptionName, ParamsOptionValue, InfileName, OutfileName)
937
938 return ParamsInfo
939
940 def _ProcessInfileAndOutfileParameters(Mode, ParamsInfo, ParamsOptionName, ParamsOptionValue, InfileName, OutfileName):
941 """Process specified infile and outfile paramaters.
942
943 """
944 if re.match("^auto$", ParamsOptionValue, re.I):
945 # No specific parameters to process except for parameters with possible auto value...
946 _ProcessInfileAndOutfileAutoParameters(Mode, ParamsInfo, ParamsOptionName, ParamsOptionValue, InfileName, OutfileName)
947 return
948
949 ParamsOptionValue = re.sub(" ", "", ParamsOptionValue)
950 if not ParamsOptionValue:
951 PrintError("No valid parameter name and value pairs specified using \"%s\" option" % ParamsOptionName)
952
953 ParamsOptionValueWords = ParamsOptionValue.split(",")
954 if len(ParamsOptionValueWords) % 2:
955 PrintError("The number of comma delimited paramater names and values, %d, specified using \"%s\" option must be an even number." % (len(ParamsOptionValueWords), ParamsOptionName))
956
957 # Setup a canonical paramater names...
958 ValidParamNames = []
959 CanonicalParamNamesMap = {}
960 for ParamName in sorted(ParamsInfo):
961 ValidParamNames.append(ParamName)
962 CanonicalParamNamesMap[ParamName.lower()] = ParamName
963
964 # Validate paramater name and value pairs...
965 for Index in range(0, len(ParamsOptionValueWords), 2):
966 Name = ParamsOptionValueWords[Index]
967 Value = ParamsOptionValueWords[Index + 1]
968
969 CanonicalName = Name.lower()
970 if not CanonicalName in CanonicalParamNamesMap:
971 PrintError("The parameter name, %s, specified using \"%s\" is not a valid name. Supported parameter names: %s" % (Name, ParamsOptionName, " ".join(ValidParamNames)))
972
973 ParamName = CanonicalParamNamesMap[CanonicalName]
974 ParamValue = Value
975
976 if re.match("^(Sanitize|StrictParsing|RemoveHydrogens|Kekulize|SMILESIsomeric)$", ParamName, re.I):
977 if not re.match("^(Yes|No|True|False)$", Value, re.I):
978 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value. Supported values: Yes No True False" % (Value, Name, ParamsOptionName))
979 ParamValue = True
980 if re.match("^(No|False)$", Value, re.I):
981 ParamValue = False
982 elif re.match("^SMILESTitleLine$", ParamName, re.I):
983 if re.match("^Infile$", Mode, re.I):
984 if not re.match("^(Yes|No|True|False|Auto)$", Value, re.I):
985 PrintError("The parameter value, %s, specified for paramater name, %s, using \"%s\" option is not a valid value. Supported values: Yes No True False Auto" % (Value, Name, ParamsOptionName))
986 elif re.match("^Outfile$", Mode, re.I):
987 if not re.match("^(Yes|No|True|False)$", Value, re.I):
988 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value. Supported values: Yes No True False" % (Value, Name, ParamsOptionName))
989 ParamValue = True
990 if re.match("^(No|False)$", Value, re.I):
991 ParamValue = False
992 elif re.match("^(SMILESMolName|SMILESMolProps)$", ParamName, re.I):
993 if re.match("^Outfile$", Mode, re.I):
994 if not re.match("^(Yes|No|True|False)$", Value, re.I):
995 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value. Supported values: Yes No True False" % (Value, Name, ParamsOptionName))
996 ParamValue = True
997 if re.match("^(No|False)$", Value, re.I):
998 ParamValue = False
999 else:
1000 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value during mode %s." % (Value, Name, ParamsOptionName, Mode))
1001 elif re.match("^SMILESDelimiter$", ParamName, re.I):
1002 if not re.match("^(space|tab|comma)$", Value, re.I):
1003 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value. Supported values: space tab comma" % (Value, Name, ParamsOptionName))
1004 ParamValue = " "
1005 if re.match("^tab$", Value, re.I):
1006 ParamValue = "\t"
1007 elif re.match("^comma$", Value, re.I):
1008 ParamValue = ","
1009 elif re.match("^Compute2DCoords$", ParamName, re.I):
1010 # No need to set the value. It would be processed later to handle "auto" value...
1011 if not re.match("^(Yes|No|True|False|Auto)$", Value, re.I):
1012 PrintError("The parameter value, %s, specified for paramater name, %s, using \"%s\" option is not a valid value. Supported values: Yes No True False Auto" % (Value, Name, ParamsOptionName))
1013 else:
1014 ParamValue = int(Value)
1015 if ParamValue <= 0:
1016 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value. Supported values: > 0" % (Value, Name, ParamsOptionName))
1017
1018 # Set value...
1019 ParamsInfo[ParamName] = ParamValue
1020
1021 # Handle paramaters with possible auto values...
1022 _ProcessInfileAndOutfileAutoParameters(Mode, ParamsInfo, ParamsOptionName, ParamsOptionValue, InfileName, OutfileName)
1023
1024 def _ProcessInfileAndOutfileAutoParameters(Mode, ParamsInfo, ParamsOptionName, ParamsOptionValue, InfileName, OutfileName):
1025 """Process parameters with possible auto values.
1026
1027 """
1028 if re.match("^Infile$", Mode, re.I):
1029 # SMILESTitleLine parameter...
1030 Value = ParamsInfo["SMILESTitleLine"]
1031 ParamValue = False
1032 if re.match("^auto$", Value, re.I):
1033 if InfileName is not None:
1034 if CheckFileExt(InfileName, "smi csv tsv txt"):
1035 ParamValue = DoesSMILESFileContainTitleLine(InfileName)
1036 elif re.match("^(Yes|True)$", Value, re.I):
1037 ParamValue = True
1038 ParamsInfo["SMILESTitleLine"] = ParamValue
1039 elif re.match("^Outfile$", Mode, re.I):
1040 # Compute2DCoords parameter...
1041 Value = ParamsInfo["Compute2DCoords"]
1042 ParamValue = False
1043 if re.match("^auto$", Value, re.I):
1044 if InfileName is not None:
1045 if CheckFileExt(InfileName, "smi csv tsv txt"):
1046 ParamValue = True
1047 if OutfileName is not None:
1048 if CheckFileExt(OutfileName, "smi csv tsv txt"):
1049 # No need to compute 2D coords for SMILES file...
1050 ParamValue = False
1051 elif re.match("^(Yes|True)$", Value, re.I):
1052 ParamValue = True
1053 ParamsInfo["Compute2DCoords"] = ParamValue
1054
1055 # SetSMILESMolProps parameter...
1056 SetSMILESMolProps = False
1057 if OutfileName is not None:
1058 SetSMILESMolProps = True if (ParamsInfo["SMILESMolProps"] and CheckFileExt(OutfileName, "smi")) else False
1059 ParamsInfo["SetSMILESMolProps"] = SetSMILESMolProps
1060
1061 def ProcessOptionSeabornPlotParameters(ParamsOptionName, ParamsOptionValue, ParamsDefaultInfo = None):
1062 """Process parameters for generating Seaborn plots and return a map containing
1063 processed parameter names and values.
1064
1065 Arguments:
1066 ParamsOptionName (str): Command line seaborn parameters option name.
1067 ParamsOptionValues (str): Comma delimited list of parameter name and value pairs.
1068 ParamsDefaultValues (dict): Default values for selected parameters.
1069
1070 Returns:
1071 dictionary: Processed parameter name and value pairs.
1072
1073 Notes:
1074 The parameter name and values specified in ParamsOptionValues are validated before
1075 returning them in a dictionary.
1076
1077 """
1078 # The default width and height in Matplotlib is 6.4 and 4.8 and maps to aspect ratio of 1.3...
1079 ParamsInfo = {'Type' : 'auto', 'OutExt': 'svg', 'Width': 'auto', 'Height': 'auto',
1080 'Title': 'auto', 'XLabel': 'auto', 'YLabel': 'auto', 'TitleWeight': 'bold', 'LabelWeight': 'bold',
1081 'Style': 'darkgrid', 'Palette': 'deep', 'Font': 'sans-serif', 'FontScale': 1,
1082 'Context': 'notebook'}
1083
1084 # Setup a canonical paramater names...
1085 ValidParamNames = []
1086 CanonicalParamNamesMap = {}
1087 for ParamName in sorted(ParamsInfo):
1088 ValidParamNames.append(ParamName)
1089 CanonicalParamNamesMap[ParamName.lower()] = ParamName
1090
1091 # Update default values...
1092 if ParamsDefaultInfo is not None:
1093 for ParamName in ParamsDefaultInfo:
1094 if ParamName not in ParamsInfo:
1095 PrintError("The default parameter name, %s, specified using \"%s\" to function ProcessOptionSeabornPlotParameters is not a valid name. Supported parameter names: %s" % (ParamName, ParamsDefaultInfo, " ".join(ValidParamNames)))
1096 ParamsInfo[ParamName] = ParamsDefaultInfo[ParamName]
1097
1098 if re.match("^auto$", ParamsOptionValue, re.I):
1099 # No specific parameters to process except for parameters with possible auto value...
1100 _ProcessOptionSeabornPlotParameters(ParamsInfo, ParamsOptionName, ParamsOptionValue, ParamsDefaultInfo = None)
1101 return ParamsInfo
1102
1103 ParamsOptionValue = ParamsOptionValue.strip()
1104 if not ParamsOptionValue:
1105 PrintError("No valid parameter name and value pairs specified using \"%s\" option" % ParamsOptionName)
1106
1107 ParamsOptionValueWords = ParamsOptionValue.split(",")
1108 if len(ParamsOptionValueWords) % 2:
1109 PrintError("The number of comma delimited paramater names and values, %d, specified using \"%s\" option must be an even number." % (len(ParamsOptionValueWords), ParamsOptionName))
1110
1111 # Validate paramater name and value pairs...
1112 for Index in range(0, len(ParamsOptionValueWords), 2):
1113 Name = ParamsOptionValueWords[Index].strip()
1114 Value = ParamsOptionValueWords[Index + 1].strip()
1115
1116 CanonicalName = Name.lower()
1117 if not CanonicalName in CanonicalParamNamesMap:
1118 PrintError("The parameter name, %s, specified using \"%s\" is not a valid name. Supported parameter names: %s" % (Name, ParamsOptionName, " ".join(ValidParamNames)))
1119
1120 ParamName = CanonicalParamNamesMap[CanonicalName]
1121 ParamValue = Value
1122
1123 if re.match("^Style$", ParamName, re.I):
1124 if not re.match("^(darkgrid|whitegrid|dark|white|ticks)$", Value):
1125 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value. Supported values: darkgrid, whitegrid, dark, white or ticks" % (Value, Name, ParamsOptionName))
1126 elif re.match("^Palette$", ParamName, re.I):
1127 if not re.match("^(deep|muted|pastel|dark|bright|colorblind)$", Value):
1128 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value. Supported values: deep, muted, pastel, dark, bright or colorblind" % (Value, Name, ParamsOptionName))
1129 elif re.match("^Context$", ParamName, re.I):
1130 if not re.match("^(notebook|paper|talk|poster)$", Value):
1131 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value. Supported values: notebook, paper, talk or poster" % (Value, Name, ParamsOptionName))
1132 elif re.match("^(Width|Height)$", ParamName, re.I):
1133 if not re.match("^auto$", ParamValue, re.I):
1134 Value = float(Value)
1135 if Value <= 0:
1136 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value. Supported values: > 0" % (Value, Name, ParamsOptionName))
1137 ParamValue = Value
1138 elif re.match("^(FontScale)$", ParamName, re.I):
1139 Value = float(Value)
1140 if Value <= 0:
1141 PrintError("The parameter value, %s, specified for parameter name, %s, using \"%s\" option is not a valid value. Supported values: > 0" % (Value, Name, ParamsOptionName))
1142 ParamValue = Value
1143 # Set value...
1144 ParamsInfo[ParamName] = ParamValue
1145
1146 # Handle paramaters with possible auto values...
1147 _ProcessOptionSeabornPlotParameters(ParamsInfo, ParamsOptionName, ParamsOptionValue, ParamsDefaultInfo = None)
1148
1149 return ParamsInfo
1150
1151 def _ProcessOptionSeabornPlotParameters(ParamsInfo, ParamsOptionName, ParamsOptionValue, ParamsDefaultInfo = None):
1152 """Process parameters with possible auto values."""
1153
1154 if ParamsDefaultInfo is None:
1155 return
1156
1157 for ParamName in ParamsInfo:
1158 ParamValue = ParamsInfo[ParamName]
1159 if re.match("^auto$", ParamsInfo[ParamName], re.I):
1160 if ParamName in ParamsDefaultInfo:
1161 ParamsInfo[ParamName] = ParamsDefaultInfo[ParamName]
1162
1163 def ReplaceHTMLEntitiesInText(Text):
1164 """Check and replace the followng HTML entities to their respective code
1165 for display in a browser: < (less than), > (greater than), & (ampersand),
1166 " (double quote), and ' (single quote).
1167
1168 Arguments:
1169 Text (str): Text value.
1170
1171 Returns:
1172 str : Modifed text value.
1173
1174 """
1175
1176 if re.search("""(<|>|&|"|')""", Text):
1177 return Text.replace("<", "<").replace(">", ">").replace("&", "&").replace('"', """).replace("'","'")
1178 else:
1179 return Text
1180
1181 def TruncateText(Text, Width, TrailingChars = "..."):
1182 """Truncate text using specified width along with appending any trailing
1183 characters.
1184
1185 Arguments:
1186 Text (string): Input text.
1187 Width (int): Max number of characters before truncating text.
1188 Delimiter (string): Trailing characters to append or None.
1189
1190 Returns:
1191 str : Truncated text
1192
1193 """
1194
1195 if len(Text) < Width:
1196 return Text
1197
1198 TruncatedText = (Text[:Width] + TrailingChars) if not IsEmpty(TrailingChars) else Text[:Width]
1199
1200 return TruncatedText
1201
1202 def WrapText(Text, Delimiter, Width):
1203 """Wrap text using specified delimiter and width.
1204
1205 Arguments:
1206 Text (string): Input text
1207 Delimiter (string): Delimiter for wrapping text
1208 Width (int): Max number of characters before wrapping text
1209
1210 Returns:
1211 str : Wrapped text
1212
1213 """
1214 WrappedText = Delimiter.join(textwrap.wrap(Text, width = Width))
1215
1216 return WrappedText