#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence) 
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED.  OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.

import sys
from openeye import oechem
from openeye import oegraphsim

# @ <SNIPPET-MEM-SIM-SEARCH>
if len(sys.argv) != 2:
    oechem.OEThrow.Usage("%s <database>" % sys.argv[0])

ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
    oechem.OEThrow.Fatal("Cannot open database molecule file!")

# load molecules

moldb = oechem.OEMolDatabase(ifs)
nrmols = moldb.GetMaxMolIdx()

# generate fingerprints

fpdb = oegraphsim.OEFPDatabase(oegraphsim.OEFPType_Path)

emptyfp = oegraphsim.OEFingerPrint()
emptyfp.SetFPTypeBase(fpdb.GetFPTypeBase())

mol = oechem.OEGraphMol()
for idx in range(0, nrmols):
    if moldb.GetMolecule(mol, idx):
        fpdb.AddFP(mol)
    else:
        fpdb.AddFP(emptyfp)

nrfps = fpdb.NumFingerPrints()

timer = oechem.OEWallTimer()
while True:

    # read query SMILES from stdin

    sys.stdout.write("Enter SMILES> ")
    line = sys.stdin.readline()
    line = line.rstrip()
    if len(line) == 0:
        sys.exit(0)

    # parse query

    query = oechem.OEGraphMol()
    if not oechem.OESmilesToMol(query, line):
        oechem.OEThrow.Warning("Invalid SMILES string")
        continue

    # calculate similarity scores

    timer.Start()
    scores = fpdb.GetSortedScores(query, 5)
    oechem.OEThrow.Info("%5.2f seconds to search %i fingerprints" % (timer.Elapsed(), nrfps))

    hit = oechem.OEGraphMol()
    for si in scores:
        if moldb.GetMolecule(hit, si.GetIdx()):
            smi = oechem.OEMolToSmiles(hit)
            oechem.OEThrow.Info("Tanimoto score %4.3f %s" % (si.GetScore(), smi))
# @ </SNIPPET-MEM-SIM-SEARCH>
