Skip to content

Commit

Permalink
Merge pull request #38 from cbouy/callbacks-cleanup
Browse files Browse the repository at this point in the history
Callbacks cleanup
  • Loading branch information
cbouy committed Dec 23, 2022
2 parents f42006e + af78ad8 commit 7723b24
Show file tree
Hide file tree
Showing 6 changed files with 39 additions and 12 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `show_3d`: displays the molecule in 3D
- `external_link`: opens a new tab. By default, opens [Leruli.com](https://leruli.com/)
using the SMILES of the molecule.
- Support for `tuple` in `display` and `save`.
- Support for `tuple` of molecules in `display` and `save`.

### Changed
- The `"click"` event is now automatically removed from `tooltip_trigger` when
Expand Down
3 changes: 2 additions & 1 deletion docs/notebooks/callbacks.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"\n",
"SDF_FILE = (f\"{RDConfig.RDDocsDir}/Book/data/solubility.test.sdf\"\n",
" if Path(RDConfig.RDDocsDir).is_dir() else \"solubility.test.sdf\")\n",
"# Optional: read SDF file and sample 50 mols from it (to keep this notebook light)\n",
"df = (\n",
" mols2grid.sdf_to_dataframe(SDF_FILE)\n",
" .sample(50, random_state=123)\n",
Expand Down Expand Up @@ -302,7 +303,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.12"
"version": "3.7.12"
}
},
"nbformat": 4,
Expand Down
18 changes: 12 additions & 6 deletions mols2grid/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@


class _JSCallback(NamedTuple):
"""Class that holds JavaScript code for running a callback function. If an external
library is required for the callback to function correctly, it can be passed in
the optional ``library_src`` as a ``<script>`` tag.
"""
code: str
library_src: Optional[str] = None

Expand Down Expand Up @@ -41,7 +45,7 @@ def _get_title_field(title):
return "${data['" + title + "']}" if title else None


def info(title="SMILES", img_size=(400, 300), style="max-width: 80%;"):
def info(title="SMILES", img_size=(400, 300), style="max-width: 80%;") -> _JSCallback:
"""Displays a bigger image of the molecule, alongside some useful descriptors:
molecular weight, number of Hydrogen bond donors and acceptors, TPSA, Crippen ClogP
and InChIKey.
Expand All @@ -56,7 +60,7 @@ def info(title="SMILES", img_size=(400, 300), style="max-width: 80%;"):
style : str
CSS style applied to the modal window.
"""
return make_popup_callback(
code = make_popup_callback(
title=_get_title_field(title),
js=f"""
let mol = RDKit.get_mol(data["SMILES"]);
Expand All @@ -80,14 +84,15 @@ def info(title="SMILES", img_size=(400, 300), style="max-width: 80%;"):
</div>""",
style=style,
)
return _JSCallback(code=code)


def show_3d(
title="SMILES",
query=["pubchem", "cactus"],
height="350px",
style="max-width: 80%"
):
) -> _JSCallback:
"""Queries the API(s) listed in ``query`` using the SMILES of the structure, to
fetch the 3D structure and display it with ``3Dmol.js``
Expand All @@ -104,7 +109,7 @@ def show_3d(
"url": "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/smiles/{}/SDF?record_type=3d",
"format": "sdf",
"field": "SMILES",
"encode": true,
"encode": True,
}
In this example, the value in the ``SMILES`` field will be URI-encoded and
Expand All @@ -131,7 +136,7 @@ def external_link(
field="SMILES",
url_encode=False,
b64_encode=True,
):
) -> _JSCallback:
"""Opens an external link using ``url`` as a template string and the value in the
corresponding ``field``. The value can be URL-encoded or base64-encoded if needed.
Expand All @@ -154,9 +159,10 @@ def external_link(
"""
if url_encode and b64_encode:
raise ValueError("Setting both URL and B64 encoding is not supported")
return env.get_template('js/callbacks/external_link.js').render(
code = env.get_template('js/callbacks/external_link.js').render(
url=url,
field=field,
url_encode=url_encode,
b64_encode=b64_encode,
)
return _JSCallback(code=code)
2 changes: 1 addition & 1 deletion mols2grid/molgrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,7 +562,7 @@ def to_pages(self, subset=None, tooltip=None, n_cols=5, n_rows=3,
tooltip_trigger = tooltip_trigger.replace("click", "")
if isinstance(callback, _JSCallback):
if custom_header and callback.library_src:
custom_header += callback.library_src
custom_header = callback.library_src + custom_header
else:
custom_header = callback.library_src
callback = callback.code
Expand Down
4 changes: 2 additions & 2 deletions mols2grid/templates/js/callbacks/external_link.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const field = "{{ field }}";
const field = {{ field | tojson }};
let value = data[field];
let url = "{{ url }}";
let url = {{ url | tojson }};

{% if url_encode %}
value = encodeURIComponent(value);
Expand Down
22 changes: 21 additions & 1 deletion mols2grid/templates/js/callbacks/show_3d.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,26 @@ function show_3d(data, apis_or_custom_resolver, viewer) {
viewer.addModel(data, resolver.format);
viewer.setStyle({}, {stick: {}});
viewer.zoomTo();
viewer.setHoverable(
{}, 1,
function(atom, viewer, event, container) {
if (!atom.label) {
atom.label = viewer.addLabel(
atom.serial + ':' + atom.atom, {
position: atom,
backgroundColor: 'mintcream',
fontColor:'black'
}
);
}
},
function(atom, viewer) {
if (atom.label) {
viewer.removeLabel(atom.label);
delete atom.label;
}
}
);
viewer.render();
},
error: function(hdr, status, err) {
Expand All @@ -58,6 +78,6 @@ $(document).ready(function() {
let config = { backgroundColor: 'white' };
let viewer = $3Dmol.createViewer(element, config);
// prepare query to fetch 3D SDF from SMILES
let apis_or_custom_resolver = {{ query }};
let apis_or_custom_resolver = {{ query | tojson }};
show_3d(data, apis_or_custom_resolver, viewer);
});

0 comments on commit 7723b24

Please sign in to comment.