Example #1
0
def mapperfunc(mol):
    fig, weight = SimilarityMaps.GetSimilarityMapForModel(
        mol,
        SimilarityMaps.GetMorganFingerprint,
        lambda x: getProba(x, model.predict_proba),
        colorMap=cm.bwr)
    cls_result = model.predict(calc_fp_arr(mol))
    fname = uuid.uuid1().hex + ".png"
    fig.savefig("static/tempfig/" + fname, bbox_inches="tight")
    return cls_result, fname
Example #2
0
 def _map(x):
     mol = molf.mol_method(x)
     fig, _ = SimilarityMaps.GetSimilarityMapForModel(
         mol,
         SimilarityMaps.GetMorganFingerprint,
         lambda y: _get_proba(y, model.predict_proba),
         linewidths=0,
     )
     b64 = b64_fig(fig, dpi=72)
     img_src = '<img src="data:image/png;base64,{}" alt="Map" />'.format(
         b64)
     return img_src
Example #3
0
 def mapperfunc( mol ):
     fig, weight = SimilarityMaps.GetSimilarityMapForModel( mol, SimilarityMaps.GetMorganFingerprint, lambda x: getProba( x, cls.predict_proba), colorMap=cm.bwr  )
     fp = AllChem.GetMorganFingerprintAsBitVect( mol, 2 )
     print(fp)
     arr = np.zeros((1,))
     DataStructs.ConvertToNumpyArray( fp, arr )
     print(arr)
     res = cls.predict( arr )
     smi = Chem.MolToSmiles( mol )
     print(smi)
     
     if res[0] == 1:
         fig.savefig( "res/act_"+smi+"_.png", bbox_inches = "tight" )
     else:
         fig.savefig("res/nonact_"+smi+"_.png", bbox_inches = "tight" )
Example #4
0
def pred_frag(mol, model, radius=3, nBits=2048):

    def getProba(fp, probabilityfunc):
        return probabilityfunc(fp)[0][1]

    def fpFunction(mol,atomId=-1):
        fp = SimilarityMaps.GetMorganFingerprint(mol,
                                                 atomId=atomId,
                                                 radius=radius,
                                                 nBits=nBits)
        return fp

    fig = SimilarityMaps.GetSimilarityMapForModel(mol,
                                                  fpFunction,
                                                  lambda x: getProba((x,),
                                                  model.predict_proba),
                                                  colorMap=cm.PiYG_r)
Example #5
0
def sim_map(mol_list,
            model,
            id_prop=None,
            interact=False,
            highlight=None,
            show_hidden=False,
            order=None,
            size=300):
    """Parameters:
        mol_list (Mol_List): List of RDKit molecules
        highlight (dict): Dict of properties (special: *all*) and values to highlight cells,
            e.g. {"activity": "< 50"}
        show_hidden (bool): Whether to show hidden properties (name starts with _) or not.
            Defaults to *False*.
        link (str): column used for linking out
        target (str): column used as link target
        order (list): A list of substrings to match with the field names for ordering in the table header
        img_dir (str): if None, the molecule images are embedded in the HTML doc.
            Otherwise the images will be stored in img_dir and linked in the doc.

    Returns:
        HTML table as TEXT to embed in IPython or a web page."""

    time_stamp = time.strftime("%y%m%d%H%M%S")
    td_opt = {"style": "text-align: center;"}
    header_opt = {"bgcolor": "#94CAEF", "style": "text-align: center;"}
    table_list = []
    prop_list = tools.list_fields(mol_list)

    if isinstance(order, list):
        for k in reversed(order):
            prop_list.sort(key=lambda x: k.lower() in x.lower(), reverse=True)

    if id_prop is None:
        guessed_id = tools.guess_id_prop(prop_list)
    else:
        guessed_id = id_prop

    if interact and guessed_id is not None:
        table_list.append(
            tools.TBL_JAVASCRIPT.format(ts=time_stamp, bgcolor="transparent"))

    if id_prop is not None:
        if id_prop not in prop_list:
            raise LookupError(
                "Id property {} not found in data set.".format(id_prop))

    if len(mol_list) > 5:
        pb = nbt.ProgressbarJS()

    if guessed_id:
        # make sure that the id_prop (or the guessed id prop) is first:
        prop_list.pop(prop_list.index(guessed_id))
        tmp_list = [guessed_id]
        tmp_list.extend(prop_list)
        prop_list = tmp_list

    cells = html.td(html.b("#"), header_opt)
    cells.extend(html.td(html.b("Molecule"), header_opt))
    cells.extend(html.td(html.b("SimMap"), header_opt))
    for prop in prop_list:
        cells.extend(html.td(html.b(prop), header_opt))
    rows = html.tr(cells)

    list_len = len(mol_list)
    for idx, mol in enumerate(mol_list):
        if len(mol_list) > 5:
            pb.update(100 * (idx + 1) / list_len)
        cells = []
        mol_props = mol.GetPropNames()

        if guessed_id:
            id_prop_val = mol.GetProp(guessed_id)
            img_id = id_prop_val
            cell_opt = {"id": "{}_{}".format(id_prop_val, time_stamp)}
        else:
            img_id = idx
            cell_opt = {"id": str(idx)}

        cell = html.td(str(idx), cell_opt)
        cells.extend(cell)

        if not mol:
            cells.extend(html.td("no structure"))

        else:
            b64 = tools.b64_img(mol, size * 2)
            img_src = "data:image/png;base64,{}".format(b64)
            cell_opt = {}
            if interact and guessed_id is not None:
                img_opt = {
                    "title": "Click to select / unselect",
                    "onclick": "toggleCpd('{}')".format(id_prop_val)
                }
            else:
                img_opt = {"title": str(img_id)}
            # img_opt["width"] = size
            # img_opt["height"] = size
            img_opt[
                "style"] = 'max-width: {}px; max-height: {}px; display: block; margin: auto;'.format(
                    size, size)

            cell = html.img(img_src, img_opt)
            cells.extend(html.td(cell, cell_opt))

            fig, _ = SimilarityMaps.GetSimilarityMapForModel(
                mol, SimilarityMaps.GetMorganFingerprint,
                lambda x: _get_proba(x, model.predict_proba))
            b64 = b64_fig(fig, dpi=72)
            img_src = "data:image/png;base64,{}".format(b64)
            cell_opt = {}
            img_opt[
                "style"] = 'max-width: {}px; max-height: {}px; display: block; margin: auto;'.format(
                    size, size)
            cell = html.img(img_src, img_opt)
            cells.extend(html.td(cell, cell_opt))

        for prop in prop_list:
            td_opt = {"style": "text-align: center;"}
            if prop in mol_props:
                if not show_hidden and prop.startswith("_"): continue
                td_opt["title"] = prop
                prop_val = mol.GetProp(prop)
                if highlight:
                    eval_str = None
                    if "*all*" in highlight:
                        if not guessed_id or (guessed_id
                                              and prop != guessed_id):
                            eval_str = " ".join([prop_val, highlight["*all*"]])
                    else:
                        if prop in highlight:
                            eval_str = " ".join([prop_val, highlight[prop]])
                    if eval_str and eval(eval_str):
                        td_opt["bgcolor"] = "#99ff99"

                cells.extend(html.td(prop_val, td_opt))
            else:
                cells.extend(html.td("", td_opt))

        rows.extend(html.tr(cells))

    table_list.extend(html.table(rows))

    if interact and guessed_id is not None:
        table_list.append(tools.ID_LIST.format(ts=time_stamp))

    if len(mol_list) > 5:
        pb.done()
    return "".join(table_list)