#!/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

if len(sys.argv) != 3:
    oechem.OEThrow.Usage("%s <molfname> <fpdbfname>" % sys.argv[0])

mfname = sys.argv[1]
ffname = sys.argv[2]

moldb = oechem.OEMolDatabase()
if not moldb.Open(mfname):
    oechem.OEThrow.Fatal("Cannot open molecule database!")

memtype = oegraphsim.OEFastFPDatabaseMemoryType_InMemory

fpdb = oegraphsim.OEFastFPDatabase(ffname, memtype)
if not fpdb.IsValid():
    oechem.OEThrow.Fatal("Cannot open fingerprint database!")

if not oegraphsim.OEAreCompatibleDatabases(moldb, fpdb):
    oechem.OEThrow.Fatal("Databases are not compatible!")

# @ <SNIPPET>
query = oechem.OEGraphMol()
oechem.OESmilesToMol(query, "Cc1c(c2cc(ccc2n1C(=O)c3ccc(cc3)Cl)OC)CC(=O)O")

limit = 5
opts = oegraphsim.OEFPDatabaseOptions(limit, oegraphsim.OESimMeasure_Tanimoto)

nrbins = 5
result = oegraphsim.OESimSearchResult(nrbins)
status = fpdb.SortedSearch(result, query, opts)
print("Search status = {}".format(oegraphsim.OESimSearchStatusToName(status)))
print("Number of searched = {}".format(result.NumSearched()))

# print scores
for score in result.GetSortedScores():
    print("{:.3f}".format(score.GetScore()))

# print histogram
hist = result.GetHistogram()
bounds = hist.GetBinBoundaries()
for idx, count in enumerate(hist.GetCounts()):
    print("[{:.3f}-{:.3f}] = {}".format(bounds[idx], bounds[idx+1], count))
# @ </SNIPPET>
