chemosim-lab / ProLIF

Interaction Fingerprints for protein-ligand complexes and more
https://prolif.readthedocs.io
Apache License 2.0
337 stars 66 forks source link

Saving interaction JS to file #163

Open richardjgowers opened 8 months ago

richardjgowers commented 8 months ago

I'd really like the ipython notebook widget saved to png/svg. This is probably a pain, has it been looked into previously?

cbouy commented 8 months ago

Did a bit of testing, this seems to work:

from prolif.plotting.network import LigNetwork
from uuid import uuid4
from html import escape
from IPython.display import HTML, Javascript

class BetterLigNetwork(LigNetwork):
    def display(self, **kwargs):
        """Prepare and display the network"""
        html = self._get_html(**kwargs)
        self.uuid = uuid4().hex
        iframe = (
            '<iframe id="{uuid}" width="{width}" height="{height}" frameborder="0" '
            'srcdoc="{doc}"></iframe>'
        )
        return HTML(
            iframe.format(width=self.width, height=self.height, doc=escape(html), uuid=self.uuid)
        )

    def save_png(self):
        code = """
        var iframe = document.getElementById("%(uuid)s");
        var iframe_doc = iframe.contentWindow.document;
        var canvas = iframe_doc.getElementsByTagName("canvas")[0];
        var link = document.createElement("a");
        link.href = canvas.toDataURL();
        link.download = "prolif-lignetwork.png"
        link.click();
        """ % {"uuid": self.uuid}
        return Javascript(code)

net = BetterLigNetwork.from_fingerprint(fp, ligand_mol)
net.display()

and when you're done drag-n-dropping things around, you'd simply run net.save_png(). You won't get the legend in the export though but that's less problematic.

Probably worth adding to the codebase at some point!