Example #1
0
def get_compounds_from_database( database_file=None, **kw):
    """easy to use interface to the SQL - keyword arguments are converted to
    corresponding SQL commands.
    Examples:
    get_compounds_from_database( smiles='C1CCCCC1')
    get_compounds_from_database( inchi='1/C4H10/c1-3-4-2/h3-4H2,1-2H3')    
    """
    for fname in (database_file, Config.database_file):
        if fname and os.path.exists(fname):
            break
    else:
        raise oasa_exceptions.oasa_error("Structure database not found. Try running 'python structure_database.py structures.txt.gz' in oasa directory to create the database file from default source.")

    if 'inchi' in kw:
        if not 'inchikey' in kw:
            import inchi_key
            kw['inchikey'] = inchi_key.key_from_inchi( kw['inchi'])
        del kw['inchi']
    search = ["%s=?" % k for k in kw.keys()]
    values = kw.values()
    tables = "structures"
    if "synonym" in kw:
        tables = "structures, synonyms"
        search.append( "structures.id=synonyms.id")
    if search:
        sql = "SELECT structures.* FROM %s WHERE %s" % (tables, " AND ".join( search))
    else:
        sql = "SELECT structures.* FROM %s" % (tables)
    connection = sqlite.connect( Config.database_file)
    c = connection.cursor()
    try:
        c.execute( sql, values)
    except sqlite.OperationalError, e:
        raise oasa_exceptions.oasa_error( "Error reading from structure database: '%s'" % e)
Example #2
0
def database_string_to_compound(line):
    a, name = line.split("###")
    inchi, cid = a.split()
    inchikey = inchi_key.key_from_inchi(inchi)
    return {
        'inchikey': inchikey.strip(),
        'cid': cid.strip(),
        'name': name.strip()
    }
Example #3
0
def generate_inchi_and_inchikey(m,
                                program=None,
                                fixed_hs=True,
                                ignore_key_error=False):
    """ignore the case when InChIKey cannot be generated for some reason
  (no mhash library and old InChI program)"""
    if not program:
        import config
        program = config.Config.inchi_binary_path
    mf = molfile.mol_to_text(m)
    if os.name == 'nt':
        options = "/AUXNONE /STDIO /Key" + (fixed_hs and " /FixedH" or "")
    else:
        options = "-AUXNONE -STDIO -Key" + (fixed_hs and " -FixedH" or "")
    #print options
    command = [os.path.abspath(program)] + options.split()
    text = _run_command(command, mf)
    inchi = ""
    key = ""
    warnings = []
    for line in text.splitlines():
        if line.startswith("Warning"):
            warnings.append(line.strip() + "\n")
        elif line.startswith("End of file detected"):
            pass
        elif line.startswith("InChIKey="):
            key = line.strip()[9:]
            break
        elif line.startswith("InChI="):
            inchi = inchi + line.strip()
        elif line.startswith("Error"):
            break
    if not inchi:
        raise oasa_inchi_error("InChI program did not create any output InChI")
    if not key:
        # probably old version of the InChI software
        try:
            import inchi_key
        except ImportError:
            if ignore_key_error:
                key = None
            else:
                raise oasa_inchi_error(
                    "InChIKey could not be generated - inchi_key module failed to load properly."
                )
        else:
            key = inchi_key.key_from_inchi(inchi)
    return inchi, key, warnings
Example #4
0
def generate_inchi_and_inchikey( m, program=None, fixed_hs=True, ignore_key_error=False):
  """ignore the case when InChIKey cannot be generated for some reason
  (no mhash library and old InChI program)"""
  if not program:
    import config
    program = config.Config.inchi_binary_path
  mf = molfile.mol_to_text( m)
  if os.name == 'nt':
    options = "/AUXNONE /STDIO /Key" + (fixed_hs and " /FixedH" or "")
  else:
    options = "-AUXNONE -STDIO -Key" + (fixed_hs and " -FixedH" or "")
  #print options
  command = [os.path.abspath( program)] + options.split()
  text = _run_command( command, mf)
  inchi = ""
  key = ""
  warnings = []
  for line in text.splitlines():
    if line.startswith( "Warning"):
      warnings.append(line.strip() + "\n")
    elif line.startswith( "End of file detected"):
      pass
    elif line.startswith( "InChIKey="):
      key = line.strip()[9:]
      break
    elif line.startswith( "InChI="):
      inchi = inchi + line.strip()
    elif line.startswith( "Error"):
      break
  if not inchi:
    raise oasa_inchi_error( "InChI program did not create any output InChI")
  if not key:
    # probably old version of the InChI software
    try:
      import inchi_key
    except ImportError:
      if ignore_key_error:
        key = None
      else:
        raise oasa_inchi_error( "InChIKey could not be generated - inchi_key module failed to load properly.")
    else:
      key = inchi_key.key_from_inchi( inchi)
  return inchi, key, warnings
Example #5
0
def compound_to_database_string(c):
    c['inchi'] = normalize_inchi(c['inchi'])
    c['inchikey'] = inchi_key.key_from_inchi(c['inchi'])
    return "%(inchikey)s %(cid)s ### %(name)s\n" % c
Example #6
0
def database_string_to_compound( line):
    a,name = line.split( "###")
    inchi, cid = a.split()
    inchikey = inchi_key.key_from_inchi( inchi)
    return {'inchikey':inchikey.strip(), 'cid':cid.strip(), 'name':name.strip()}
Example #7
0
def compound_to_database_string( c):
    c['inchi'] = normalize_inchi( c['inchi'])
    c['inchikey'] = inchi_key.key_from_inchi( c['inchi'])
    return "%(inchikey)s %(cid)s ### %(name)s\n" % c