Metadata-Version: 2.4
Name: st_oxview
Version: 2.0.0
Summary: A Streamlit component for coarse-grained DNA/RNA visualization with OxView
Home-page: https://github.com/Lucandia/st_oxview
Author: Luca Monari
Author-email: Luca.Monari@mr.mpg.de
License: GPL-3.0-or-later
Project-URL: Source, https://github.com/Lucandia/st_oxview
Project-URL: Issues, https://github.com/Lucandia/st_oxview/issues
Keywords: streamlit,oxDNA,oxView,DNA,RNA,visualization
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Topic :: Scientific/Engineering :: Visualization
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: streamlit
Requires-Dist: matplotlib
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: project-url
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# Streamlit Oxview Component

A Streamlit component for the display of coarse-grained DNA/RNA 3D models.
It is a wrapper around the [oxdna-viewer](https://github.com/sulcgroup/oxdna-viewer.git).
The viewer's own colour-bar legend is not drawn, so the 3D view fills the frame.

## Installation

**Python 3.10 or newer. This component requires access to write files to a cache directory.**

```bash
pip install st_oxview
```

The component serves its assets from disk, from a per-user cache directory
(`~/Library/Caches/st_oxview` on macOS, `%LOCALAPPDATA%\st_oxview\cache` on
Windows, `$XDG_CACHE_HOME/st_oxview` elsewhere) rather than the system temp
directory, which the OS reaps while a long-lived app is still open.

## Example

![Alt Text](https://github.com/Lucandia/st_oxview/blob/main/example.png?raw=true)

Look at the [example](https://stoxview.streamlit.app/) for a streamlit Web App:

[![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://stoxview.streamlit.app/)

## Usage

### Display with drag and drop

You can make a empty oxview fram and drag and drop the files to the frame.

```python
import streamlit as st
from st_oxview import oxview_from_file

success = oxview_from_file()
```

*Just drag and drop the files to the frame.*


### Display from file paths

```python
import streamlit as st
from st_oxview import oxview_from_file

success = oxview_from_file(configuration=path_to_conf, # path to the configuration file
                           topology=path_to_topo,      # path to the topology file
                           forces=None,                # path to the forces file
                           pdb=None,                   # path to the pdb file
                           js_script=None,             # path to the javascript script file
                           colormap=None,              # name of the Matplotlib colormap
                           index_colors=(),            # one integer per nucleotide, spread over the colormap
                           selected=(),                # nucleotide indices to select in the viewer
                           frame_id=None,              # ID of the oxView frame: if a frame ID is set, it will be reused instead of creating a new frame
                           width='99%',                # width of the viewer frame
                           height=500,                 # height of the viewer frame
                           reset_scene=True,           # clear the scene before loading the structure
                           reset_camera=False,         # also recentre the camera when reusing a frame
                           scale_bar=False,            # draw a nanometre scale bar in the corner
                           pick=False,                 # report clicks in the 3D view
                           key=None,                   # streamlit component key
                        )
```

When `pick` is False, the component returns True if the visualization is successfully created and False otherwise. When `pick` is True, the component returns the clicked nucleotide's index the first run after a click, otherwise `None`.

### Display from text

```python
import streamlit as st
from st_oxview import oxview_from_text

with open("configuration.dat", "r") as f:
    conf_text = f.read()

with open("topology.top", "r") as f:
    topo_text = f.read()

success = oxview_from_text(configuration=conf_text, # text of the configuration file
                           topology=topo_text,      # text of the topology file
                           forces=None,             # text of the forces file
                           pdb=None,                # text of the pdb file
                           js_script=None,          # text of the javascript script file
                           colormap=None,           # name of the Matplotlib colormap
                           index_colors=(),         # one integer per nucleotide, spread over the colormap
                           selected=(),             # nucleotide indices to select in the viewer
                           width='99%',             # width of the viewer frame
                           height=500,              # height of the viewer frame
                           reset_scene=True,        # clear the scene before loading the structure
                           reset_camera=False,      # also recentre the camera when reusing a frame
                           scale_bar=False,         # draw a nanometre scale bar in the corner
                           pick=False,              # report clicks in the 3D view
                           key=None)                # streamlit component key

```

When `pick` is False, the component returns True if the visualization is successfully created and False otherwise. When `pick` is True, the component returns the clicked nucleotide's index the first run after a click, otherwise `None`.

### Colouring the nucleotides

`index_colors` takes one integer per nucleotide, in load order (the order of
the topology file). The chosen `colormap` is stretched over the range of those
values, so `range(n)` paints a gradient along the structure, while `0`/`1`
flags paint two groups.

```python
success = oxview_from_text(configuration=conf_text,
                           topology=topo_text,
                           colormap="Reds",
                           index_colors=list(range(n_nucleotides)),
                           key="gradient")
```

### Picking and selecting

`pick=True` reports clicks in the 3D view: the function returns the clicked
nucleotide's index — numbered exactly like `index_colors` — on the first run
after the click, and `None` afterwards, so an old click cannot keep overriding
a selection made some other way. It needs a `key`.

`selected` goes the other way: the nucleotides whose indices you pass get
oxView's own selection — its selection colour on top of whatever they are
already coloured with, and a slightly larger scale. The colouring is left
alone, so a colormap overlay stays visible underneath. Re-sending the
structure clears the selection, so `selected` is re-applied on every render.

Together they make a two-way link between the 3D view and the rest of the app:

```python
import streamlit as st
from st_oxview import oxview_from_text

if "picked" not in st.session_state:
    st.session_state.picked = []

clicked = oxview_from_text(configuration=conf_text,
                           topology=topo_text,
                           colormap="Reds",
                           index_colors=list(range(n_nucleotides)),
                           selected=st.session_state.picked,
                           frame_id=1,
                           pick=True,
                           key="viewer")

if clicked is not None:
    # select the whole strand/domain the clicked nucleotide belongs to
    st.session_state.picked = my_domain_of(clicked)
    st.rerun()
```

### Reusing a frame

Pass the same `frame_id` to keep rendering into the same viewer instead of
building a new one on every rerun — the camera then stays where the user put
it. `reset_scene=True` (the default) clears the scene before loading, which is
what you want when the structure itself changed; with `reset_scene=False` the
files are dropped onto the structure already in the viewer, which is how a
colour overlay is updated without re-sending the whole model.
`reset_camera=True` additionally recentres the camera.


### Display from an OxView JSON file

You can load a saved OxView scene directly from a `.oxview` file with `oxview_from_json`.

#### From a local `.oxview` file

```python
import streamlit as st
from st_oxview import oxview_from_json

with open("scene.oxview", "r", encoding="utf-8") as f:
    scene_text = f.read()

success = oxview_from_json(scene_data=scene_text,  # text content of the .oxview file
                           frame_id=None,          # if None, the component creates a new frame
                           width='99%',            # width of the viewer frame
                           height=500,             # height of the viewer frame
                           key='oxview_json')      # streamlit component key
```

#### From a Streamlit file uploader

```python
import streamlit as st
from st_oxview import oxview_from_json

json_file = st.file_uploader("Upload an OxView file", type=["oxview"])

if json_file is not None:
    success = oxview_from_json(scene_data=json_file.getvalue(),  # uploaded file content
                               frame_id=None,
                               width='99%',
                               height=500,
                               key='oxview_json_upload')
```

Scene_data can be provided as:

- a Python dict
-  a JSON str
- the bytes returned by st.file_uploader(...).getvalue()

The function returns a boolean value indicating whether the scene was successfully processed and displayed.

## Housekeeping

Each process copies the component's assets into its own folder under the cache
directory and removes it again when it exits. That last step only happens on a
clean exit, so an app that is killed or crashes leaves its folder behind —
assets and all — and the cache directory is deliberately one the OS does not
reap, so nothing else would ever clear it.

Both of these run by themselves; they are exported so an app can also tidy up
on demand:

```python
from st_oxview import clear_cache, trim_temp_files

clear_cache()            # drop the folders of viewers whose process is gone
                         # (called on import, so a restart already cleans up)
trim_temp_files(keep=32) # drop the per-render files no longer needed
                         # (called after every render)
```

Every render writes a fresh set of files — configuration, topology, colour
overlay, injected scripts — into the working folder, so without
`trim_temp_files` a long session with a large structure grows that folder by
megabytes per rerun.

## Tests

The 3D view is oxView in an iframe and is not testable from here, but the
bookkeeping around it is: the working folders on disk, and turning a click
reported by the viewer into a value the calling app sees exactly once.

```
pytest
```

## How to cite:

Please include this citation if the OxView Component is used in an academic study:

```
Lucandia. Lucandia/st_oxview; Zenodo, 2024. https://zenodo.org/doi/10.5281/zenodo.12515559.
```

[![DOI](https://zenodo.org/badge/819322738.svg)](https://zenodo.org/doi/10.5281/zenodo.12515559)


## License

Code is licensed under the GNU General Public License v3.0 ([GPL-3.0](https://www.gnu.org/licenses/gpl-3.0.en.html))

[![License: GPL-3.0](https://img.shields.io/badge/License-GPL%20v3-lightgrey.svg)](https://www.gnu.org/licenses/gpl-3.0.en.html)
