MayaChemTools

    1 #!/bin/env python
    2 #
    3 # File: RDKitDrawMoleculesAndDataTable.py
    4 # Author: Manish Sud <msud@san.rr.com>
    5 #
    6 # Copyright (C) 2020 Manish Sud. All rights reserved.
    7 #
    8 # The functionality available in this script is implemented using RDKit, an
    9 # open source toolkit for cheminformatics developed by Greg Landrum.
   10 #
   11 # This file is part of MayaChemTools.
   12 #
   13 # MayaChemTools is free software; you can redistribute it and/or modify it under
   14 # the terms of the GNU Lesser General Public License as published by the Free
   15 # Software Foundation; either version 3 of the License, or (at your option) any
   16 # later version.
   17 #
   18 # MayaChemTools is distributed in the hope that it will be useful, but without
   19 # any warranty; without even the implied warranty of merchantability of fitness
   20 # for a particular purpose.  See the GNU Lesser General Public License for more
   21 # details.
   22 #
   23 # You should have received a copy of the GNU Lesser General Public License
   24 # along with MayaChemTools; if not, see <http://www.gnu.org/licenses/> or
   25 # write to the Free Software Foundation Inc., 59 Temple Place, Suite 330,
   26 # Boston, MA, 02111-1307, USA.
   27 #
   28 
   29 from __future__ import print_function
   30 
   31 # Add local python path to the global path and import standard library modules...
   32 import os
   33 import sys;  sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), "..", "lib", "Python"))
   34 import time
   35 import re
   36 import random
   37 
   38 # RDKit imports...
   39 try:
   40     from rdkit import rdBase
   41     from rdkit import Chem
   42     from rdkit.Chem import AllChem
   43 except ImportError as ErrMsg:
   44     sys.stderr.write("\nFailed to import RDKit module/package: %s\n" % ErrMsg)
   45     sys.stderr.write("Check/update your RDKit environment and try again.\n\n")
   46     sys.exit(1)
   47 
   48 # MayaChemTools imports...
   49 try:
   50     from docopt import docopt
   51     import MiscUtil
   52     import RDKitUtil
   53 except ImportError as ErrMsg:
   54     sys.stderr.write("\nFailed to import MayaChemTools module/package: %s\n" % ErrMsg)
   55     sys.stderr.write("Check/update your MayaChemTools environment and try again.\n\n")
   56     sys.exit(1)
   57 
   58 ScriptName = os.path.basename(sys.argv[0])
   59 Options = {}
   60 OptionsInfo = {}
   61 
   62 def main():
   63     """Start execution of the script"""
   64     
   65     MiscUtil.PrintInfo("\n%s (RDK v%s; %s): Starting...\n" % (ScriptName, rdBase.rdkitVersion, time.asctime()))
   66     
   67     (WallClockTime, ProcessorTime) = MiscUtil.GetWallClockAndProcessorTime()
   68     
   69     # Retrieve command line arguments and options...
   70     RetrieveOptions()
   71     
   72     # Process and validate command line arguments and options...
   73     ProcessOptions()
   74     
   75     # Perform actions required by the script...
   76     GenerateMoleculesAndDataTable()
   77     
   78     MiscUtil.PrintInfo("\n%s: Done...\n" % ScriptName)
   79     MiscUtil.PrintInfo("Total time: %s" % MiscUtil.GetFormattedElapsedTime(WallClockTime, ProcessorTime))
   80 
   81 def GenerateMoleculesAndDataTable():
   82     """Generate a HTML table containing molecules and alphanumerical data."""
   83     
   84     # Retrieve data...
   85     ValidMols = RetrieveMoleculesAndData()
   86 
   87     # Setup data type map...
   88     DataMap = IdentifyStructureAndNumericalData(ValidMols)
   89 
   90     # Validate data labels used to specify highlighting data...
   91     ValidateSpecifiedDataLabels(DataMap)
   92 
   93     # Validate show molecule name option...
   94     ValidateShowMolNameOption(DataMap)
   95     
   96     # Compute 2D coordinates before alignment...
   97     if OptionsInfo["Compute2DCoords"]:
   98         MiscUtil.PrintInfo("\nComputing 2D coordinates for primary structure data...")
   99         for Mol in ValidMols:
  100             AllChem.Compute2DCoords(Mol)
  101             
  102     # Perform alignment to a common template for primary molecular structure data...
  103     PerformAlignment(ValidMols)
  104 
  105     # Write out a HTML file...
  106     WriteHTMLTableFile(ValidMols, DataMap)
  107 
  108 def WriteHTMLTableFile(ValidMols, DataMap):
  109     """Write out a HTML table file."""
  110     
  111     Outfile = OptionsInfo["Outfile"]
  112     
  113     Writer = open(Outfile, "w")
  114     if Writer is None:
  115         MiscUtil.PrintError("Failed to setup a writer for output fie %s " % Outfile)
  116     
  117     MiscUtil.PrintInfo("\nGenerating file %s..." % Outfile)
  118 
  119     WriteHTMLPageHeader(Writer, DataMap)
  120     WriteHTMLPageTitle(Writer)
  121     
  122     WriteHTMLTableHeader(Writer)
  123     WriteHTMLTableRows(Writer, ValidMols, DataMap)
  124     WriteHTMLTableEnd(Writer)
  125     
  126     WriteHTMLPageFooter(Writer)
  127     WriteHTMLPageEnd(Writer)
  128     
  129     if Writer is not None:
  130         Writer.close()
  131 
  132 def WriteHTMLTableRows(Writer, ValidMols, DataMap):
  133     """Write out HTML table rows."""
  134 
  135     WriteTableHeaderRow(Writer, ValidMols, DataMap)
  136     WriteTableDataRows(Writer, ValidMols, DataMap)
  137     WriteTableFooterRow(Writer, ValidMols, DataMap)
  138 
  139 def WriteTableDataRows(Writer, ValidMols, DataMap):
  140     """Write out table data row."""
  141 
  142     Writer.write("""        <tbody>\n""")
  143     
  144     MolCount = 0
  145     for Mol in ValidMols:
  146         MolCount += 1
  147         Writer.write("""          <tr>\n""")
  148 
  149         if OptionsInfo["CounterCol"]:
  150             Writer.write("""            <td></td>\n""")
  151             
  152         SetupPrimaryStructureTableData(Writer, Mol)
  153         
  154         if OptionsInfo["ShowMolName"]:
  155             MolName = RDKitUtil.GetMolName(Mol, MolCount)
  156             WrappedMolName = MiscUtil.WrapText(MolName, "<br/>", OptionsInfo["WrapTextWidth"])
  157             Writer.write("""            <td>%s</td>\n""" % WrappedMolName)
  158 
  159         # Set up rest of the data..
  160         AvailableDataLabelsMap = Mol.GetPropsAsDict(includePrivate = False, includeComputed = False)
  161         for DataLabel in DataMap["DataLabels"]:
  162             if not DataLabel in AvailableDataLabelsMap:
  163                 Writer.write("""            <td></td>\n""")
  164                 continue
  165 
  166             # Check for empty value...
  167             DataValue = "%s" % AvailableDataLabelsMap[DataLabel]
  168             DataValue = DataValue.strip()
  169             if MiscUtil.IsEmpty(DataValue):
  170                 Writer.write("""            <td></td>\n""")
  171                 continue
  172             
  173             if DataMap["StructureDataMap"][DataLabel]:
  174                 SetupNonPrimaryStructureTableData(Writer, DataLabel, DataValue, DataMap)
  175             else:
  176                 SetupAlphanumericTableData(Writer, DataLabel, DataValue, DataMap)
  177         
  178         Writer.write("""          </tr>\n""")
  179         
  180     Writer.write("""        </tbody>\n""")
  181 
  182 def SetupPrimaryStructureTableData(Writer, Mol):
  183     """Set up an inline SVG image for primary structure data for a table cell."""
  184     
  185     HightlightAtomList = SetupAtomListToHighlight(Mol, "Structure")
  186     SVGImageTag = SetupMolInLineSVGImageTag(Mol, HightlightAtomList)
  187     
  188     Writer.write("""            <td bgcolor="white"><%s></td>\n""" % SVGImageTag)
  189 
  190 def SetupNonPrimaryStructureTableData(Writer, DataLabel, DataValue, DataMap):
  191     """Set up an inline SVG image for non primary structure data cell."""
  192 
  193     WrappedDataValue = DataValue
  194     if OptionsInfo["WrapText"]:
  195         WrappedDataValue = MiscUtil.WrapText(DataValue, "<br/>", OptionsInfo["WrapTextWidth"])
  196 
  197     if DataMap["SMILESDataMap"][DataLabel]:
  198         Mol = Chem.MolFromSmiles(DataValue, sanitize = False)
  199         Mol.UpdatePropertyCache(strict = False)
  200     else:
  201         MiscUtil.PrintWarning("\nIgnoring uknown structure data column type with column label %s: %s\n" % (DataLabel, DataValue))
  202         Writer.write("""            <td>%s</td>\n""" % WrappedDataValue)
  203         return
  204 
  205     if Mol is None:
  206         MiscUtil.PrintWarning("\nSMILES parsing failed for data label %s: %s\n" % (DataLabel, DataValue))
  207         Writer.write("""            <td>%s</td>\n""" % WrappedDataValue)
  208         return
  209     elif  not Mol.GetNumHeavyAtoms():
  210         Writer.write("""            <td>%s</td>\n""" % WrappedDataValue)
  211         return
  212     elif AllChem.Compute2DCoords(Mol) < 0:
  213         Writer.write("""            <td>%s</td>\n""" % WrappedDataValue)
  214         return
  215     
  216     HightlightAtomList = SetupAtomListToHighlight(Mol, DataLabel)
  217     SVGImageTag = SetupMolInLineSVGImageTag(Mol, HightlightAtomList)
  218     
  219     Writer.write("""            <td bgcolor="white"><%s></td>\n""" % SVGImageTag)
  220 
  221 def SetupAlphanumericTableData(Writer, DataLabel, DataValue, DataMap):
  222     """Set up alphanumeric data."""
  223 
  224     BackgroundColor, BackgroundColorType = GetAlphanumeircValueHighlightBackgroundColor(DataLabel, DataValue, DataMap)
  225     SetupAlphanumericTableDataValue(Writer, DataValue, BackgroundColor, BackgroundColorType)
  226 
  227 def WriteTableHeaderRow(Writer, ValidMols, DataMap):
  228     """Write out table header row."""
  229 
  230     TableHeaderStyle = OptionsInfo["TableHeaderStyle"]
  231     if TableHeaderStyle is None:
  232         Writer.write("""      <thead>\n""")
  233         Writer.write("""        <tr>\n""")
  234     elif re.match("^(thead|table)", TableHeaderStyle):
  235         Writer.write("""      <thead class="%s">\n""" % TableHeaderStyle)
  236         Writer.write("""        <tr>\n""")
  237     else:
  238         Writer.write("""      <thead>\n""")
  239         Writer.write("""        <tr bgcolor="%s"\n""" % TableHeaderStyle)
  240 
  241     if OptionsInfo["CounterCol"]:
  242         Writer.write("""          <th></th>\n""")
  243     Writer.write("""          <th>Structure</th>\n""")
  244     if OptionsInfo["ShowMolName"]:
  245         Writer.write("""          <th>%s</th>\n""" % OptionsInfo["ShowMolNameDataLabel"])
  246     
  247     # Write out rest of the column headers...
  248     for DataLabel in DataMap["DataLabels"]:
  249         Writer.write("""          <th>%s</th>\n""" % DataLabel)
  250         
  251     Writer.write("""        </tr>\n""")
  252     Writer.write("""      </thead>\n""")
  253 
  254 def WriteTableFooterRow(Writer, ValidMols, DataMap):
  255     """Write out table footer row."""
  256 
  257     if not OptionsInfo["TableFooter"]:
  258         return
  259     
  260     Writer.write("""      <tfoot>\n""")
  261     Writer.write("""        <tr>\n""")
  262 
  263     if OptionsInfo["CounterCol"]:
  264         Writer.write("""          <td></td>\n""")
  265     Writer.write("""          <td>Structure</td>\n""")
  266     if OptionsInfo["ShowMolName"]:
  267         Writer.write("""          <td>%s</td>\n""" % OptionsInfo["ShowMolNameDataLabel"])
  268 
  269     # Write out rest of the column headers...
  270     for DataLabel in DataMap["DataLabels"]:
  271         Writer.write("""          <td>%s</td>\n""" % DataLabel)
  272         
  273     Writer.write("""        </tr>\n""")
  274     Writer.write("""      </tfoot>\n""")
  275 
  276 def WriteHTMLPageHeader(Writer, DataMap):
  277     """Write out HTML page header."""
  278 
  279     # Collect column indices containing counter and structure data to disable
  280     # sorting and searching. In addition, set up a list to exclude counter and
  281     # primary structure columns from column visibility pulldown along with
  282     # any other columns...
  283     #
  284     if OptionsInfo["CounterCol"]:
  285         StrColIndicesList = ["0", "1"]
  286         ColVisibilityExcludeColIndicesList = ["0", "1"]
  287         ColIndexOffset = 2
  288         FreezeLeftColumns = "2"
  289     else:
  290         StrColIndicesList = ["0"]
  291         ColVisibilityExcludeColIndicesList = ["0"]
  292         ColIndexOffset = 1
  293         FreezeLeftColumns = "1"
  294 
  295     if OptionsInfo["ShowMolName"]:
  296         ColIndexOffset += 1
  297         
  298     MaxColVisColCount = OptionsInfo["ColVisibilityCtrlMax"]
  299     MaxDataColVisColCount = MaxColVisColCount - len(ColVisibilityExcludeColIndicesList)
  300     MaxDataColVisColCount = MaxColVisColCount
  301 
  302     DataColVisibilityExclude = False
  303     ColCount = len(DataMap["DataLabels"])
  304     if OptionsInfo["ColVisibility"]:
  305         if ColCount > MaxDataColVisColCount:
  306             DataColVisibilityExclude = True
  307             MiscUtil.PrintWarning("The number of data columns, %d, is more than %d. Only first %d data columns will be available in column visibility pulldown." % (ColCount, MaxColVisColCount, MaxColVisColCount))
  308     
  309     DisplayButtons = False
  310     if OptionsInfo["ColVisibility"]:
  311         if ColCount > 0 or OptionsInfo["ShowMolName"]:
  312             DisplayButtons = True
  313     
  314     FreezeCols = False
  315     if (OptionsInfo["FreezeCols"] and OptionsInfo["ScrollX"]):
  316         FreezeCols = True
  317     
  318     for Index, DataLabel in enumerate(DataMap["DataLabels"]):
  319         if DataMap["StructureDataMap"][DataLabel]:
  320             StrColIndex = Index + ColIndexOffset
  321             StrColIndicesList.append("%s" % StrColIndex)
  322         
  323         if OptionsInfo["ColVisibility"]:
  324             if Index >= MaxDataColVisColCount:
  325                 ColIndex = Index + ColIndexOffset
  326                 ColVisibilityExcludeColIndicesList.append("%s" %ColIndex)
  327             
  328     StrColIndices = MiscUtil.JoinWords(StrColIndicesList, ", ")
  329     ColVisibilityExcludeColIndices = MiscUtil.JoinWords(ColVisibilityExcludeColIndicesList, ", ")
  330 
  331     Paging = "true" if OptionsInfo["Paging"] else "false"
  332     PageLength = "%d" % OptionsInfo["PageLength"]
  333     PagingType = "\"%s\"" % OptionsInfo["PagingType"]
  334 
  335     ScrollX = "true" if OptionsInfo["ScrollX"] else "false"
  336     
  337     ScrollY = ""
  338     if OptionsInfo["ScrollY"]:
  339         if re.search("vh$", OptionsInfo["ScrollYSize"]):
  340             ScrollY = "\"%s\"" % OptionsInfo["ScrollYSize"]
  341         else:
  342             ScrollY = "%s" % OptionsInfo["ScrollYSize"]
  343     
  344     RegexSearch = "true" if  OptionsInfo["RegexSearch"] else "false"
  345 
  346     # Start HTML header...
  347     Title = "Molecules and data table" if OptionsInfo["Header"] is None else OptionsInfo["Header"]
  348 
  349     Writer.write("""\
  350 <!doctype html>
  351 <html lang="en">
  352 <head>
  353     <title>%s</title>
  354     <meta charset="utf-8">
  355     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  356     <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  357     <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css">
  358   
  359 """ % (Title))
  360 
  361     if (FreezeCols):
  362         Writer.write("""\
  363     <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/fixedcolumns/3.2.4/css/fixedColumns.bootstrap4.min.css">
  364 """)
  365     
  366     if (OptionsInfo["KeysNavigation"]):
  367         Writer.write("""\
  368     <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/keytable/2.3.2/css/keyTable.bootstrap4.min.css">
  369 """)
  370     
  371     Writer.write("""\
  372 
  373     <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
  374     <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
  375     <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
  376 
  377 """)
  378 
  379     if DisplayButtons:
  380         Writer.write("""\
  381     <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>
  382     <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.bootstrap4.min.js"></script>
  383     <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.colVis.min.js"></script>
  384 
  385 """)
  386     
  387     if (FreezeCols):
  388         Writer.write("""\
  389     <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/fixedcolumns/3.2.4/js/dataTables.fixedColumns.min.js"></script>
  390 """)
  391     
  392     if (OptionsInfo["KeysNavigation"]):
  393         Writer.write("""\
  394     <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/keytable/2.3.2/js/dataTables.keyTable.min.js"></script>
  395 """)
  396     
  397     # Intialize table using Bootstrap, DataTables and JQuery frameworks...
  398     Writer.write("""\
  399 
  400     <script type="text/javascript" class="init">
  401 
  402 $(document).ready(function() {
  403     var MolsAndDataTable = $('#MolsAndDataTable').DataTable( {
  404         "columnDefs": [
  405             {
  406                 "orderable": false,
  407                 "searchable": false,
  408                 "targets": [%s]
  409             },
  410 """ % (StrColIndices))
  411 
  412     if OptionsInfo["ColVisibility"]:
  413         Writer.write("""\
  414             {
  415                 "className": "noColVisCtrl",
  416                 "targets": [%s]
  417             }
  418 """ % (ColVisibilityExcludeColIndices))
  419 
  420     Writer.write("""\
  421         ],
  422 """)
  423     
  424     # Setup column visibility control pulldown by excluding counter column
  425     # and primary structure column from the list...
  426     #
  427     if OptionsInfo["ColVisibility"]:
  428         # Set up dom for button display...
  429         if OptionsInfo["Paging"]:
  430             Writer.write("""\
  431         "dom":  "<'row'<'col'l><'col'B><'col'f>>" +
  432             "<'row'<'col-sm-12'tr>>" +
  433             "<'row'<'col-sm-5'i><'col-sm-7'p>>",
  434 """)
  435         else:
  436             Writer.write("""\
  437         "dom":  "<'row'<'col-sm-6'B><'col-sm-6'f>>" +
  438             "<'row'<'col-sm-12'tr>>" +
  439             "<'row'<'col-sm-5'i><'col-sm-7'p>>",
  440 """)
  441         # Set up buttons...
  442         Writer.write("""\
  443         "buttons": [
  444             {
  445                 "extend": "colvis",
  446                 "text": "Column visibility",
  447                 "className": "btn btn-outline-light text-dark",
  448                 "columns": ":not(.noColVisCtrl)",
  449 """)
  450         if not DataColVisibilityExclude:
  451             Writer.write("""\
  452                 "prefixButtons": [ "colvisRestore" ],
  453 """)
  454         
  455         Writer.write("""\
  456                 "columnText": function ( dt, colIndex, colLabel ) {
  457                     return (colIndex + 1) + ": " + colLabel;
  458                 },
  459             }
  460         ],
  461 """)
  462 
  463     # Write out rest of the variables for DataTables...
  464     if FreezeCols:
  465         Writer.write("""\
  466         "fixedColumns": {
  467             "leftColumns": %s
  468         },
  469 """ % (FreezeLeftColumns))
  470     
  471     if (OptionsInfo["KeysNavigation"]):
  472         Writer.write("""\
  473         "keys": true,
  474 """)
  475     
  476     Writer.write("""\
  477         "pageLength": %s,
  478         "lengthMenu": [ [10, 15, 25, 50, 100, 500, 1000, -1], [10, 15, 25, 50, 100, 500, 1000, "All"] ],
  479         "paging": %s,
  480         "pagingType": %s,
  481         "scrollX": %s,
  482         "scrollY": %s,
  483         "scrollCollapse": true,
  484         "order": [],
  485         "search" : {"regex" : %s},
  486     } );
  487 """ % (PageLength, Paging, PagingType, ScrollX, ScrollY, RegexSearch))
  488     
  489     if OptionsInfo["CounterCol"]:
  490         Writer.write("""\
  491     MolsAndDataTable.on( 'order.dt search.dt', function () {
  492         MolsAndDataTable.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, rowIndex) {
  493             cell.innerHTML = rowIndex + 1;
  494         } );
  495     } ).draw();
  496 """)
  497     
  498     # End of Javacscript code...
  499     Writer.write("""\
  500 } );
  501 
  502     </script>
  503 """)
  504 
  505     # Finish up HTML header...
  506     Writer.write("""\
  507   
  508 </head>
  509 <body>
  510   <div class="container-fluid">
  511     <br/>
  512 """)
  513 
  514 def WriteHTMLPageEnd(Writer):
  515     """Write out HTML page end."""
  516 
  517     Writer.write("""\
  518   </div>
  519 </body>
  520 </html>
  521 """)
  522 
  523 def WriteHTMLPageTitle(Writer):
  524     """Write out HTML page title."""
  525 
  526     if OptionsInfo["Header"] is None:
  527         return
  528 
  529     Writer.write("""    <%s class="text-center">%s</%s>\n""" % (OptionsInfo["HeaderStyle"], OptionsInfo["Header"], OptionsInfo["HeaderStyle"]))
  530 
  531 def WriteHTMLPageFooter(Writer):
  532     """Write out HTML page footer."""
  533 
  534     if OptionsInfo["Footer"] is None:
  535         return
  536 
  537     Writer.write("""    <br/>\n    <p class="%s">%s</p>\n""" % (OptionsInfo["FooterClass"], OptionsInfo["Footer"]))
  538 
  539 def WriteHTMLTableHeader(Writer):
  540     """Write out HTML table header."""
  541 
  542     if OptionsInfo["TableStyle"] is None:
  543         Writer.write("""\n    <table id="MolsAndDataTable" cellspacing="0" width="100%">\n""")
  544     else:
  545         Writer.write("""    <table id="MolsAndDataTable" class="%s" cellspacing="0" width="100%s">\n""" % (OptionsInfo["TableStyle"], "%"))
  546         
  547 def WriteHTMLTableEnd(Writer):
  548     """Write out HTML table end."""
  549 
  550     Writer.write("""    </table>\n\n""")
  551 
  552 def RetrieveMoleculesAndData():
  553     """Retrieve molecules and data from input file."""
  554 
  555     MiscUtil.PrintInfo("\nReading file %s..." % OptionsInfo["Infile"])
  556 
  557     if MiscUtil.CheckFileExt(OptionsInfo["Infile"] ,"smi csv tsv txt"):
  558         # Check for the presence of SMILES column name in title line...
  559         Infile = open(OptionsInfo["Infile"], "r")
  560         if Infile is None:
  561             MiscUtil.PrintError("Couldn't open file %s..." % OptionsInfo["Infile"])
  562         Line = Infile.readline()
  563         Infile.close()
  564         
  565         if not re.search("SMILES", Line, re.I):
  566             MiscUtil.PrintError("The input file, %s, must contain a title line containing a column name with SMILES in its name." % OptionsInfo["Infile"])
  567     
  568     if MiscUtil.CheckFileExt(OptionsInfo["Infile"],"sdf sd smi"):
  569         ValidMols, MolCount, ValidMolCount  = RDKitUtil.ReadAndValidateMolecules(OptionsInfo["Infile"], **OptionsInfo["InfileParams"])
  570     else:
  571         ValidMols, MolCount, ValidMolCount  = RetrieveMoleculesFromTextFile(OptionsInfo["Infile"])
  572     
  573     MiscUtil.PrintInfo("Total number of molecules: %d" % MolCount)
  574     MiscUtil.PrintInfo("Number of valid molecules: %d" % ValidMolCount)
  575     MiscUtil.PrintInfo("Number of ignored molecules: %d" % (MolCount - ValidMolCount))
  576 
  577     return ValidMols
  578 
  579 def RetrieveMoleculesFromTextFile(Infile):
  580     """Retrieve molecules from a CSV/TSV text file."""
  581 
  582     # Read and parse text lines...
  583     Delimiter = "," if MiscUtil.CheckFileExt(Infile ,"csv") else "\t"
  584     QuoteChar = '"'
  585     IgnoreHeaderLine = False
  586     TextLinesWords = MiscUtil.GetTextLinesWords(Infile, Delimiter, QuoteChar, IgnoreHeaderLine)
  587 
  588     # Process column names...
  589     ColNames = TextLinesWords[0]
  590     ColCount = len(ColNames)
  591     
  592     MolColIndex = None
  593     MolDataColIndices = []
  594 
  595     FirstSMILES = True
  596     for ColIndex in range(0, ColCount):
  597         if re.search("SMILES", ColNames[ColIndex], re.I) and FirstSMILES:
  598             MolColIndex = ColIndex
  599             FirstSMILES = False
  600             continue
  601         
  602         MolDataColIndices.append(ColIndex)
  603     
  604     if MolColIndex is None:
  605             MiscUtil.PrintError("The input file, %s, must contain a title line containing a column name with SMILES in its name." % Infile)
  606 
  607     ValidMols = []
  608     MolCount = 0
  609 
  610     Sanitize = OptionsInfo["InfileParams"]["Sanitize"]
  611     
  612     # Process data lines...
  613     for LineIndex in range(1, len(TextLinesWords)):
  614         MolCount += 1
  615         LineWords = TextLinesWords[LineIndex]
  616         if len(LineWords) != ColCount:
  617             MiscUtil.PrintWarning("Ignoring text line number %d: Number of columns, %d, must match number of columns, %d, in title line.\nLine: %s" % (MolCount, len(LineWords), ColCount, Delimiter.join(LineWords)))
  618             continue
  619 
  620         # Process molecule column...
  621         MolSMILES = LineWords[MolColIndex]
  622         Mol = Chem.MolFromSmiles(MolSMILES, sanitize = Sanitize)
  623         if Mol is None:
  624             MiscUtil.PrintWarning("Ignoring text line number %d: SMILES parsing failed\nLine: %s" % (MolCount, Delimiter.join(LineWords)))
  625             continue
  626 
  627         # Process molecule data columns...
  628         for ColIndex in MolDataColIndices:
  629             Name = ColNames[ColIndex]
  630             Value = LineWords[ColIndex]
  631             Mol.SetProp(Name, Value)
  632         
  633         ValidMols.append(Mol)
  634     
  635     ValidMolCount = len(ValidMols)
  636     
  637     return (ValidMols, MolCount, ValidMolCount)
  638 
  639 def IdentifyStructureAndNumericalData(ValidMols):
  640     """Identify structure and alphanumerical data."""
  641 
  642     DataMap = {}
  643     DataMap["DataLabels"] = []
  644     DataMap["DataLabelsMap"] = {}
  645     DataMap["CanonicalDataLabelsMap"] = {}
  646     
  647     DataMap["StructureDataMap"] = {}
  648     DataMap["SMILESDataMap"] = {}
  649 
  650     # Retrieve all possible data labels...
  651     if MiscUtil.CheckFileExt(OptionsInfo["Infile"] ,"smi csv tsv txt"):
  652         # First molecule contains all possible data fields...
  653         Mol = ValidMols[0]
  654         ProcessMolDataLabels(ValidMols[0], DataMap)
  655     else:
  656         # Go over all molecules to identify unique data labels...
  657         MiscUtil.PrintInfo("\nRetrieving unique data labels for data in file %s..." % OptionsInfo["Infile"])
  658         for Mol in ValidMols:
  659             ProcessMolDataLabels(Mol, DataMap)
  660 
  661     return DataMap
  662 
  663 def ProcessMolDataLabels(Mol, DataMap):
  664     """Process data label to identify and track its type"""
  665     
  666     for DataLabel in Mol.GetPropNames(includePrivate = False, includeComputed = False):
  667         if DataLabel in DataMap["DataLabelsMap"]:
  668             continue
  669 
  670         # Track labels...
  671         DataMap["DataLabels"].append(DataLabel)
  672         DataMap["DataLabelsMap"][DataLabel] = DataLabel
  673         DataMap["CanonicalDataLabelsMap"][DataLabel.lower()] = DataLabel
  674         
  675         DataMap["StructureDataMap"][DataLabel] = False
  676         DataMap["SMILESDataMap"][DataLabel] = False
  677         
  678         if re.search("SMILES", DataLabel, re.I):
  679             DataMap["StructureDataMap"][DataLabel] = True
  680             DataMap["SMILESDataMap"][DataLabel] = True
  681 
  682 def ValidateShowMolNameOption(DataMap):
  683     """Validate show molecule name option. """
  684     
  685     if not OptionsInfo["ShowMolName"]:
  686         return
  687 
  688     if not MiscUtil.CheckFileExt(OptionsInfo["Infile"],"sdf sd smi"):
  689         OptionsInfo["ShowMolName"] = False
  690         return
  691 
  692     CanonicalDataLabel = OptionsInfo["ShowMolNameDataLabel"].lower()
  693     if CanonicalDataLabel in DataMap["CanonicalDataLabelsMap"]:
  694         OptionsInfo["ShowMolName"] = False
  695         if not OptionsInfo["ShowMolNameAuto"]:
  696             MiscUtil.PrintWarning("Ignoring \"--showMolName\" option: Data label \"Name\" corresponding to molecule name is already present in input file.")
  697 
  698 def ValidateSpecifiedDataLabels(DataMap):
  699     """Validate data labels used to specify highlighting data. """
  700     
  701     ValidateSpecifiedDataLabelsForHighlightSMARTS(DataMap)
  702     
  703     ValidateSpecifiedDataLabelsForHighlightValues(DataMap)
  704     ValidateSpecifiedDataLabelsForHighlightRanges(DataMap)
  705     ValidateSpecifiedDataLabelsForHighlightClasses(DataMap)
  706     
  707 def ValidateSpecifiedDataLabelsForHighlightSMARTS(DataMap):
  708     """Validate data labels used to specify highlighting SMARTS option. """
  709 
  710     if OptionsInfo["HighlightSMARTSAllMode"]:
  711         return
  712 
  713     for DataLabel in OptionsInfo["HighlightSMARTSDataLabels"]:
  714         if re.match("^Structure$", DataLabel, re.I):
  715             continue
  716         
  717         CanonicalDataLabel = DataLabel.lower()
  718         if not CanonicalDataLabel in DataMap["CanonicalDataLabelsMap"]:
  719             MiscUtil.PrintError("The data label specified, %s, using option \"--highlightSMARTS\" doesn't exist in input file." % DataLabel)
  720         
  721         Label = DataMap["CanonicalDataLabelsMap"][CanonicalDataLabel]
  722         if not DataMap["StructureDataMap"][Label]:
  723             MiscUtil.PrintError("The data label specified, %s, using option \"--highlightSMARTS\" doesn't correspond to structure data: Valid structure data labels: SMILES in data label." % DataLabel)
  724             
  725 def ValidateSpecifiedDataLabelsForHighlightValues(DataMap):
  726     """Validate data labels used to specify highlighting values option. """
  727 
  728     ValidateDataLabels("--highlightValues", DataMap, OptionsInfo["HighlightValuesLabels"])
  729 
  730 def ValidateSpecifiedDataLabelsForHighlightRanges(DataMap):
  731     """Validate data labels used to specify highlighting ranges option. """
  732     
  733     ValidateDataLabels("--highlightRanges", DataMap, OptionsInfo["HighlightRangesLabels"])
  734 
  735 def ValidateSpecifiedDataLabelsForHighlightClasses(DataMap):
  736     """Validate data labels used to specify highlighting classes option. """
  737 
  738     if OptionsInfo["HighlightClassesRules"] is None:
  739         return
  740     
  741     ValidDataLabelsList = []
  742     NotValidDataLabelsList = []
  743     for Label in OptionsInfo["HighlightClassesLabels"]:
  744         ValidCanonicalLabel = None
  745         
  746         for LabelSynonym in OptionsInfo["HighlightClassesSynonymsMap"][Label]:
  747             CanonicalLabel = LabelSynonym.lower()
  748             
  749             # Is this label already in use...
  750             if CanonicalLabel in OptionsInfo["HighlightValuesCanonicalLabelsMap"]:
  751                 MiscUtil.PrintInfo("")
  752                 MiscUtil.PrintWarning("The data label, %s, for class, %s , in option \"--highlightValuesClasses\" has already been used in \"--highlightValues\" option. It'll be ignored during highlighting." % (LabelSynonym, OptionsInfo["HighlightClasses"]))
  753                 continue
  754 
  755             if CanonicalLabel in OptionsInfo["HighlightRangesCanonicalLabelsMap"]:
  756                 MiscUtil.PrintInfo("")
  757                 MiscUtil.PrintWarning("The data label, %s, for class, %s , in option \"--highlightValuesClasses\" has already been used in \"--highlightValuesRanges\" option. It'll be ignored during highlighting." % (LabelSynonym, OptionsInfo["HighlightClasses"]))
  758                 continue
  759             
  760             # Is this label present in input file...
  761             if  CanonicalLabel in DataMap["CanonicalDataLabelsMap"]:
  762                 ValidCanonicalLabel = CanonicalLabel
  763                 break
  764         
  765         if ValidCanonicalLabel is None:
  766             MiscUtil.PrintWarning("The data label or its synonyms - %s - for class, %s , in option \"--highlightValuesClasses\" either don't exist in input file or have already been used for highlighting in option \"--highlightValuesClasses\" or \"--highlightValuesRanges\". It'll be ignored during highlighting." % (MiscUtil.JoinWords(OptionsInfo["HighlightClassesSynonymsMap"][Label], ", "), OptionsInfo["HighlightClasses"]))
  767             NotValidDataLabelsList.append(Label)
  768             continue
  769         
  770         # Track label...
  771         OptionsInfo["HighlightClassesCanonicalLabelsMap"][ValidCanonicalLabel] = Label
  772         ValidDataLabelsList.append(DataMap["CanonicalDataLabelsMap"][ValidCanonicalLabel])
  773 
  774     ValidDataLabelsCount = len(ValidDataLabelsList)
  775     NotValidDataLabelsCount = len(NotValidDataLabelsList)
  776     DataLabelsCount = len(OptionsInfo["HighlightClassesLabels"])
  777     
  778     if ValidDataLabelsCount == 0:
  779         MiscUtil.PrintInfo("")
  780         MiscUtil.PrintWarning("The data labels and their synonyms for class, %s , in option \"--highlightValuesClasses\" either don't exists in input file or have already been used for highlighting in option \"--highlightValuesClasses\" or \"--highlightValuesRanges\". No class highlighting will be performed. Missing data labels:  %s" % (OptionsInfo["HighlightClasses"], MiscUtil.JoinWords(OptionsInfo["HighlightClassesLabels"], ", ")))
  781     elif  ValidDataLabelsCount < DataLabelsCount:
  782         MiscUtil.PrintInfo("")
  783         MiscUtil.PrintWarning("The class, %s, based highlighting specified using \"--highlightValuesClasses\" option will be performed using only, %d, out of, %d, data labels: %s\nThe rest of the data label(s) - %s - either don't exist in the input file or have aready been used for highlighting in option \"--highlightValuesClasses\" or \"--highlightValuesRanges\"." % (OptionsInfo["HighlightClasses"], ValidDataLabelsCount,  DataLabelsCount,  MiscUtil.JoinWords(ValidDataLabelsList, ", "),  MiscUtil.JoinWords(NotValidDataLabelsList, ", ") ))
  784         
  785 def ValidateDataLabels(OptionName, DataMap, DataLabels):
  786     """Validate data labels."""
  787     
  788     for DataLabel in DataLabels:
  789         if re.match("^Structure$", DataLabel, re.I):
  790             MiscUtil.PrintError("The data label specified, %s, using option \"-%s\" must not correspond to structure data. Structure label is not allowed." % (DataLabel, OptionName))
  791             
  792         CanonicalDataLabel = DataLabel.lower()
  793         if not CanonicalDataLabel in DataMap["CanonicalDataLabelsMap"]:
  794             MiscUtil.PrintError("The data label specified, %s, using option \"%s\" doesn't exist in input file." % (DataLabel, OptionName))
  795         
  796         Label = DataMap["CanonicalDataLabelsMap"][CanonicalDataLabel]
  797         if DataMap["StructureDataMap"][Label]:
  798             MiscUtil.PrintError("The data label specified, %s, using option \"%s\" must not correspond to structure data: Valid structure data labels contain \"SMILES\" in their name.." % (DataLabel, OptionName))
  799 
  800 def SetupMolInLineSVGImageTag(Mol, HightlightAtomList):
  801     """Setup a inline SVG image tag for molecule."""
  802 
  803     SVGText = RDKitUtil.GetInlineSVGForMolecule(Mol, OptionsInfo["MolImageWidth"], OptionsInfo["MolImageHeight"], AtomListToHighlight = HightlightAtomList, Base64Encoded = OptionsInfo["MolImageEncoded"])
  804 
  805     if OptionsInfo["MolImageEncoded"]:
  806         SVGInlineImageTag = "img src=\"data:image/svg+xml;base64,\n%s\"" % SVGText
  807     else:
  808         SVGInlineImageTag = "img src=\"data:image/svg+xml;charset=UTF-8,\n%s\"" % SVGText
  809     
  810     return SVGInlineImageTag
  811 
  812 def SetupAtomListToHighlight(Mol, DataLabel):
  813     """Set up atom list to highlight using specified SMARTS patterns."""
  814 
  815     HighlightAtomList = None
  816     if OptionsInfo["HighlightSMARTS"] is None:
  817         return  HighlightAtomList
  818 
  819     if OptionsInfo["HighlightSMARTSAllMode"]:
  820         PatternMol = OptionsInfo["HighlightSMARTSPatternMol"]
  821     else:
  822         CanonicalDataLabel = DataLabel.lower()
  823         if not CanonicalDataLabel in OptionsInfo["HighlightSMARTSCanonicalDataLabelsMap"]:
  824             return  HighlightAtomList
  825         
  826         Label = OptionsInfo["HighlightSMARTSCanonicalDataLabelsMap"][CanonicalDataLabel]
  827         PatternMol = OptionsInfo["HighlightSMARTSPatternMolsMap"][Label]
  828         
  829     # Get matched atom lists and flatten it...
  830     MatchedAtomsLists = Mol.GetSubstructMatches(PatternMol)
  831     MatchedAtoms = [ Atom for AtomsList in MatchedAtomsLists for Atom in AtomsList]
  832 
  833     if len(MatchedAtoms):
  834         HighlightAtomList = MatchedAtoms
  835     
  836     return  HighlightAtomList
  837 
  838 def GetAlphanumeircValueHighlightBackgroundColor(DataLabel, DataValue, DataMap):
  839     """Get background highlight color for a value."""
  840 
  841     BackgroundColor = None
  842     BackgroundColorType = None
  843     
  844     CanonicalDataLabel =DataLabel.lower()
  845     if CanonicalDataLabel in OptionsInfo["HighlightValuesCanonicalLabelsMap"]:
  846         return GetBackgroundColorUsingHighlightValuesMode(DataLabel, DataValue, DataMap)
  847     elif CanonicalDataLabel in OptionsInfo["HighlightRangesCanonicalLabelsMap"]:
  848         return GetBackgroundColorUsingHighlightRangesMode(DataLabel, DataValue, DataMap)
  849     elif CanonicalDataLabel in OptionsInfo["HighlightClassesCanonicalLabelsMap"]:
  850         return GetBackgroundColorUsingHighlightClassesMode(DataLabel, DataValue, DataMap)
  851     elif OptionsInfo["HighlightClassesRandom"]:
  852         return GetBackgroundColorUsingRandomMode(DataLabel, DataValue, DataMap)
  853     
  854     return (BackgroundColor, BackgroundColorType)
  855     
  856 def GetBackgroundColorUsingHighlightValuesMode(DataLabel, DataValue, DataMap):
  857     """Get background highlight color for a value."""
  858 
  859     BackgroundColor = None
  860     BackgroundColorType = None
  861 
  862     CanonicalDataLabel =DataLabel.lower()
  863     if not CanonicalDataLabel in OptionsInfo["HighlightValuesCanonicalLabelsMap"]:
  864         return (BackgroundColor, BackgroundColorType)
  865 
  866     Label = OptionsInfo["HighlightValuesCanonicalLabelsMap"][CanonicalDataLabel]
  867     DataType = OptionsInfo["HighlightValuesTypesMap"][Label]
  868     Criterion = OptionsInfo["HighlightValuesCriteriaMap"][Label]
  869     CriterionValue = OptionsInfo["HighlightValuesCriteriaValuesMap"][Label]
  870 
  871     return GetBackgroundColorForHighlightingValue(DataLabel, DataValue, DataType, Criterion, CriterionValue)
  872     
  873 def GetBackgroundColorUsingHighlightClassesMode(DataLabel, DataValue, DataMap):
  874     """Get background highlight color for a value."""
  875 
  876     BackgroundColor = None
  877     BackgroundColorType = None
  878 
  879     CanonicalDataLabel =DataLabel.lower()
  880     if not CanonicalDataLabel in OptionsInfo["HighlightClassesCanonicalLabelsMap"]:
  881         return (BackgroundColor, BackgroundColorType)
  882 
  883     Label = OptionsInfo["HighlightClassesCanonicalLabelsMap"][CanonicalDataLabel]
  884     DataType = OptionsInfo["HighlightClassesTypesMap"][Label]
  885     Criterion = OptionsInfo["HighlightClassesCriteriaMap"][Label]
  886     CriterionValue = OptionsInfo["HighlightClassesCriteriaValuesMap"][Label]
  887 
  888     return GetBackgroundColorForHighlightingValue(DataLabel, DataValue, DataType, Criterion, CriterionValue)
  889 
  890 def GetBackgroundColorForHighlightingValue(DataLabel, DataValue, DataType, Criterion, CriterionValue):
  891     """Get background color for highlighting a value."""
  892     
  893     ValueOkay = False
  894     if re.match("^numeric$", DataType, re.I):
  895         if not MiscUtil.IsNumber(DataValue):
  896             MiscUtil.PrintWarning("Ignoring data value, %s, for data label, %s, during numeric highlighting: It must be a number" % (DataValue, DataLabel))
  897             return (BackgroundColor, BackgroundColorType)
  898         
  899         DataValue = float(DataValue)
  900         if re.match("^gt$", Criterion, re.I):
  901             ValueOkay = True if DataValue > CriterionValue else False
  902         elif re.match("^lt$", Criterion, re.I):
  903             ValueOkay = True if DataValue < CriterionValue else False
  904         elif re.match("^ge$", Criterion, re.I):
  905             ValueOkay = True if DataValue >= CriterionValue else False
  906         elif re.match("^le$", Criterion, re.I):
  907             ValueOkay = True if DataValue <= CriterionValue else False
  908         elif re.match("^eq$", Criterion, re.I):
  909             ValueOkay = True if DataValue == CriterionValue else False
  910         elif re.match("^ne$", Criterion, re.I):
  911             ValueOkay = True if DataValue != CriterionValue else False
  912         else:
  913             return (BackgroundColor, BackgroundColorType)
  914     elif re.match("^text$", DataType, re.I):
  915         DataValue = "%s" % DataValue
  916         if re.match("^gt$", Criterion, re.I):
  917             ValueOkay = True if DataValue > CriterionValue else False
  918         elif re.match("^lt$", Criterion, re.I):
  919             ValueOkay = True if DataValue < CriterionValue else False
  920         elif re.match("^ge$", Criterion, re.I):
  921             ValueOkay = True if DataValue >= CriterionValue else False
  922         elif re.match("^le$", Criterion, re.I):
  923             ValueOkay = True if DataValue <= CriterionValue else False
  924         elif re.match("^eq$", Criterion, re.I):
  925             ValueOkay = True if DataValue == CriterionValue else False
  926         elif re.match("^ne$", Criterion, re.I):
  927             ValueOkay = True if DataValue != CriterionValue else False
  928         else:
  929             return (BackgroundColor, BackgroundColorType)
  930     elif re.match("^regex$", DataType, re.I):
  931         DataValue = "%s" % DataValue
  932         if re.match("^eq$", Criterion, re.I):
  933             ValueOkay = True if re.search("%s" % CriterionValue, DataValue, re.I) else False
  934         elif re.match("^ne$", Criterion, re.I):
  935             ValueOkay = False if re.search("%s" % CriterionValue, DataValue, re.I) else True
  936         else:
  937             return (BackgroundColor, BackgroundColorType)
  938 
  939     BackgroundColor = OptionsInfo["HighlightColorsList"][0] if ValueOkay else OptionsInfo["HighlightColorsList"][1]
  940     BackgroundColorType = OptionsInfo["HighlightColorsType"]
  941     
  942     return (BackgroundColor, BackgroundColorType)
  943 
  944 def GetBackgroundColorUsingHighlightRangesMode(DataLabel, DataValue, DataMap):
  945     """Get background highlight color for value range."""
  946 
  947     BackgroundColor = None
  948     BackgroundColorType = None
  949 
  950     CanonicalDataLabel =DataLabel.lower()
  951     if not CanonicalDataLabel in OptionsInfo["HighlightRangesCanonicalLabelsMap"]:
  952         return (BackgroundColor, BackgroundColorType)
  953 
  954     Label = OptionsInfo["HighlightRangesCanonicalLabelsMap"][CanonicalDataLabel]
  955     DataType = OptionsInfo["HighlightRangesTypesMap"][Label]
  956     CriterionLower = OptionsInfo["HighlightRangesCriteriaLowerMap"][Label]
  957     CriterionLowerValue = OptionsInfo["HighlightRangesCriteriaLowerValuesMap"][Label]
  958     CriterionUpper = OptionsInfo["HighlightRangesCriteriaUpperMap"][Label]
  959     CriterionUpperValue = OptionsInfo["HighlightRangesCriteriaUpperValuesMap"][Label]
  960     
  961     if re.match("^numeric$", DataType, re.I):
  962         if not MiscUtil.IsNumber(DataValue):
  963             MiscUtil.PrintWarning("Ignoring data value, %s, for data label, %s, during numeric highlighting: It must be a number" % (DataValue, DataLabel))
  964             return (BackgroundColor, BackgroundColorType)
  965         
  966         DataValue = float(DataValue)
  967         ColorIndex = 1
  968         
  969         if DataValue < CriterionLowerValue and re.match("^lt$", CriterionLower, re.I):
  970             ColorIndex = 0
  971         elif DataValue <= CriterionLowerValue and re.match("^le$", CriterionLower, re.I):
  972             ColorIndex = 0
  973         elif DataValue > CriterionUpperValue and re.match("^gt$", CriterionUpper, re.I):
  974             ColorIndex = 2
  975         elif DataValue >= CriterionUpperValue and re.match("^ge$", CriterionUpper, re.I):
  976             ColorIndex = 2
  977     elif re.match("^text$", DataType, re.I):
  978         DataValue = "%s" % DataValue
  979         ColorIndex = 1
  980         
  981         if DataValue < CriterionLowerValue and re.match("^lt$", CriterionLower, re.I):
  982             ColorIndex = 0
  983         elif DataValue <= CriterionLowerValue and re.match("^le$", CriterionLower, re.I):
  984             ColorIndex = 0
  985         elif DataValue > CriterionUpperValue and re.match("^gt$", CriterionUpper, re.I):
  986             ColorIndex = 2
  987         elif DataValue >= CriterionUpperValue and re.match("^ge$", CriterionUpper, re.I):
  988             ColorIndex = 2
  989     else:
  990         return (BackgroundColor, BackgroundColorType)
  991 
  992     BackgroundColor = OptionsInfo["HighlightColorsRangesList"][ColorIndex]
  993     BackgroundColorType = OptionsInfo["HighlightColorsRangesType"]
  994     
  995     return (BackgroundColor, BackgroundColorType)
  996 
  997 def GetBackgroundColorUsingRandomMode(DataLabel, DataValue, DataMap):
  998     """Get a random background highlight color for a value."""
  999 
 1000     BackgroundColor = random.choice(OptionsInfo["HighlightColorsRandomList"])
 1001     BackgroundColorType = OptionsInfo["HighlightColorsRandomType"]
 1002     
 1003     return (BackgroundColor, BackgroundColorType)
 1004     
 1005 def SetupAlphanumericTableDataValue(Writer, DataValue, BackgroundColor, BackgroundColorType):
 1006     """Set up alphanumeric data value for a table cell."""
 1007     
 1008     WrappedDataValue = "%s" % DataValue
 1009 
 1010     # Look for new lines...
 1011     Delim = "<br/>"
 1012     if re.search("(\r\n|\r|\n)", WrappedDataValue):
 1013         WrappedDataValue = re.sub("(\r\n|\r|\n)", "<br/>", DataValue)
 1014 
 1015     # Wrap text...
 1016     if OptionsInfo["WrapText"] and len(WrappedDataValue) > OptionsInfo["WrapTextWidth"]:
 1017         WrappedDataLines = []
 1018         for DataLine in WrappedDataValue.split("<br/>"):
 1019             WrappedDataLine = MiscUtil.WrapText(DataLine, "<br/>", OptionsInfo["WrapTextWidth"])
 1020             WrappedDataLines.append(WrappedDataLine)
 1021         
 1022         WrappedDataValue = "<br/>".join(WrappedDataLines)
 1023     
 1024     # Highlight value...
 1025     if BackgroundColor is not None:
 1026         ColorTypeTag = GetBackgroundColorTypeTagForTableValue(BackgroundColor, BackgroundColorType)
 1027         Writer.write("""            <td %s = "%s">%s</td>\n""" % (ColorTypeTag, BackgroundColor, WrappedDataValue))
 1028     else:
 1029         Writer.write("""            <td>%s</td>\n""" % WrappedDataValue)
 1030 
 1031 def GetBackgroundColorTypeTagForTableValue(Color, ColorType):
 1032     """Setup color type tage for setting background of a table value."""
 1033 
 1034     ColorTypeTag = "class" if re.match("^colorclass", ColorType, re.I) else "bgcolor"
 1035     
 1036     return ColorTypeTag
 1037     
 1038 def PerformAlignment(ValidMols):
 1039     """Perform alignment to a common template specified by a SMARTS pattern."""
 1040     
 1041     if OptionsInfo["AlignmentSMARTSPattern"] is None:
 1042         return
 1043     
 1044     MiscUtil.PrintInfo("\nPerforming alignment for primary structure data...")
 1045     
 1046     PatternMol = Chem.MolFromSmarts(OptionsInfo["AlignmentSMARTSPattern"])
 1047     AllChem.Compute2DCoords(PatternMol)
 1048         
 1049     MatchedValidMols = [ValidMol for ValidMol in ValidMols if ValidMol.HasSubstructMatch(PatternMol)]
 1050     for ValidMol in MatchedValidMols:
 1051         AllChem.GenerateDepictionMatching2DStructure(ValidMol, PatternMol)
 1052 
 1053 def ProcessHighlightSMARTSOption():
 1054     """Process highlight SMARTS option"""
 1055 
 1056     OptionsInfo["HighlightSMARTS"]  = None
 1057     OptionsInfo["HighlightSMARTSAllMode"]  = False
 1058     OptionsInfo["HighlightSMARTSPatternMol"]  = None
 1059     
 1060     OptionsInfo["HighlightSMARTSDataLabels"]  = []
 1061     OptionsInfo["HighlightSMARTSDataLabelsMap"]  = {}
 1062     
 1063     OptionsInfo["HighlightSMARTSCanonicalDataLabelsMap"]  = {}
 1064     OptionsInfo["HighlightSMARTSPatternsMap"]  = {}
 1065     OptionsInfo["HighlightSMARTSPatternMolsMap"]  = {}
 1066 
 1067     if re.match("^None$", Options["--highlightSMARTS"], re.I):
 1068         # Nothing to proecess...
 1069         return
 1070     
 1071     HighlightSMARTS = Options["--highlightSMARTS"].strip()
 1072     if not HighlightSMARTS:
 1073         MiscUtil.PrintError("No valid values specified using \"--highlightSMARTS\" option.")
 1074 
 1075     OptionsInfo["HighlightSMARTS"]  = HighlightSMARTS
 1076     HighlightSMARTSWords = HighlightSMARTS.split(",")
 1077 
 1078     if len(HighlightSMARTSWords) == 1:
 1079         PatternMol = Chem.MolFromSmarts(HighlightSMARTS)
 1080         if PatternMol is None:
 1081             MiscUtil.PrintError("The value specified, %s, using option \"--highlightSMARTS\" is not a valid SMARTS: Failed to create pattern molecule" % Options["--highlightSMARTS"])
 1082         OptionsInfo["HighlightSMARTSAllMode"]  = True
 1083         OptionsInfo["HighlightSMARTSPatternMol"]  = PatternMol
 1084         return
 1085     
 1086     if len(HighlightSMARTSWords) % 2:
 1087         MiscUtil.PrintError("The number of comma delimited paramater names and values, %d, specified using \"--highlightSMARTS\" option must be an even number." % (len(HighlightSMARTSWords)))
 1088     
 1089     HighlightSMARTSAllMode = False
 1090             
 1091     for Index in range(0, len(HighlightSMARTSWords), 2):
 1092         DataLabel = HighlightSMARTSWords[Index].strip()
 1093         SMARTSPattern = HighlightSMARTSWords[Index + 1].strip()
 1094                 
 1095         PatternMol = Chem.MolFromSmarts(SMARTSPattern)
 1096         if PatternMol is None:
 1097             MiscUtil.PrintError("The value specified, %s, using option \"--highlightSMARTS\" is not a valid SMARTS: Failed to create pattern molecule" % Options["--highlightSMARTS"])
 1098 
 1099         if DataLabel in OptionsInfo["HighlightSMARTSDataLabelsMap"]:
 1100             MiscUtil.PrintError("The datalabel, %s, specified in pair, \"%s, %s\", using option \"--highlightSMARTS\" is not a valid: Multiple occurences of data label" % (DataLabel, DataLabel, SMARTSPattern))
 1101             
 1102         OptionsInfo["HighlightSMARTSDataLabels"].append(DataLabel)
 1103         OptionsInfo["HighlightSMARTSDataLabelsMap"][DataLabel] = DataLabel
 1104         OptionsInfo["HighlightSMARTSCanonicalDataLabelsMap"][DataLabel.lower()] = DataLabel
 1105         OptionsInfo["HighlightSMARTSPatternsMap"][DataLabel] = SMARTSPattern
 1106         OptionsInfo["HighlightSMARTSPatternMolsMap"][DataLabel] = PatternMol
 1107 
 1108 def ProcessHighlightDataOptions():
 1109     """Process highlight values and colors option"""
 1110     
 1111     ProcessHighlightValuesOption()
 1112     ProcessHighlightValuesRangesOption()
 1113     ProcessHighlightValuesClassesOption()
 1114     
 1115     ProcessHighlightColorsOption()
 1116     ProcessHighlightColorsRangesOption()
 1117     ProcessHighlightColorsRandomOption()
 1118 
 1119 def ProcessHighlightValuesOption():
 1120     """Process highlight values option"""
 1121 
 1122     OptionsInfo["HighlightValues"]  = None
 1123     OptionsInfo["HighlightValuesLabels"]  = []
 1124     
 1125     OptionsInfo["HighlightValuesLabelsMap"]  = {}
 1126     OptionsInfo["HighlightValuesCanonicalLabelsMap"]  = {}
 1127     
 1128     OptionsInfo["HighlightValuesTypesMap"]  = {}
 1129     OptionsInfo["HighlightValuesCriteriaMap"]  = {}
 1130     OptionsInfo["HighlightValuesCriteriaValuesMap"]  = {}
 1131 
 1132     HighlightValues = Options["--highlightValues"].strip()
 1133     if re.match("^None$", HighlightValues, re.I):
 1134         return
 1135     
 1136     OptionsInfo["HighlightValues"]  = HighlightValues
 1137     HighlightValuesWords = HighlightValues.split(",")
 1138     
 1139     if len(HighlightValuesWords) % 4:
 1140         MiscUtil.PrintError("The number of comma delimited paramater names and values, %d, specified using \"--highlightValues\" option must be a multiple of 4." % (len(HighlightValuesWords)))
 1141 
 1142     for Index in range(0, len(HighlightValuesWords), 4):
 1143         DataLabel = HighlightValuesWords[Index].strip()
 1144         DataType = HighlightValuesWords[Index + 1].strip()
 1145         DataCriterion = HighlightValuesWords[Index + 2].strip()
 1146         DataValue = HighlightValuesWords[Index + 3].strip()
 1147         
 1148         if not re.match("^(numeric|text|regex)$", DataType, re.I):
 1149             MiscUtil.PrintError("The data type, %s, specified in quratet \"%s,%s,%s,%s\", using \"--highlightValues\" option is not valid. Supported values: numeric, regex or text." % (DataType, DataLabel, DataType, DataCriterion, DataValue))
 1150         
 1151         if re.match("^regex$", DataType, re.I):
 1152             if not re.match("^(eq|ne)$", DataCriterion, re.I):
 1153                 MiscUtil.PrintError("The data criterion, %s, specified in quratet \"%s,%s,%s,%s\", using \"--highlightValues\" option is not valid. Supported values: eq or ne" % (DataType, DataLabel, DataType, DataCriterion, DataValue))
 1154         else:
 1155             if not re.match("^(gt|lt|ge|le|eq|ne)$", DataCriterion, re.I):
 1156                 MiscUtil.PrintError("The data criterion, %s, specified in quratet \"%s,%s,%s,%s\", using \"--highlightValues\" option is not valid. Supported values: gt, lt, ge, le, eq, or  ne." % (DataType, DataLabel, DataType, DataCriterion, DataValue))
 1157 
 1158         # Check criterion value...
 1159         if re.match("^numeric$", DataType, re.I):
 1160             if not MiscUtil.IsNumber(DataValue):
 1161                 MiscUtil.PrintError("The data value, %s, specified in quratet \"%s,%s,%s,%s\", using \"--highlightValues\" option is not valid. It must be a number for data type, %s" % (DataType, DataLabel, DataType, DataCriterion, DataValue, DataType))
 1162             DataValue = float(DataValue)
 1163         
 1164         # Track values...
 1165         if DataLabel in OptionsInfo["HighlightValuesLabelsMap"]:
 1166             MiscUtil.PrintError("The data label, %s, specified in quratet \"%s,%s,%s,%s\", using \"--highlightValues\" option is not valid: Multiple occurences of data label" % (DataLabel, DataLabel, DataType, DataCriterion, DataValue))
 1167 
 1168         OptionsInfo["HighlightValuesLabels"].append(DataLabel)
 1169         OptionsInfo["HighlightValuesLabelsMap"][DataLabel]  = DataLabel
 1170         OptionsInfo["HighlightValuesCanonicalLabelsMap"][DataLabel.lower()]  = DataLabel
 1171         
 1172         OptionsInfo["HighlightValuesTypesMap"][DataLabel]  = DataType
 1173         OptionsInfo["HighlightValuesCriteriaMap"][DataLabel]  = DataCriterion 
 1174         OptionsInfo["HighlightValuesCriteriaValuesMap"][DataLabel]  = DataValue
 1175 
 1176 def ProcessHighlightValuesRangesOption():
 1177     """Process highlight values ranges option"""
 1178     
 1179     OptionsInfo["HighlightRanges"]  = None
 1180     OptionsInfo["HighlightRangesLabels"]  = []
 1181     
 1182     OptionsInfo["HighlightRangesLabelsMap"]  = {}
 1183     OptionsInfo["HighlightRangesCanonicalLabelsMap"]  = {}
 1184     
 1185     OptionsInfo["HighlightRangesTypesMap"]  = {}
 1186     OptionsInfo["HighlightRangesCriteriaLowerMap"]  = {}
 1187     OptionsInfo["HighlightRangesCriteriaLowerValuesMap"]  = {}
 1188     OptionsInfo["HighlightRangesCriteriaUpperMap"]  = {}
 1189     OptionsInfo["HighlightRangesCriteriaUpperValuesMap"]  = {}
 1190 
 1191     HighlightRanges = Options["--highlightValuesRanges"].strip()
 1192     if re.match("^None$", HighlightRanges, re.I):
 1193         return
 1194     
 1195     OptionsInfo["HighlightRanges"]  = HighlightRanges
 1196     HighlightRangesWords = HighlightRanges.split(",")
 1197     
 1198     if len(HighlightRangesWords) % 6:
 1199         MiscUtil.PrintError("The number of comma delimited paramater names and values, %d, specified in sextet \"%s\" using \"--highlightValuesRanges\" option must be a multiple of 6." % (len(HighlightRangesWords), HighlightRanges))
 1200 
 1201     for Index in range(0, len(HighlightRangesWords), 6):
 1202         DataLabel = HighlightRangesWords[Index].strip()
 1203         DataType = HighlightRangesWords[Index + 1].strip()
 1204         LowerBoundDataCriterion = HighlightRangesWords[Index + 2].strip()
 1205         LowerBoundDataValue = HighlightRangesWords[Index + 3].strip()
 1206         UpperBoundDataCriterion = HighlightRangesWords[Index + 4].strip()
 1207         UpperBoundDataValue = HighlightRangesWords[Index + 5].strip()
 1208 
 1209         SpecifiedSextet = "%s,%s,%s,%s,%s,%s" % (DataLabel, DataType, LowerBoundDataCriterion, LowerBoundDataValue, UpperBoundDataCriterion, UpperBoundDataValue)
 1210 
 1211         CanonicalDataLabel = DataLabel.lower()
 1212         if CanonicalDataLabel in OptionsInfo["HighlightValuesCanonicalLabelsMap"]:
 1213             MiscUtil.PrintError("The data label specified, %s, using option \"--highlightRanges\" has already been used in \"--highlightValues\" option" % DataLabel)
 1214         
 1215         if not re.match("^(numeric|text)$", DataType, re.I):
 1216             MiscUtil.PrintError("The data type, %s, specified in sextet \"%s\" using \"--highlightValuesRanges\" option is not valid. Supported values: numeric text." % (DataType, SpecifiedSextet))
 1217         
 1218         if not re.match("^(lt|le)$", LowerBoundDataCriterion, re.I):
 1219             MiscUtil.PrintError("The lower bound criterion, %s, specified in sextet \"%s\" using \"--highlightValuesRanges\" option is not valid. Supported values: lt or le." % (LowerBoundDataCriterion, SpecifiedSextet))
 1220         
 1221         if not re.match("^(gt|ge)$", UpperBoundDataCriterion, re.I):
 1222             MiscUtil.PrintError("The upper bound criterion, %s, specified in sextet \"%s\" using \"--highlightValuesRanges\" option is not valid. Supported values: gt or ge." % (UpperBoundDataCriterion, SpecifiedSextet))
 1223 
 1224         if re.match("^numeric$", DataType, re.I):
 1225             if not MiscUtil.IsNumber(LowerBoundDataValue):
 1226                 MiscUtil.PrintError("The lower bound data value, %s, specified in sextet \"%s\", using \"--highlightValuesRanges\" option is not valid. It must be a number for \"%s\" data type." % (LowerBoundDataValue, SpecifiedSextet, DataType))
 1227             
 1228             if not MiscUtil.IsNumber(UpperBoundDataValue):
 1229                 MiscUtil.PrintError("The upper bound data value, %s, specified in sextet \"%s\", using \"--highlightValuesRanges\" option is not valid. It must be a number for \"%s\"data type." % (UpperBoundDataValue, SpecifiedSextet, DataType))
 1230             
 1231             if float(LowerBoundDataValue) >= float(UpperBoundDataValue):
 1232                 MiscUtil.PrintError("The lower bound data value, %s, must be less than upper bound value, %s, specified in sextet \"%s\" using \"--highlightValuesRanges\" option." % (LowerBoundDataValue, UpperBoundDataValue,  SpecifiedSextet))
 1233             
 1234             LowerBoundDataValue = float(LowerBoundDataValue)
 1235             UpperBoundDataValue = float(UpperBoundDataValue)
 1236         else:
 1237             if LowerBoundDataValue >= UpperBoundDataValue:
 1238                 MiscUtil.PrintError("The lower bound data value, %s, must be less than upper bound value, %s, specified in sextet \"%s\", using \"--highlightValuesRanges\" option is not valid. It must be a number for data type, %s" % (LowerBoundDataValue, UpperBoundDataValue,  SpecifiedSextet, DataType))
 1239 
 1240         # Track values...
 1241         if DataLabel in OptionsInfo["HighlightRangesLabelsMap"]:
 1242             MiscUtil.PrintError("The data label, %s, specified in sextet \"%s\", using \"--highlightValuesRanges\" option is not valid. Multiple occurences of data label" % (DataLabel, SpecifiedSextet))
 1243 
 1244         OptionsInfo["HighlightRangesLabels"].append(DataLabel)
 1245         OptionsInfo["HighlightRangesLabelsMap"][DataLabel]  = DataLabel
 1246         OptionsInfo["HighlightRangesCanonicalLabelsMap"][CanonicalDataLabel]  = DataLabel
 1247         
 1248         OptionsInfo["HighlightRangesTypesMap"][DataLabel]  = DataType
 1249         
 1250         OptionsInfo["HighlightRangesCriteriaLowerMap"][DataLabel]  = LowerBoundDataCriterion 
 1251         OptionsInfo["HighlightRangesCriteriaLowerValuesMap"][DataLabel]  = LowerBoundDataValue
 1252         OptionsInfo["HighlightRangesCriteriaUpperMap"][DataLabel]  = UpperBoundDataCriterion 
 1253         OptionsInfo["HighlightRangesCriteriaUpperValuesMap"][DataLabel]  = UpperBoundDataValue
 1254 
 1255 def ProcessHighlightValuesClassesOption():
 1256     """Process highlight values classes option"""
 1257     
 1258     OptionsInfo["HighlightClasses"]  = None
 1259     OptionsInfo["HighlightClassesRules"]  = None
 1260     OptionsInfo["HighlightClassesSynonymsMap"]  = None
 1261     OptionsInfo["HighlightClassesRandom"]  = False
 1262 
 1263     OptionsInfo["HighlightClassesLabels"]  = []
 1264     OptionsInfo["HighlightClassesLabelsMap"]  = {}
 1265     OptionsInfo["HighlightClassesCanonicalLabelsMap"]  = {}
 1266     
 1267     OptionsInfo["HighlightClassesTypesMap"]  = {}
 1268     OptionsInfo["HighlightClassesCriteriaMap"]  = {}
 1269     OptionsInfo["HighlightClassesCriteriaValuesMap"]  = {}
 1270     
 1271     HighlightClasses = Options["--highlightValuesClasses"].strip()
 1272     if re.match("^None$", HighlightClasses, re.I):
 1273         return
 1274 
 1275     OptionsInfo["HighlightClasses"]  = HighlightClasses
 1276     
 1277     if re.match("^RuleOf5$", HighlightClasses, re.I):
 1278         HighlightClassessRules = "MolecularWeight,numeric,le,500,HydrogenBondDonors,numeric,le,5,HydrogenBondAcceptors,numeric,le,10,LogP,numeric,le,5"
 1279     elif re.match("^RuleOf3$", HighlightClasses, re.I):
 1280         HighlightClassessRules = "MolecularWeight,numeric,le,300,HydrogenBondDonors,numeric,le,3,HydrogenBondAcceptors,numeric,le,3,LogP,numeric,le,3,RotatableBonds,numeric,le,3,TPSA,numeric,le,60"
 1281     elif re.match("^DrugLike$", HighlightClasses, re.I):
 1282         HighlightClassessRules = "MolecularWeight,numeric,le,500,HydrogenBondDonors,numeric,le,5,HydrogenBondAcceptors,numeric,le,10,LogP,numeric,le,5,RotatableBonds,numeric,le,10,TPSA,numeric,le,140"
 1283     elif re.match("^Random$", HighlightClasses, re.I):
 1284         if OptionsInfo["HighlightValues"] is not None:
 1285             MiscUtil.PrintError("The value specified, %s, using option \"--highlightValuesClasses\" is not allowed in conjunction with \"--highlightValues\" option." % HighlightClasses)
 1286         if OptionsInfo["HighlightRanges"] is not None:
 1287             MiscUtil.PrintError("The value specified, %s, using option \"--highlightValuesClasses\" is not allowed in conjunction with \"--highlightRanges\" option ." % HighlightClasses)
 1288             
 1289         OptionsInfo["HighlightClassesRandom"]  = True
 1290         return
 1291     else:
 1292         MiscUtil.PrintError("The value specified, %d, using option \"--highlightValuesClasses\" is not supported." % HighlightClasses)
 1293         return
 1294         
 1295     OptionsInfo["HighlightClassesRules"]  = HighlightClassessRules
 1296 
 1297     # Process rules for highlighting values...
 1298     HighlightClassesWords = HighlightClassessRules.split(",")
 1299     for Index in range(0, len(HighlightClassesWords), 4):
 1300         DataLabel = HighlightClassesWords[Index].strip()
 1301         DataType = HighlightClassesWords[Index + 1].strip()
 1302         DataCriterion = HighlightClassesWords[Index + 2].strip()
 1303         DataValue = HighlightClassesWords[Index + 3].strip()
 1304         
 1305         DataValue = float(DataValue)
 1306 
 1307         if DataLabel in OptionsInfo["HighlightClassesLabelsMap"]:
 1308             MiscUtil.PrintWarning("Ignoring duplicate datalabel, %s, specified in highlighting values rule for class, %s, in \"--highlightClassesValue\" option..." % (DataLabel, HighlightClasses))
 1309             continue
 1310             
 1311         OptionsInfo["HighlightClassesLabels"].append(DataLabel)
 1312         OptionsInfo["HighlightClassesLabelsMap"][DataLabel] = DataLabel
 1313         
 1314         OptionsInfo["HighlightClassesTypesMap"][DataLabel] = DataType
 1315         OptionsInfo["HighlightClassesCriteriaMap"][DataLabel] = DataCriterion
 1316         OptionsInfo["HighlightClassesCriteriaValuesMap"][DataLabel] = DataValue
 1317     
 1318     # Set up synonyms for data labels corresponding to physicochemical properties
 1319     # calculated by MayaChemTools and RDKit...
 1320     OptionsInfo["HighlightClassesSynonymsMap"]  = {}
 1321     OptionsInfo["HighlightClassesSynonymsMap"]["MolecularWeight"]  = ["MolecularWeight", "MolWt"]
 1322     OptionsInfo["HighlightClassesSynonymsMap"]["HydrogenBondDonors"]  = ["HydrogenBondDonors", "NHOHCount"]
 1323     OptionsInfo["HighlightClassesSynonymsMap"]["HydrogenBondAcceptors"]  = ["HydrogenBondAcceptors", "NOCount"]
 1324     OptionsInfo["HighlightClassesSynonymsMap"]["LogP"]  = ["SLogP", "MolLogP"]
 1325     OptionsInfo["HighlightClassesSynonymsMap"]["RotatableBonds"]  = ["RotatableBonds", "NumRotatableBonds"]
 1326     OptionsInfo["HighlightClassesSynonymsMap"]["TPSA"]  = ["TPSA", "TPSA"]
 1327 
 1328 def ProcessHighlightColorsOption():
 1329     """Process highlight colors option"""
 1330 
 1331     OptionsInfo["HighlightColors"] = None
 1332     OptionsInfo["HighlightColorsType"] = None
 1333     OptionsInfo["HighlightColorsList"] = None
 1334 
 1335     HighlightColors = "colorclass,table-success, table-danger"
 1336     if not re.match("^auto$", Options["--highlightColors"], re.I):
 1337         HighlightColors = Options["--highlightColors"].strip()
 1338         if MiscUtil.IsEmpty(HighlightColors):
 1339             MiscUtil.PrintError("The value specified using \"--highlightColors\" is empty.")
 1340 
 1341     OptionsInfo["HighlightColors"] = re.sub(" ", "", HighlightColors)
 1342     HighlightColorsList = [Color.lower() for Color in OptionsInfo["HighlightColors"].split(",")]
 1343         
 1344     if len(HighlightColorsList) != 3:
 1345         MiscUtil.PrintError("The number of comma delimited paramater names and values, %d, specified using \"--highlightColors\" option must be 3." % (len(HighlightColorsList)))
 1346         
 1347     ColorsType, Color1, Color2 = HighlightColorsList
 1348     if not re.match("^(colorclass|colorspec)$", ColorsType, re.I):
 1349         MiscUtil.PrintError("The color type, %s, specified using \"--highlightColors\" option is not valid. Supported values: colorclass or colorspec." % ColorsType)
 1350 
 1351     ColorsList = [Color1, Color2]
 1352     if re.match("^colorclass$", ColorsType, re.I):
 1353         CheckOptionTableClassColorValues("--highlightColors", ColorsList)
 1354         
 1355     OptionsInfo["HighlightColorsList"] = ColorsList
 1356     OptionsInfo["HighlightColorsType"] = ColorsType
 1357 
 1358 def ProcessHighlightColorsRangesOption():
 1359     """Process highlight colors ranges option"""
 1360 
 1361     OptionsInfo["HighlightColorsRanges"] = None
 1362     OptionsInfo["HighlightColorsRangesType"] = None
 1363     OptionsInfo["HighlightColorsRangesList"] = None
 1364 
 1365     HighlightColors = "colorclass,table-success, table-warning, table-danger"
 1366     if not re.match("^auto$", Options["--highlightColorsRanges"], re.I):
 1367         HighlightColors = Options["--highlightColorsRanges"].strip()
 1368         if MiscUtil.IsEmpty(HighlightColors):
 1369             MiscUtil.PrintError("The value specified using \"--highlightColorsRanges\" is empty.")
 1370 
 1371     OptionsInfo["HighlightColorsRanges"] = re.sub(" ", "", HighlightColors)
 1372     HighlightColorsList = [Color.lower() for Color in OptionsInfo["HighlightColorsRanges"].split(",")]
 1373         
 1374     if len(HighlightColorsList) != 4:
 1375         MiscUtil.PrintError("The number of comma delimited paramater names and values, %d, specified using \"--highlightColorsRanges\" option must be 4." % (len(HighlightColorsList)))
 1376     
 1377     ColorsType, Color1, Color2, Color3 = HighlightColorsList
 1378     if not re.match("^(colorclass|colorspec)$", ColorsType, re.I):
 1379         MiscUtil.PrintError("The color type, %s, specified using \"--highlightColorsRanges\" option is not valid. Supported values: colorclass or colorspec." % ColorsType)
 1380     
 1381     ColorsList = [Color1, Color2, Color3]
 1382     if re.match("^colorclass$", ColorsType, re.I):
 1383         CheckOptionTableClassColorValues("--highlightColorsRanges", ColorsList)
 1384     
 1385     OptionsInfo["HighlightColorsRangesList"] = ColorsList
 1386     OptionsInfo["HighlightColorsRangesType"] = ColorsType
 1387 
 1388 def ProcessHighlightColorsRandomOption():
 1389     """Process highlight colors random option"""
 1390 
 1391     OptionsInfo["HighlightColorsRandom"] = None
 1392     OptionsInfo["HighlightColorsRandomType"] = None
 1393     OptionsInfo["HighlightColorsRandomList"] = None
 1394 
 1395     HighlightColors = "colorclass,table-primary,table-success,table-danger,table-info,table-warning,table-secondary"
 1396     if not re.match("^auto$", Options["--highlightColorsRandom"], re.I):
 1397         HighlightColors = Options["--highlightColorsRandom"].strip()
 1398         if MiscUtil.IsEmpty(HighlightColors):
 1399             MiscUtil.PrintError("The value specified using \"--highlightColorsRandom\" is empty.")
 1400 
 1401     OptionsInfo["HighlightColorsRandom"] = re.sub(" ", "", HighlightColors)
 1402     HighlightColorsList = [Color.lower() for Color in OptionsInfo["HighlightColorsRandom"].split(",")]
 1403         
 1404     if len(HighlightColorsList) <= 1:
 1405         MiscUtil.PrintError("The number of comma delimited paramater names and values, %d, specified using \"--highlightColorsRandom\" option must be > 1." % (len(HighlightColorsList)))
 1406         
 1407     ColorsType = HighlightColorsList[0]
 1408     ColorsList = HighlightColorsList[1:]
 1409     
 1410     if not re.match("^(colorclass|colorspec)$", ColorsType, re.I):
 1411         MiscUtil.PrintError("The color type, %s, specified using \"--highlightColorsRandim\" option is not valid. Supported values: colorclass or colorspec." % ColorsType)
 1412 
 1413     if re.match("^colorclass$", ColorsType, re.I):
 1414         CheckOptionTableClassColorValues("--highlightColorsRandom", ColorsList)
 1415         
 1416     OptionsInfo["HighlightColorsRandomList"] = ColorsList
 1417     OptionsInfo["HighlightColorsRandomType"] = ColorsType
 1418 
 1419 def CheckOptionTableClassColorValues(OptionName, ColorsList):
 1420     """Check names of table color classes and issue a warning for unknown names."""
 1421 
 1422     TableClassColors = ["thead-dark", "thead-light", "table-primary", "table-success", "table-danger", "table-info", "table-warning", "table-active", "table-secondary", "table-light", "table-dark", "bg-primary", "bg-success", "bg-danger",  "bg-info", "bg-warning", "bg-secondary", "bg-dark", "bg-light"]
 1423 
 1424     for Color in ColorsList:
 1425         if not Color in TableClassColors:
 1426             MiscUtil.PrintWarning("The color class name, %s, specified using option \"%s\" appears to be a unknown name..." % (Color, OptionName))
 1427         
 1428 def ProcessOptions():
 1429     """Process and validate command line arguments and options"""
 1430     
 1431     MiscUtil.PrintInfo("Processing options...")
 1432     
 1433     # Validate options...
 1434     ValidateOptions()
 1435     
 1436     OptionsInfo["Infile"] = Options["--infile"]
 1437     OptionsInfo["Outfile"] = Options["--outfile"]
 1438     OptionsInfo["Overwrite"] = Options["--overwrite"]
 1439     
 1440     # No need for any RDKit specific --outfileParams....
 1441     OptionsInfo["InfileParams"] = MiscUtil.ProcessOptionInfileParameters("--infileParams", Options["--infileParams"], OptionsInfo["Infile"])
 1442 
 1443     AlignmentSMARTSPattern = None
 1444     if not re.match("^None$", Options["--alignmentSMARTS"], re.I):
 1445         AlignmentSMARTSPattern = Options["--alignmentSMARTS"]
 1446     OptionsInfo["AlignmentSMARTSPattern"]  = AlignmentSMARTSPattern
 1447     
 1448     Compute2DCoords = True
 1449     if re.match("^no$", Options["--compute2DCoords"], re.I):
 1450         Compute2DCoords = False
 1451     OptionsInfo["Compute2DCoords"]  = Compute2DCoords
 1452 
 1453     CounterCol = True
 1454     if re.match("^no$", Options["--counterCol"], re.I):
 1455         CounterCol = False
 1456     OptionsInfo["CounterCol"]  = CounterCol
 1457     
 1458     ColVisibility = True
 1459     if re.match("^no$", Options["--colVisibility"], re.I):
 1460         ColVisibility = False
 1461     OptionsInfo["ColVisibility"]  = ColVisibility
 1462     
 1463     OptionsInfo["ColVisibilityCtrlMax"]  = int(Options["--colVisibilityCtrlMax"])
 1464     
 1465     Footer = None
 1466     if not re.match("^None$", Options["--footer"], re.I):
 1467         Footer = Options["--footer"]
 1468     OptionsInfo["Footer"]  = Footer
 1469 
 1470     FooterClass = Options["--footerClass"].strip()
 1471     if MiscUtil.IsEmpty(FooterClass):
 1472         MiscUtil.PrintError("The value specified using option \"--footerClass\" is empty.")
 1473     OptionsInfo["FooterClass"]  = FooterClass
 1474     
 1475     FreezeCols = True
 1476     if re.match("^no$", Options["--freezeCols"], re.I):
 1477         FreezeCols = False
 1478     OptionsInfo["FreezeCols"]  = FreezeCols
 1479     
 1480     Header = None
 1481     if not re.match("^None$", Options["--header"], re.I):
 1482         Header = Options["--header"]
 1483     OptionsInfo["Header"]  = Header
 1484     
 1485     HeaderStyle = Options["--headerStyle"].strip()
 1486     if MiscUtil.IsEmpty(HeaderStyle):
 1487         MiscUtil.PrintError("The value specified using option \"--headerStyle\" is empty.")
 1488     OptionsInfo["HeaderStyle"]  = HeaderStyle
 1489 
 1490     ProcessHighlightSMARTSOption()
 1491     ProcessHighlightDataOptions()
 1492     
 1493     OptionsInfo["KeysNavigation"] = True
 1494     if re.match("^no$", Options["--keysNavigation"], re.I):
 1495         OptionsInfo["KeysNavigation"] = False
 1496     
 1497     SizeValues = Options["--molImageSize"].split(",")
 1498     OptionsInfo["MolImageWidth"] = int(SizeValues[0])
 1499     OptionsInfo["MolImageHeight"] = int(SizeValues[1])
 1500     
 1501     OptionsInfo["MolImageEncoded"] = True
 1502     if re.match("^no$", Options["--molImageEncoded"], re.I):
 1503         OptionsInfo["MolImageEncoded"] = False
 1504     
 1505     OptionsInfo["Paging"] = True
 1506     if re.match("^no$", Options["--paging"], re.I):
 1507         OptionsInfo["Paging"] = False
 1508     
 1509     PagingType = Options["--pagingType"]
 1510     if not re.match("^(numbers|simple|simple_numbers|full|full_numbers|simple_number)$", Options["--pagingType"], re.I):
 1511         MiscUtil.PrintWarning("The paging type name, %s, specified using option \"--pagingType\" appears to be a unknown type..." % (PagingType))
 1512     OptionsInfo["PagingType"] = PagingType.lower()
 1513     
 1514     OptionsInfo["PageLength"] = int(Options["--pageLength"])
 1515     
 1516     OptionsInfo["RegexSearch"] = True
 1517     if re.match("^no$", Options["--regexSearch"], re.I):
 1518         OptionsInfo["RegexSearch"] = False
 1519     
 1520     OptionsInfo["ShowMolName"] = True
 1521     OptionsInfo["ShowMolNameDataLabel"] = "Name"
 1522     if re.match("^no$", Options["--showMolName"], re.I):
 1523         OptionsInfo["ShowMolName"] = False
 1524     
 1525     OptionsInfo["ShowMolNameAuto"] = True if re.match("^auto$", Options["--showMolName"], re.I) else False
 1526 
 1527     OptionsInfo["ScrollX"] = True
 1528     if re.match("^no$", Options["--scrollX"], re.I):
 1529         OptionsInfo["ScrollX"] = False
 1530         
 1531     OptionsInfo["ScrollY"] = True
 1532     if re.match("^no$", Options["--scrollY"], re.I):
 1533         OptionsInfo["ScrollY"] = False
 1534 
 1535     OptionsInfo["ScrollYSize"] = Options["--scrollYSize"]
 1536     if re.match("vh$", Options["--scrollYSize"], re.I):
 1537         ScrollYSize = int(re.sub("vh$", "", Options["--scrollYSize"]))
 1538         if ScrollYSize <= 0:
 1539             MiscUtil.PrintError("The value specified, %s, for option \"--scrollYSize\" is not valid. Supported value: > 0 followed by \"vh\"" % Options["--scrollYSize"])
 1540     
 1541     TableStyle = None
 1542     if not re.match("^None$", Options["--tableStyle"], re.I):
 1543         if re.match("^All$", Options["--tableStyle"], re.I):
 1544             TableStyle = "table table-striped table-bordered table-hover table-dark"
 1545         else:
 1546             TableStyle = re.sub(" ", "", Options["--tableStyle"])
 1547             for Style in [Style for Style in TableStyle.split(",")]:
 1548                 if not re.match("^(table|table-striped|table-bordered|table-hover|table-dark|table-sm)$", Style, re.I):
 1549                     MiscUtil.PrintWarning("The table style name, %s, specified using option \"-t, --tableStyle\" appears to be a unknown style..." % (Style))
 1550             TableStyle = re.sub(",", " ", TableStyle.lower())
 1551     OptionsInfo["TableStyle"]  = TableStyle
 1552 
 1553     TableHeaderStyle = None
 1554     if not re.match("^None$", Options["--tableHeaderStyle"], re.I):
 1555         TableHeaderStyle = Options["--tableHeaderStyle"]
 1556         TableHeaderStyle = TableHeaderStyle.lower()
 1557         CheckOptionTableClassColorValues("--tableHeaderStyle", [TableHeaderStyle])
 1558     OptionsInfo["TableHeaderStyle"]  = TableHeaderStyle
 1559     
 1560     OptionsInfo["TableFooter"] = True
 1561     if re.match("^no$", Options["--tableFooter"], re.I):
 1562         OptionsInfo["TableFooter"] = False
 1563 
 1564     OptionsInfo["WrapText"] = True
 1565     if re.match("^no$", Options["--wrapText"], re.I):
 1566         OptionsInfo["WrapText"] = False
 1567 
 1568     OptionsInfo["WrapTextWidth"] = int(Options["--wrapTextWidth"])
 1569 
 1570 def RetrieveOptions():
 1571     """Retrieve command line arguments and options"""
 1572     
 1573     # Get options...
 1574     global Options
 1575     Options = docopt(_docoptUsage_)
 1576     
 1577     # Set current working directory to the specified directory...
 1578     WorkingDir = Options["--workingdir"]
 1579     if WorkingDir:
 1580         os.chdir(WorkingDir)
 1581     
 1582     # Handle examples option...
 1583     if "--examples" in Options and Options["--examples"]:
 1584         MiscUtil.PrintInfo(MiscUtil.GetExamplesTextFromDocOptText(_docoptUsage_))
 1585         sys.exit(0)
 1586 
 1587 def ValidateOptions():
 1588     """Validate option values"""
 1589     
 1590     if not re.match("^None$", Options["--alignmentSMARTS"], re.I):
 1591         PatternMol = Chem.MolFromSmarts(Options["--alignmentSMARTS"])
 1592         if PatternMol is None:
 1593             MiscUtil.PrintError("The value specified, %s, using option \"--alignmentSMARTS\" is not a valid SMARTS: Failed to create pattern molecule" % Options["--alignmentSMARTS"])
 1594     
 1595     MiscUtil.ValidateOptionTextValue("-c, --compute2DCoords", Options["--compute2DCoords"], "yes no auto")
 1596     
 1597     MiscUtil.ValidateOptionTextValue("--counterCol", Options["--counterCol"], "yes no")
 1598     MiscUtil.ValidateOptionTextValue("--colVisibility", Options["--colVisibility"], "yes no")
 1599     MiscUtil.ValidateOptionIntegerValue("--colVisibilityCtrlMax", Options["--colVisibilityCtrlMax"], {">": 0})
 1600     
 1601     MiscUtil.ValidateOptionTextValue("--freezeCols", Options["--freezeCols"], "yes no")
 1602     MiscUtil.ValidateOptionTextValue("--highlightValuesClasses", Options["--highlightValuesClasses"], "RuleOf5 RuleOf3 DrugLike Random None")
 1603     
 1604     MiscUtil.ValidateOptionFilePath("-i, --infile", Options["--infile"])
 1605     MiscUtil.ValidateOptionFileExt("-i, --infile", Options["--infile"], "sdf sd mol smi csv tsv txt")
 1606 
 1607     MiscUtil.ValidateOptionFileExt("-o, --outfile", Options["--outfile"], "html")
 1608     MiscUtil.ValidateOptionsOutputFileOverwrite("-o, --outfile", Options["--outfile"], "--overwrite", Options["--overwrite"])
 1609     MiscUtil.ValidateOptionsDistinctFileNames("-i, --infile", Options["--infile"], "-o, --outfile", Options["--outfile"])
 1610     
 1611     MiscUtil.ValidateOptionTextValue("-k, --keysNavigation", Options["--keysNavigation"], "yes no")
 1612     
 1613     MiscUtil.ValidateOptionNumberValues("-m, --molImageSize", Options["--molImageSize"], 2, ",", "integer", {">": 0})
 1614     MiscUtil.ValidateOptionTextValue("--molImageEncoded", Options["--molImageEncoded"], "yes no")
 1615     
 1616     MiscUtil.ValidateOptionTextValue("-p, --paging", Options["--paging"], "yes no")
 1617     MiscUtil.ValidateOptionIntegerValue("--pageLength", Options["--pageLength"], {">": 0})
 1618     MiscUtil.ValidateOptionTextValue("-r, --regexSearch", Options["--regexSearch"], "yes no")
 1619     
 1620     MiscUtil.ValidateOptionTextValue("--showMolName", Options["--showMolName"], "yes no auto")
 1621     
 1622     MiscUtil.ValidateOptionTextValue("--scrollX", Options["--scrollX"], "yes no")
 1623     MiscUtil.ValidateOptionTextValue("--scrollY", Options["--scrollY"], "yes no")
 1624     if not re.search("vh$", Options["--scrollYSize"], re.I):
 1625         MiscUtil.ValidateOptionIntegerValue("--scrollYSize", Options["--scrollYSize"], {">": 0})
 1626     
 1627     MiscUtil.ValidateOptionTextValue("--tableFooter", Options["--tableFooter"], "yes no")
 1628     
 1629     MiscUtil.ValidateOptionTextValue("--wrapText", Options["--wrapText"], "yes no")
 1630     MiscUtil.ValidateOptionIntegerValue("--wrapTextWidth", Options["--wrapTextWidth"], {">": 0})
 1631 
 1632 # Setup a usage string for docopt...
 1633 _docoptUsage_ = """
 1634 RDKitDrawMoleculesAndDataTable.py - Generate a HTML data table
 1635 
 1636 Usage:
 1637     RDKitDrawMoleculesAndDataTable.py [--alignmentSMARTS <SMARTS>]
 1638                              [--compute2DCoords <yes or  no>] [--counterCol <yes or no>]
 1639                              [--colVisibility <yes or no>] [--colVisibilityCtrlMax <number>] [--footer <text>]
 1640                              [--footerClass <text>] [--freezeCols <yes or no>] [--header <text>]
 1641                              [--headerStyle <text>] [--highlightSMARTS <SMARTS,...>]
 1642                              [--highlightValues <datalabel,datatype,criterion,value,...>]
 1643                              [--highlightValuesRanges <datalabel,datatype,criterion1,vaue1,criterion2,value2...>]
 1644                              [--highlightValuesClasses <RuleOf5,RuleOf3,...>]
 1645                              [--highlightColors <colortype,color1,color2>]
 1646                              [--highlightColorsRanges <colortype,color1,color2,color3>]
 1647                              [--highlightColorsRandom <colottype,color1,color2,...>]
 1648                              [--infileParams <Name,Value,...>] [--keysNavigation <yes or no>]
 1649                              [--molImageSize <width,height>] [--molImageEncoded <yes or no> ] [--overwrite]
 1650                              [--paging <yes or no>] [--pagingType <numbers,simple, ...>] [--pageLength <number>]
 1651                              [--regexSearch <yes or no>] [--showMolName <yes or no>]
 1652                              [--scrollX <yes or no>] [--scrollY <yes or no>] [--scrollYSize <number>]
 1653                              [--tableStyle <table,table-striped,...>] [--tableFooter <yes or no>]
 1654                              [--tableHeaderStyle <thead-dark,thead-light,...>] [--wrapText <yes or no>] 
 1655                              [--wrapTextWidth <number>] [-w <dir>] -i <infile> -o <outfile>
 1656     RDKitDrawMoleculesAndDataTable.py -h | --help | -e | --examples
 1657 
 1658 Description:
 1659     Generate an interactive HTML table with columns corresponding to molecules
 1660     and available alphanumerical data in an input file. The drawing of molecules are
 1661     embedded in the columns as in line SVG images.
 1662 
 1663     The interactive HTML table may contain multiple columns with drawing of
 1664     molecules. These columns are automatically generated for each data field in SD
 1665     file or a column name in SMILES and CSV/TSV file containing SMILES
 1666     string in their names. The first molecular drawing column in the HTML table
 1667     represents primary molecular structure data available in an input file. It
 1668     corresponds to MOL block is SD file or a first column containing SMILES string
 1669     in its name in SMILES and CSV/TSV files.
 1670  
 1671     The interactive table requires internet access for viewing in a browser and
 1672     employs the following frameworks: JQuery, Bootstrap, and DataTable. It provides
 1673     the following functionality: sorting by columns, page length control, page 
 1674     navigation, searching data with regular expressions, and horizontal/vertical
 1675     scrolling, row highlighting during hovering, a counter column, freezing of primary
 1676     structure and counter columns, and column visibility control.
 1677 
 1678     The supported input file formats are: Mol (.mol), SD (.sdf, .sd), SMILES (.smi),
 1679     CSV/TSV (.csv, .tsv, .txt)
 1680 
 1681     The supported output file format is HTML (.html).
 1682 
 1683 Options:
 1684     -a, --alignmentSMARTS <SMARTS>  [default: none]
 1685         SMARTS pattern for aligning molecules to a common template. This option is
 1686         only used for primary molecular data in SD, SMILES and CSV/TSV files. It is 
 1687         ignored for all other molecular coordinates corresponding to data fields in SD
 1688         file or columns in SMILES and CSV/TSV files containing SMILES string in their
 1689         names.
 1690     -c, --compute2DCoords <yes or no>  [default: yes]
 1691         Compute 2D coordinates of molecules before drawing. Default: yes for SMILES
 1692         strings in SMILES, CSV/TSV, and SD file data fields. In addition, 2D coordinated are
 1693         always calculated for molecules corresponding to data fields in SD file or columns
 1694         in SMILES and CSV/TSV files containing SMILES string in their names.
 1695     --counterCol <yes or no>  [default: yes]
 1696         Show a counter column as the first column in the table. It contains the position
 1697         for each row in the table.
 1698     --colVisibility <yes or no>  [default: yes]
 1699         Show a dropdown button to toggle visibility of columns in the table. The counter
 1700         and primary structure columns are excluded from the list.
 1701     --colVisibilityCtrlMax <number>  [default: 25]
 1702         Maximum number of columns to show in column visibility dropdown button. The
 1703         rest of the data columns are not listed in the dropdown and are shown in the table.
 1704         A word to the wise: The display of too many columns appear to hang interactive
 1705         Javascript framework for Bootstrap and DataTables.
 1706     --freezeCols <yes or no>  [default: yes]
 1707         Lock counter and primary structure columns in place during horizontal scrolling.
 1708     --footer <text>  [default: none]
 1709         Footer text to insert at the bottom of the HTML page after the table.
 1710     --footerClass <text>  [default: small text-center text-muted]
 1711         Footer class style to use with <p> tag.
 1712     -e, --examples
 1713         Print examples.
 1714     -h, --help
 1715         Print this help message.
 1716     --header <text>  [default: none]
 1717         Header text to insert at the top of the HTML page before the table.
 1718     --headerStyle <text>  [default: h5]
 1719         Header style to use. Possible values: h1 to h6.
 1720     --highlightSMARTS <SMARTS,...>  [default: none]
 1721         SMARTS pattern for highlighting atoms and bonds in molecules. All matched
 1722         substructures are highlighted.
 1723         
 1724         The SMARTS string is used to highlight atoms and bonds in drawing of
 1725         molecules present in a HTML table across multiple columns. These columns
 1726         correspond to data field labels in SD file or a column name in SMILES and
 1727         CSV/TSV file containing SMILES string in their names. The first molecular
 1728         drawing column in HTML table corresponds to primary molecular structure
 1729         data available in an input file. It is identified by a label 'Structure' across
 1730         all input formats.
 1731         
 1732         A single SMARTS string is used to highlight a common substructure across
 1733         all columns containing drawing of molecules in HTML table.
 1734         
 1735         Format:
 1736             
 1737             SMARTS
 1738             Structure,SMARTS1,DataLabel,SMARTS2,...
 1739             Structure,SMARTS1,Collabel,SMARTS2,...
 1740             
 1741         Example:
 1742             
 1743             c1ccccc1
 1744             Structure,c1ccccc1,SMILESR1,c1ccccc1,SMILESR2,c1ccccc1
 1745             
 1746     --highlightValues <datalabel,datatype,criterion,value,...>  [default: none]
 1747         Highlighting methodology to use for highlighting  alphanumerical data
 1748         corresponding to data fields in SD file or column names in SMILES and
 1749         CSV/TSV text files.
 1750         
 1751         Input text contains these quartets: DataLabel, DataType, Criterion, Value.
 1752         Possible datatype values: numeric, text. Possible criterion values for numeric
 1753         and text: gt, lt, ge, le.
 1754         
 1755         The 'datalabel' corresponds to either data field label in SD file or column name
 1756         in SMILES and CSV/TSV text files.
 1757         
 1758         Examples:
 1759             
 1760             MolecularWeight,numeric,le,500
 1761             MolecularWeight,numeric,le,450,SLogP,numeric,le,5
 1762             Name,text,eq,Aspirin
 1763             Name,regex,eq,acid|amine
 1764             
 1765     --highlightValuesRanges <datalabel,datatype,...>  [default: none]
 1766         Highlighting methodology to use for highlighting ranges of alphanumerical
 1767         data corresponding to data fields in SD file or column names in SMILES and
 1768         CSV/TSV text files.
 1769         
 1770         Input text contains these sextets: DataLabel, DataType, CriterionLowerBound,
 1771         LowerBoundValue, CriterionUpperBound, UpperBoundValue.
 1772         
 1773         Possible datatype values: numeric or text. Possible criterion values: Lower
 1774         bound value - lt, le; Upper bound value: gt, ge.
 1775         
 1776         The 'datalabel' corresponds to either data field label in SD file or column name
 1777         in SMILES and CSV/TSV text files.
 1778         
 1779         Examples:
 1780             
 1781             MolecularWeight,numeric,lt,450,gt,1000
 1782             MolecularWeight,numeric,lt,450,gt,1000,SLogP,numeric,lt,0,gt,5
 1783             
 1784     --highlightValuesClasses <RuleOf5,RuleOf3,...>  [default: none]
 1785         Highlighting methodology to use for highlighting ranges of numerical data
 1786         data corresponding to specific set of data fields in SD file or column names in
 1787         SMILES and CSV/TSV text files. Possible values: RuleOf5, RuleOf3, DrugLike,
 1788         Random.
 1789         
 1790         The following value classes are supported: RuleOf5, RuleOf3, LeadLike, DrugLike.
 1791         LeadLike is equivalent to RuleOf3.
 1792         
 1793         Each supported class encompasses a specific set of data labels along with
 1794         appropriate criteria to compare and highlight column values, except for
 1795         'Random' class. The data labels in these classes are automatically associated
 1796         with appropriate data fields in SD file or column names in SMILES and CSV/TSV
 1797         text files.
 1798         
 1799         No data labels are associated with 'Random' class. It is used to highlight
 1800         available alphanumeric data by randomly selecting a highlight color from the
 1801         list of colors specified using '--highlightColorsRandom' option. The 'Random'
 1802         class value is not allowed in conjunction with '--highlightValues' or
 1803         '--highlightValuesRanges'.
 1804         
 1805         The rules to highlight values for the supported classes are as follows.
 1806         
 1807         RuleOf5 [ Ref 91 ]:
 1808          
 1809             MolecularWeight,numeric,le,500 (MolecularWeight <= 500)
 1810             HydrogenBondDonors,numeric,le,5 (HydrogenBondDonors <= 5)
 1811             HydrogenBondAcceptors,numeric,le,10 (HydrogenBondAcceptors <= 10)
 1812             LogP,numeric,le,5 (LogP <= 5)
 1813          
 1814         RuleOf3 or LeadLike [ Ref 92 ]:
 1815          
 1816             MolecularWeight,numeric,le,300 (MolecularWeight <= 300)
 1817             HydrogenBondDonors,numeric,le,3 (HydrogenBondDonors <= 3)
 1818             HydrogenBondAcceptors,numeric,le,3 (HydrogenBondAcceptors <= 3)
 1819             LogP,numeric,le,3 (LogP <= 3)
 1820             RotatableBonds,numeric,le,3 (RotatableBonds <= 3)
 1821             TPSA,numeric,le,60 (TPSA <= 60)
 1822          
 1823         DrugLike:
 1824          
 1825             MolecularWeight,numeric,le,500 (MolecularWeight <= 500)
 1826             HydrogenBondDonors,numeric,le,5 (HydrogenBondDonors <= 5)
 1827             HydrogenBondAcceptors,numeric,le,10 (HydrogenBondAcceptors <= 10)
 1828             LogP,numeric,le,5 (LogP <= 5)
 1829             RotatableBonds,numeric,le,10 (RotatableBonds <= 10)
 1830             TPSA,numeric,le,140 (TPSA <= 140)
 1831             
 1832         The following synonyms are automatically detected for data labels used
 1833         by MayaChemTools and RDKit packages during the calculation of
 1834         physicochemical properties.
 1835         
 1836         MayaChemTools: MolecularWeight, HydrogenBondDonors, HydrogenBondAcceptors,
 1837         SLogP, RotatableBonds, TPSA.
 1838             
 1839         RDKit: MolWt,  NHOHCount, NOCount, MolLogP, NumRotatableBonds, TPSA
 1840         
 1841     --highlightColors <colortype,color1,color2>  [default: auto]
 1842         Background colors used to highlight column values based on criterion
 1843         specified by '--highlightValues' and '--highlightColorsClasses' option. Default
 1844         value: colorclass,table-success, table-danger.
 1845         
 1846         The first color is used to highlight column values that satisfy the specified
 1847         criterion for the column. The second color highlights the rest of the values
 1848         in the column. 
 1849         
 1850         Possible values for colortype: colorclass or colorspec.
 1851         
 1852         Any valid bootstrap contextual color class is supported for 'colorclass'
 1853         color type. For example: table-primary (Blue), table-success (Green),
 1854         table-danger (Red), table-info (Light blue), table-warning (Orange),
 1855         table-secondary (Grey), table-light (Light grey), and  table-dark (Dark grey).
 1856         
 1857         The following bootstrap color classes may also used: bg-primary bg-success,
 1858         bg-danger bg-info, bg-warning, bg-secondary.
 1859         
 1860         Any valid color name or hexadecimal color specification is supported for
 1861         'colorspec' color type: For example: red, green, blue, #ff000, #00ff00, #0000ff.
 1862     --highlightColorsRanges <colortype,color1,color2,color3>  [default: auto]
 1863         Background colors used to highlight column values using criteria specified
 1864         by '--highlightValuesRanges' option. Default value:  colorclass, table-success,
 1865         table-warning, table-danger.
 1866         
 1867         The first and third color are used to highlight column values lower and higher
 1868         than the specified values for the lower and upper bound. The middle color highlights
 1869         the rest of the values in the column.
 1870         
 1871         The supported color type and values are explained in the section for '--highlightColors'.
 1872     --highlightColorsRandom <colortype,color1,color2,...>  [default: auto]
 1873         Background color list to use for randomly selecting a color  to highlight
 1874         column values during 'Random" value of '--highlightValuesClasses' option.
 1875         
 1876         Default value:  colorclass,table-primary,table-success,table-danger,table-info,
 1877         table-warning,table-secondary.
 1878         
 1879         The supported color type and values are explained in the section for '--highlightColors'.
 1880     -i, --infile <infile>
 1881         Input file name.
 1882     --infileParams <Name,Value,...>  [default: auto]
 1883         A comma delimited list of parameter name and value pairs for reading
 1884         molecules from files. The supported parameter names for different file
 1885         formats, along with their default values, are shown below:
 1886             
 1887             SD, MOL: removeHydrogens,yes,sanitize,yes,strictParsing,yes
 1888             SMILES: smilesColumn,1,smilesNameColumn,2,smilesDelimiter,space,
 1889                 sanitize,yes
 1890             
 1891         Possible values for smilesDelimiter: space, comma or tab.
 1892     -k, --keysNavigation <yes or no>  [default: yes]
 1893         Provide Excel like keyboard cell navigation for the table.
 1894     -m, --molImageSize <width,height>  [default: 200,150]
 1895         Image size of a molecule in pixels.
 1896     --molImageEncoded <yes or no>  [default: yes]
 1897         Base64 encode SVG image of a molecule for inline embedding in a HTML page.
 1898         The inline SVG image may fail to display in browsers without encoding.
 1899     -o, --outfile <outfile>
 1900         Output file name.
 1901     --overwrite
 1902         Overwrite existing files.
 1903     -p, --paging <yes or no>  [default: yes]
 1904         Provide page navigation for browsing data in the table.
 1905     --pagingType <numbers, simple, ...>  [default: full_numbers]
 1906         Type of page navigation. Possible values: numbers, simple, simple_numbers,
 1907         full, full_numbers, or first_last_numbers.
 1908             
 1909             numbers - Page number buttons only
 1910             simple - 'Previous' and 'Next' buttons only
 1911             simple_numbers - 'Previous' and 'Next' buttons, plus page numbers
 1912             full - 'First', 'Previous', 'Next' and 'Last' buttons
 1913             full_numbers - 'First', 'Previous', 'Next' and 'Last' buttons, plus
 1914                 page numbers
 1915             first_last_numbers - 'First' and 'Last' buttons, plus page numbers
 1916             
 1917     --pageLength <number>  [default: 15]
 1918         Number of rows to show per page.
 1919     -r, --regexSearch <yes or no>  [default: yes]
 1920         Allow regular expression search through alphanumerical data in the table.
 1921     -s, --showMolName <yes or no>  [default: auto]
 1922         Show molecule names in a column next to the column corresponding to primary
 1923         structure data in SD and SMILES file. The default value is yes for SD and SMILES file.
 1924         This option is ignored for CSV/TSV text files.
 1925     --scrollX <yes or no>  [default: yes]
 1926         Provide horizontal scroll bar in the table as needed.
 1927     --scrollY <yes or no>  [default: yes]
 1928         Provide vertical scroll bar in the table as needed.
 1929     --scrollYSize <number>  [default: 75vh]
 1930         Maximum height of table viewport either in pixels or percentage of the browser
 1931         window height before providing a vertical scroll bar. Default: 75% of the height of
 1932         browser window.
 1933     -t, --tableStyle <table,table-striped,...>  [default: table,table-hover,table-sm]
 1934         Style of table. Possible values: table, table-striped, table-bordered,
 1935         table-hover, table-dark, table-sm, none, or All. Default: 'table,table-hover'. A
 1936         comma delimited list of any valid Bootstrap table styles is also supported.
 1937     --tableFooter <yes or no>  [default: yes]
 1938         Show column headers at the end of the table.
 1939     --tableHeaderStyle <thead-dark,thead-light,...>  [default: thead-dark]
 1940         Style of table header. Possible values: thead-dark, thead-light, or none.
 1941         The names of the following contextual color classes are also supported:
 1942         table-primary (Blue), table-success (Green), table-danger (Red), table-info
 1943         (Light blue), table-warning (Orange), table-active (Grey), table-light (Light
 1944         grey), and  table-dark (Dark grey).
 1945     -w, --workingdir <dir>
 1946         Location of working directory which defaults to the current directory.
 1947     --wrapText <yes or no>  [default: yes]
 1948         Wrap alphanumeric text using <br/> delimiter for display in a HTML table.
 1949     --wrapTextWidth <number>  [default: 40]
 1950         Maximum width in characters before wraping alphanumeric text for display
 1951         in a HTML table.
 1952 
 1953 Examples:
 1954     To generate a HTML table containing structure and alphanumeric data for
 1955     molecules in a SD file along with all the bells and whistles to interact with
 1956     the table, type:
 1957 
 1958         % RDKitDrawMoleculesAndDataTable.py -i Sample.sdf -o SampleOut.html
 1959 
 1960     To generate a HTML table containing structure and alphanumeric data for
 1961     molecules in a SMILES file along with all the bells and whistles to interact
 1962     with the table, type:
 1963 
 1964         % RDKitDrawMoleculesAndDataTable.py  -i Sample.smi -o SampleOut.html
 1965 
 1966     To generate a HTML table containing multiple structure columns for molecules
 1967     in a CSV file along with all the bells and whistles to interact with the table, type:
 1968 
 1969         % RDKitDrawMoleculesAndDataTable.py -i SampleSeriesRGroupsD3R.csv
 1970           -o SampleSeriesRGroupsD3ROut.html
 1971 
 1972     To generate a HTML table containing structure and alphanumeric data for
 1973     molecules in a SD file along without any bells and whistles to interact with
 1974     the table, type:
 1975 
 1976         % RDKitDrawMoleculesAndDataTable.py --colVisibility no --freezeCols no
 1977           --keysNavigation no --paging no --regexSearch no --scrollX no
 1978           --scrollY no -i Sample.sdf -o SampleOut.html
 1979 
 1980     To generate a HTML table containing structure and alphanumeric data for
 1981     molecules in a SD file along with highlighting molecular weight values
 1982     using a specified criterion, type:
 1983 
 1984         % RDKitDrawMoleculesAndDataTable.py  --highlightValues
 1985           "MolecularWeight,numeric,le,500" -i Sample.sdf -o SampleOut.html
 1986 
 1987     To generate a HTML table containing structure and alphanumeric data for
 1988     molecules in a SD file along with highlighting range of molecular weight values
 1989     using a specified criterion, type:
 1990 
 1991         % RDKitDrawMoleculesAndDataTable.py  --highlightValuesRanges
 1992           "MolecularWeight,numeric,lt,400,gt,500" -i Sample.sdf -o SampleOut.html
 1993 
 1994     To generate a HTML table containing structure and alphanumeric data for
 1995     molecules in a SD file along with highlighting molecular weight values and
 1996     ranges of SLogP values using a specified criterion and color schemes, type:
 1997 
 1998         % RDKitDrawMoleculesAndDataTable.py  --highlightValues
 1999           "MolecularWeight,numeric,le,500" --highlightValuesRanges
 2000           "SLogP,numeric,lt,0,gt,5" --highlightColors "colorclass,table-success,
 2001           table-danger" --highlightColorsRanges "colorclass,table-danger,
 2002           table-success,table-warning" -i Sample.sdf -o SampleOut.html
 2003 
 2004     To generate a HTML table containing structure and alphanumeric data for
 2005     molecules in a SD file along with highlighting RuleOf5 physicochemical
 2006     properties using a pre-defined set of criteria, type:
 2007 
 2008         % RDKitDrawMoleculesAndDataTable.py  --highlightValuesClasses RuleOf5
 2009           -i Sample.sdf -o SampleOut.html
 2010 
 2011     To generate a HTML table containing structure and alphanumeric data for
 2012     molecules in a SD file along with all the bells and whistles to interact
 2013     with the table and highlight a specific SMARTS pattern in molecules, type:
 2014 
 2015         % RDKitDrawMoleculesAndDataTable.py  --highlightSMARTS "c1ccccc1"
 2016           -i Sample.sdf -o SampleOut.html
 2017 
 2018     To generate a HTML table containing structure and alphanumeric data for
 2019     molecules in a SD file along with highlighting of values using random colors
 2020     from a default list of colors, type:
 2021 
 2022         % RDKitDrawMoleculesAndDataTable.py --highlightValuesClasses Random
 2023           -i Sample.sdf -o SampleOut.html
 2024 
 2025     To generate a HTML table containing structure and alphanumeric data for
 2026     molecules in a SD file along with highlighting of values using random colors
 2027     from a specified list of colors, type:
 2028 
 2029         % RDKitDrawMoleculesAndDataTable.py --highlightValuesClasses Random
 2030           --highlightColorsRandom "colorspec,Lavendar,MediumPurple,SkyBlue,
 2031           CornflowerBlue,LightGreen,MediumSeaGreen,Orange,Coral,Khaki,Gold,
 2032           Salmon,LightPink,Aquamarine,MediumTurquoise,LightGray" 
 2033           -i Sample.sdf -o SampleOut.html
 2034 
 2035     To generate a HTML table containing structure and alphanumeric data for
 2036     molecules in a SMILES file specific columns, type:
 2037 
 2038         % RDKitDrawMoleculesAndDataTable.py --infileParams "smilesDelimiter,
 2039           comma, smilesColumn,1,smilesNameColumn,2"
 2040           -i SampleSMILES.csv -o SampleOut.html
 2041 
 2042 Author:
 2043     Manish Sud(msud@san.rr.com)
 2044 
 2045 See also:
 2046     RDKitConvertFileFormat.py, RDKitDrawMolecules.py, RDKitRemoveDuplicateMolecules.py,
 2047     RDKitSearchFunctionalGroups.py, RDKitSearchSMARTS.py
 2048 
 2049 Copyright:
 2050     Copyright (C) 2020 Manish Sud. All rights reserved.
 2051 
 2052     The functionality available in this script is implemented using RDKit, an
 2053     open source toolkit for cheminformatics developed by Greg Landrum.
 2054 
 2055     This file is part of MayaChemTools.
 2056 
 2057     MayaChemTools is free software; you can redistribute it and/or modify it under
 2058     the terms of the GNU Lesser General Public License as published by the Free
 2059     Software Foundation; either version 3 of the License, or (at your option) any
 2060     later version.
 2061 
 2062 """
 2063 
 2064 if __name__ == "__main__":
 2065     main()