tskit-dev / pyslim

Tools for dealing with tree sequences coming to and from SLiM.
MIT License
27 stars 23 forks source link

Jupyter-book format, SLiM cell magic #137

Closed hyanwong closed 3 years ago

hyanwong commented 3 years ago

It would be nice to have the code in the docs actually execute and produce output, presumably by transferring the docs to the tskit-docs Jupyter-book format.

One nice thing is that, if we have access to a SLiM executable, we can easily run the SLiM examples by defining our own cell magic, as follows:

from IPython.core.magic import register_cell_magic
import subprocess

@register_cell_magic
def slim(line, cell):
    args = line.split()
    subprocess.run(["slim"] + args, input=cell, text=True)

Then for the cells containing SLiM code, we can simply do

%%slim -s 23
initialize() {
    initializeTreeSeq();
    // etc
}
2000 late() {
   sim.treeSeqOutput("my_sim.trees");
}

And then we should have access to the tree sequence file output by the SLiM simulation

import pyslim
pyslim.load("my_sim.trees")
jeromekelleher commented 3 years ago

Very neat. Could you tell pygments to treat the SLiM cells a bit like R for code highlighting (I assume R is the closest common language?)

petrelharp commented 3 years ago

oooo, this would be nice (and magic). I suggested on slack that the file still live outside the notebook, but I guess this is better because you can then edit it and re-run inside of the notebook.

petrelharp commented 3 years ago

I've switched over to jupyterbook, but have not done this magic. It's kinda nice to have a separate .slim script so that you can run slim on it more easily? I'm going to close this, but feel free to re-open (and/or go ahead and do it) if you think it's worthwhile.

hyanwong commented 2 years ago

OK, here's nicer Jupyterbook code to get the book to execute a SLiM file and also display the contents. I've prettified it by adding the filename on the top left:

```{code-cell}
:tags: ["remove-cell"]
import subprocess
from IPython.display import display, Code, HTML
def show_and_execute_slim_file(filename):
    display(HTML(f'<div style="text-align: right; font-size: 80%; font-weight: bold">{filename}</div>'))
    display(Code(filename=filename, language='r'))
    subprocess.run(["slim", filename])
```

```{code-cell}
:tags: ["remove-input"]
show_and_execute_slim_file("data/forward.slim")
```

```{code-cell}
import pyslim
import numpy as np

from IPython.display import SVG
ts = pyslim.load("slim_output.trees")
SVG(ts.simplify(np.arange(10)).first())
```

Screenshot from a jupyterbook

Screenshot 2021-12-07 at 16 18 23