cpmech / plotpy

Rust plotting library using Python (Matplotlib)
MIT License
65 stars 6 forks source link

Run python code in rust directly through pyo3 #84

Closed wangjiawen2013 closed 1 month ago

wangjiawen2013 commented 1 month ago

Hi,

As is said in https://github.com/cpmech/plotpy/issues/58#issuecomment-2303621266 "I assume some of the crates wouldn't have save in the name because they don't need to save a file in order to show it - i.e. they just print out the image data directly to stdout without creating any files."

The working strategy of plotpy is practical but inefficient, especially when the dataset is larger. I am trying to run python code in rust directly without saving them to the disk. This is a minimal example: Cargo.toml:

[package]
name = "abc"
version = "0.1.0"
edition = "2021"

[dependencies]
plotpy = {git = "https://github.com/cpmech/plotpy"}
pyo3 = { version = "0.22.2", features=["auto-initialize"] }

main.rs

use pyo3::prelude::*;

fn main() -> PyResult<()> {
    let b: &str = "import numpy as np\n\
                   from matplotlib import pyplot as plt\n\
                   path='boxplot.svg'\n\
                   x=np.array([[1,2,3,4,5,],[2,3,4,5,6,],[3,4,5,6,7,],[4,5,6,7,8,],[5,6,7,8,9,],[6,7,8,9,10,],],dtype=float)\n\
                   positions=[1,2,3,4,5,]\n\
                   p=plt.boxplot(x,sym=r'b+',vert=False,whis=1.5,positions=positions,widths=0.5)\n\
                   plt.savefig(path)\n";
    Python::with_gil(|py| Python::run_bound(py, b, None, None))
}

I ran the "buffer" from plotpy in pyo3 successfully without any interaction with disk. And we perhaps can even get svg string from matplotlib and showing jupyter directly without saving the figure (such as through Try using StringIO to avoid writing any file-like object to disk). This is only a minimal example. I think a great effort is needed if we adopt this strategy. But now we can keep an eye on it in the future.

cpmech commented 1 month ago

It sounds interesting. I didn't know we could fetch dependencies via git and wasn't aware of pyo3. Thanks.

cpmech commented 1 month ago

I've read a little about Pyo3, but unfortunately, I won't have the time to implement it. The approach of saving an SVG (or PNG) file has worked for me for years. I'll close this for now, but the possibility of using Pyo3 is on the table as a future PR.