Commit 25ee0c62 authored by amichaut's avatar amichaut
Browse files

added galaxy tutorial to doc

parent 4e994761
Pipeline #75332 passed with stages
in 18 seconds
......@@ -18,7 +18,7 @@ Trajectories can also be plotted on the original image in 2D or 3D using custom
The filtered subsets can then be analyzed either independently or compared. This filtering section also provides a tool
for selecting specific trajectories based on spatiotemporal criteria which can be useful to perform fate mapping and back-tracking.
**Track Analyzer** is distributed as two versions: an installation-free web-base tool run on [Galaxy](https://galaxyproject.org/), and full version run on a user-friendly Jupyter notebook. On both versions, **Track Analyzer** can be run without any programming knowledge using its graphical interface. The full version interface is launched by running a [Jupyter notebook](https://jupyter.org/) containing widgets allowing the user to load data and set parameters without writing any code.
**Track Analyzer** is distributed as two versions: an [installation-free web-base interface](https://galaxy.pasteur.fr/root?tool_id=toolshed.pasteur.fr/repos/rplanel/track_analyzer/track-analyzer/0.1.0) run on [Galaxy](https://galaxyproject.org/), and full version run on a user-friendly Jupyter notebook. On both versions, **Track Analyzer** can be run without any programming knowledge using its graphical interface. The full version interface is launched by running a [Jupyter notebook](https://jupyter.org/) containing widgets allowing the user to load data and set parameters without writing any code.
![screenshot_1](https://gitlab.pasteur.fr/track-analyzer/track-analyzer/-/raw/master/resources/screenshot_1.png)
......@@ -73,14 +73,15 @@ To run track-analyzer
## Installation-free version
The installation-free online version is available [here](https://galaxy.pasteur.fr/root?tool_id=toolshed.pasteur.fr/repos/rplanel/track_analyzer/track-analyzer/0.1.0). It is run on the web-base platform [Galaxy](https://galaxyproject.org/), which is easy to use (some documentation regarding Galaxy is available [here](https://training.galaxyproject.org/training-material/)).
The installation-free online version is available [here](https://galaxy.pasteur.fr/root?tool_id=toolshed.pasteur.fr/repos/rplanel/track_analyzer/track-analyzer/0.1.0). It is run on the web-base platform [Galaxy](https://galaxyproject.org/), which is easy to use (some documentation regarding Galaxy is available [here](https://training.galaxyproject.org/training-material/)). A quickstart tutorial to Galaxy's interface is presented in Track Analyzer [documentation](https://track-analyzer.pages.pasteur.fr/track-analyzer/).
## Documentation
You can find a complete documentation [here](https://track-analyzer.pages.pasteur.fr/track-analyzer/)
You can find a complete documentation [here](https://track-analyzer.pages.pasteur.fr/track-analyzer/).
## Troubleshooting
The 3D visualization and the drawing selection tool depend on the [napari](https://napari.org/) package.
- The 3D visualization and the drawing selection tool depend on the [napari](https://napari.org/) package.
The installation of this package can lead to issues depending on your system.
If you are not able to solve this installation, you will not be able to have access to 3D rendering. However, you will still be able to
use **Track Analyzer** without the drawing tool, by using coordinates sliders in the graphical interface.
- The execution of blocks in the Jupyter notebook can be buggy because of the large number of widgets. If you can't normally execute a block by pressing Shift+Enter, use the Execute button at the top of the notebook.
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
......@@ -60,6 +60,17 @@ Using Galaxy (recommended for a first trial)
The installation-free online version is available `here <https://galaxy.pasteur.fr/root?tool_id=toolshed.pasteur.fr/repos/rplanel/track_analyzer/track-analyzer/0.1.0>`_. It is run on the web-base platform `Galaxy <https://galaxyproject.org/>`_, which is easy to use (some documentation regarding Galaxy is available `here <https://training.galaxyproject.org/training-material/>`_). This online version is slightly limited compared to the full version run on Jupyter notebook. Jupyter notebook offers 3D visualization and hand-drawing data selection using a `Napari <https://napari.org/>`_ viewer. Moreover, loaded data are computed step by step throughout the pipeline, which provides the user with a better interactivity with the data. Conversely, on Galaxy, the user needs to enter numerical parameters before the analysis can be run.
A complete documentation about Galaxy is available `here <https://training.galaxyproject.org/training-material/>`_. Here's a quick overview of Galaxy's interface.
.. image:: ../_static/screenshots/galaxy_help.jpeg
:align: center
1. Upload your data to Galaxy. If you want to keep track of your history of analysis, you can create a user account.
2. Choose your input files that were previously uploaded.
3. Enter the parameters necessary to your analysis.
4. Hit the execution button to launch the execution on Galaxy's cluster.
5. You can find in the history panel all the output of each analysis job. For each of the output element, you can have a quick look (6), or save it (7). Note that when you display output plots, it is not very intuitive how to display again the main interface. The double arrow 'Run this job again' button (8) displayed on every log file, is then useful. If you press the 'Run this job again' button, the interface will be displayed with the exact same set of parameters as the corresponding job.
Using a Jupyter notebook (recommended for advanced options)
===========================================================
......
......@@ -1750,7 +1750,7 @@
},
{
"cell_type": "code",
"execution_count": 21,
"execution_count": 24,
"metadata": {
"scrolled": false
},
......@@ -1782,7 +1782,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "4ac66c34f7df47a3aee82baef868da9c",
"model_id": "f286c072d94a46fa88a23d51f9dbf172",
"version_major": 2,
"version_minor": 0
},
......@@ -1808,7 +1808,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "829c5e46ed1c49be86c234e6d392ab19",
"model_id": "7c04eee901fb48068e933d12a0c88e87",
"version_major": 2,
"version_minor": 0
},
......@@ -1858,7 +1858,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "294c0f65f5d84cb7885545d4bddcfb27",
"model_id": "daa559eb7d4748af82573a322cde0fad",
"version_major": 2,
"version_minor": 0
},
......@@ -1884,7 +1884,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "f8075c3bea7c44b18a18ed0f0d1b102a",
"model_id": "ea9819c28aab4e238e35f2f92ee29640",
"version_major": 2,
"version_minor": 0
},
......@@ -1910,7 +1910,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "677fcc4474b74c2b8c123a33c26b1b86",
"model_id": "54f5f1c36c024162904643ff9ab5d1c6",
"version_major": 2,
"version_minor": 0
},
......@@ -1936,7 +1936,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "8bf922ba40cc4d1abc5ea169793ca8f9",
"model_id": "2d6ffe4d651e458cae9acb783d181b1e",
"version_major": 2,
"version_minor": 0
},
......@@ -1986,7 +1986,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "fde4595176ea4f88b3b4e4e9d1fbd7a2",
"model_id": "b165b58d91ae4403ab3aee34b8563893",
"version_major": 2,
"version_minor": 0
},
......@@ -2000,7 +2000,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "3de46bf1eeda4690a31f5c2111b77d98",
"model_id": "169c0f06dfa64076924fae3b26ae61fb",
"version_major": 2,
"version_minor": 0
},
......@@ -2014,7 +2014,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "b4689e26aac447ff85b85fb0642d3403",
"model_id": "bb30352510714bdfb1b126adee0d85fb",
"version_major": 2,
"version_minor": 0
},
......@@ -2064,7 +2064,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "7145dd75f2004451adccb08906992a63",
"model_id": "ca801709e8ea4fe2a92d42be473d86cc",
"version_major": 2,
"version_minor": 0
},
......@@ -2090,7 +2090,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "44a52f1c96d14cd2966c0c62dad0bbb8",
"model_id": "24a493f6d69c4568944d36e43a483c47",
"version_major": 2,
"version_minor": 0
},
......@@ -2116,7 +2116,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "f6c3a36a0426440aa2e982c09a8d6ab2",
"model_id": "6ccf9215f1f142b186e94e6764bb72e9",
"version_major": 2,
"version_minor": 0
},
......@@ -2142,7 +2142,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "8232ed000e66498f9bd9003c6e4ca88a",
"model_id": "471269b5d46248cca2e5d7492a3b349a",
"version_major": 2,
"version_minor": 0
},
......@@ -2156,7 +2156,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "431132fb60114e84acd25a403be701d8",
"model_id": "205b321d398e4601a40590200572107f",
"version_major": 2,
"version_minor": 0
},
......@@ -2170,7 +2170,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "7e78d15825b8491ba2e6b70bc02b56ca",
"model_id": "6b4c82e6b4074acf9bed3af3cdcc9c6f",
"version_major": 2,
"version_minor": 0
},
......@@ -2196,7 +2196,7 @@
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "1821c409809d4cb2a07428ca1b18d57a",
"model_id": "be00338bef18437ab06deef743f85fc2",
"version_major": 2,
"version_minor": 0
},
......@@ -2400,7 +2400,7 @@
},
{
"cell_type": "code",
"execution_count": 23,
"execution_count": 25,
"metadata": {
"scrolled": false
},
......@@ -2416,6 +2416,20 @@
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "46354d4496204b4982fc9b9148e34981",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Tab(children=(Accordion(children=(VBox(children=(Dropdown(description='parameter', index=14, options=('track',…"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
......
%% Cell type:code id: tags:
``` python
import os
import os.path as osp
import pickle
import napari
from skimage import io
from skimage.color import rgb2gray
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import seaborn as sns
import pandas as pd
import warnings
import ipywidgets as widgets
from ipywidgets import HBox, VBox, interact, interact_manual, TwoByTwoLayout, GridspecLayout, Label, AppLayout
from ipyfilechooser import FileChooser
from IPython.display import HTML, Markdown, display, clear_output
from traitlets import traitlets
from track_analyzer import prepare as tpr
from track_analyzer import plotting as tpl
from track_analyzer import calculate as tca
from track_analyzer.scripts.analyze_tracks import traj_analysis
from track_analyzer.scripts.analyze_maps import map_analysis
from track_analyzer.scripts.compare_datasets import compare_datasets
from napari.settings import get_settings
get_settings().application.ipy_interactive = False # disable interactive usage of Napari viewer (necessary for tpr.get_coordinates)
warnings.filterwarnings('ignore')
%matplotlib inline
def printmd(string):
display(Markdown(string))
cwd = os.getcwd() # working directory
plot_param = tpl.make_plot_config() # some config parameters
color_list = plot_param['color_list'] # a list of colors often used
# Hide code
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''')
```
%%%% Output: stream
_ _ _
| |_ _ __ __ _ ___| | __ __ _ _ __ __ _| |_ _ _______ _ __
| __| '__/ _` |/ __| |/ / / _` | '_ \ / _` | | | | |_ / _ \ '__|
| |_| | | (_| | (__| < | (_| | | | | (_| | | |_| |/ / __/ |
\__|_| \__,_|\___|_|\_\ \__,_|_| |_|\__,_|_|\__, /___\___|_|
|___/
Track Analyzer - Quantification and visualization of tracking data.
Developed and maintained by Arthur Michaut: arthur.michaut@gmail.com
%%%% Output: execute_result
<IPython.core.display.HTML object>
%% Cell type:markdown id: tags:
# Preparation module
## Loading data
%% Cell type:code id: tags:
``` python
#choose positions file
fc_table = FileChooser(cwd)
fc_table.use_dir_icons = True
fc_table.title = '<b>Tracking data file</b>'
sep_wid = widgets.Dropdown(options=[',',';', 'tab', ' '],value=',',description='column separator:',style={'description_width': 'initial'})
header_wid = widgets.Dropdown(options=['yes','no'],value='yes',description='first row = column names?',style={'description_width': 'initial'})
printmd("""**Browse your file system to the table of tracked data (only .txt and .csv are supported)**""")
display(fc_table,sep_wid,header_wid)
```
%%%% Output: display_data
**Browse your file system to the table of tracked data (only .txt and .csv are supported)**
%%%% Output: display_data
%%%% Output: display_data
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
# get position file path
data_dir = fc_table.selected_path
data_file = fc_table.selected
if data_file is None:
raise Exception("**ERROR: no data table has been selected**")
# choose image file
printmd("""**(Optional) Browse your file system to the image file**
You can plot your data on your image. The image can be a single image or a stack (a 2D time series or a 3D time series).
Only tif images are supported. """)
fc_im = FileChooser(data_dir)
fc_im.use_dir_icons = True
fc_im.title = '<b>Image file</b>'
display(fc_im)
```
%%%% Output: display_data
**(Optional) Browse your file system to the image file**
You can plot your data on your image. The image can be a single image or a stack (a 2D time series or a 3D time series).
Only tif images are supported.
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
# get image file path
im_file = fc_im.selected
#im_file = "/Users/amichaut/Desktop/Fluo-N3DH-CE/stack.tif"
# analyze image
y_size,x_size = [512,512] #default size of an image to inialize the make info widget
image = tpr.get_image(data_dir,filename=im_file,verbose=True)
if image['image_size'] is not None:
y_size,x_size = image['image_size']
get_image_size = False
else:
get_image_size = True # to call get_image again after info.txt is generated
# swap z and t dimensions if needed
check_swap_wid = False # bool to retrieve swap_wid value if necessary
if image['t_dim'] is not None and image['z_dim'] is not None:
check_swap_wid=True
printmd("If there is an error between t and z dimension, you can swap these dimensions")
swap_wid = widgets.ToggleButton(value=False,description='Swap z and t')
display(swap_wid)
# refresh database and info if needed
database_fn=osp.join(data_dir,'data_base.p')
info_fn=osp.join(data_dir,'info.txt')
printmd("---")
if osp.exists(database_fn):
printmd('The database already exists, do you want to refresh it?')
refresh_db_wid=widgets.ToggleButton(value=False,description='Refresh database')
display(refresh_db_wid)
if osp.exists(info_fn):
printmd("The info.txt file already exists, do you want to refresh it?")
refresh_info_wid=widgets.ToggleButton(value=False,description='Refresh info')
display(refresh_info_wid)
```
%%%% Output: display_data
---
%%%% Output: display_data
The database already exists, do you want to refresh it?
%%%% Output: display_data
%%%% Output: display_data
The info.txt file already exists, do you want to refresh it?
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
printmd("**Don't forget to run this cell!**") # no output cell, make it visible
#swap z and t
if check_swap_wid:
if swap_wid.value:
t_dim = image['t_dim']
z_dim = image['z_dim']
image['t_dim'] = z_dim
image['z_dim'] = t_dim
printmd("**z and t swapped!**")
im = io.imread(image['image_fn'])
printmd("4D image with {} time steps and {} z slices".format(im.shape[image['t_dim']],im.shape[image['z_dim']]))
del im # free memory
# retrieve refresh widgets values
refresh_db=refresh_db_wid.value if osp.exists(database_fn) else True
refresh_info=refresh_info_wid.value if osp.exists(info_fn) else True
# get info
if refresh_info:
length_unit_wid=widgets.Dropdown(options=['um', 'mm', 'au'],value='um',description='Length unit:',style={'description_width': 'initial'})
time_unit_wid=widgets.Dropdown(options=['min', 's', 'hr', 'au'],value='min',description='Time unit:',style={'description_width': 'initial'})
length_sc_wid=widgets.BoundedFloatText(value=1.0,min=0,max=1e4,description='Pixel size:',style={'description_width': 'initial'})
z_sc_wid=widgets.BoundedFloatText(value=0,min=0,max=1e4,description='z step:',style={'description_width': 'initial'})
time_sc_wid=widgets.BoundedFloatText(value=1.0,min=0,max=1e4,description='Frame interval:',style={'description_width': 'initial'})
width_wid=widgets.BoundedIntText(value=x_size,min=0,max=1e4,description='Image width (px):',style={'description_width': 'initial'})
height_wid=widgets.BoundedIntText(value=y_size,min=0,max=1e4,description='Image height (px):',style={'description_width': 'initial'})
left_box = VBox([length_unit_wid, time_unit_wid,width_wid])
right_box = VBox([length_sc_wid, time_sc_wid,height_wid])
box = HBox([left_box, right_box])
printmd("**Information about the data**")
display(box)
printmd("In the data table, are the positions given in pixels or in the length unit (given above)?")
table_unit_wid=widgets.Dropdown(options=['px', 'unit'],value='px',description='Data unit:',style={'description_width': 'initial'})
display(table_unit_wid)
printmd("If the lengthscale in z is different from the xy lengthscale, enter the z step (in length unit). If not, leave it to zero.")
display(z_sc_wid)
wid_list = [length_unit_wid,time_unit_wid,length_sc_wid,time_sc_wid,width_wid,height_wid,table_unit_wid,z_sc_wid]
param_names = ['length_unit','time_unit','lengthscale','timescale','image_width','image_height','table_unit','z_step']
```
%%%% Output: display_data
**Don't forget to run this cell!**
%% Cell type:code id: tags:
``` python
printmd("**Don't forget to run this cell!**") # no output cell, make it visible
# save info as txt file
if refresh_info:
info = {}
with open(info_fn,'w+') as f:
for couple in zip(param_names,wid_list):
info[couple[0]]=couple[1].value
f.write('{}:{}\n'.format(couple[0],couple[1].value))
else:
info = tpr.get_info(data_dir)
image = tpr.get_image(data_dir,filename=im_file,verbose=True)
```
%%%% Output: display_data
**Don't forget to run this cell!**
%% Cell type:code id: tags:
``` python
printmd("**Don't forget to run this cell!**") # no output cell, make it visible
# Set columns identity
if refresh_db:
sep = sep_wid.value if sep_wid.value !='tab' else '\t'
header = None if header_wid.value=='no' else 0
df = pd.read_csv(data_file,sep=sep,header=header)
printmd("**Here are the first rows of the input data table**")
display(df.head(10))
```
%%%% Output: display_data
**Don't forget to run this cell!**
%% Cell type:code id: tags:
``` python
printmd("**Don't forget to run this cell!**") # no output cell, make it visible
if refresh_db:
col_wid_list = []
left_list=[]
right_list=[]
param_list = ['discard','x','y','z','frame','track']
var_list = []
var_wid_dict = {}
custom_var_num = df.shape[1] - 5 # number of columns apart from 'x','y','z','frame','track'
for i in range(custom_var_num):
param_list.append('var_{}'.format(i+1))
var_list.append('var_{}'.format(i+1))
# display the df columns as two columns of widgets
for i,col in enumerate(df.columns):
wid = widgets.Dropdown(options=param_list,value='discard',
description='column {}:'.format(col),
style={'description_width': 'initial'})
col_wid_list.append(wid)
if i<len(df.columns)/2:
left_list.append(wid)
else:
right_list.append(wid)
printmd("""**Select the columns to be used in the analysis: track,frame,x,y,(z).
Leave to "discard" the other ones. If you want to use custom variables, use var_i.**""")
left_box = VBox(left_list)
right_box = VBox(right_list)
display(HBox([left_box, right_box]))
# get the custom variable name and unit
HBox_list = []
for var in var_list:
wid_name = widgets.Text(value='',placeholder='Variable name')
wid_unit = widgets.Text(value='',placeholder='Variable unit')
HBox_list.append(HBox([Label(var+':'),wid_name,wid_unit]))
var_wid_dict[var] = {'name': wid_name, 'unit': wid_unit}
printmd("""**If you selected some custom variables, give their name and unit to be displayed on plots.
You can use Latex, if necessary.**""")
display(VBox(HBox_list))
# deal with gaps in trajectories
printmd("""**Some tracking softwares support to miss objects at some frames. This results in tracks with gaps.
However, this analysis pipeline requires to have continuous tracks. How do you want to handle tracks with gaps:
fill the gaps by linear interpolation or split the track in different tracks?**""")
split_wid=widgets.Dropdown(options=['interpolate','split'],value='interpolate',description='gap resolution:'.format(col),style={'description_width': 'initial'})
display(split_wid)
```
%%%% Output: display_data
**Don't forget to run this cell!**
%% Cell type:code id: tags:
``` python
printmd("**Don't forget to run this cell!**") # no output cell, make it visible
if refresh_db:
col_values = [wid.value for wid in col_wid_list]
for param_ in ['x','y','frame','track']: # mandatory columns
if param_ not in col_values:
raise Exception("You MUST select a column for "+param_)
df.columns = col_values # rename columns
# discard non-relevant columns
col_values = np.array(col_values)
new_cols = col_values[col_values!='discard']
for c in new_cols:
if np.count_nonzero(new_cols==c) > 1: # if repeated element
raise Exception("You have selected several times the column: "+c)
df = df[new_cols]
# get names and units of custom variables
custom_var = {}
for var in var_list:
if var in new_cols:
custom_var[var] = {'name': var_wid_dict[var]['name'].value, 'unit': var_wid_dict[var]['unit'].value}
# retrieve split traj widget value
split_traj = True if split_wid.value=='split' else False
#get dimension
dim_list = ['x','y','z'] if 'z' in df.columns else ['x','y']
# coordinates origin
printmd("""**Do you want to set a custom origin to the coordinates?**""")
printmd("""Select a new origin by drawing on the image (you can choose which dimension to reset)""")
ori_onimage_wid=widgets.ToggleButton(value=False,description='Select on image')
reset_dim_wid=widgets.SelectMultiple(options=dim_list,value=['x','y'],description='Dimensions to reset',style={'description_width': 'initial'})
display(HBox([ori_onimage_wid,reset_dim_wid]))
printmd("""Or directly type in the new origin (in px)""")
origin_coord_wid_list=[]
for dim in dim_list:
origin_coord_wid_list.append(widgets.FloatSlider(value=0,min=0,max=df[dim].max(),step=0.1,description=dim,style={'description_width': 'initial'}))
display(HBox(origin_coord_wid_list))
# axes signs
printmd("""**Do you want to invert the axes?**
Default orientation: x: left->right, y: top->bottom, z: slice number""")
invert_axes_wid=widgets.SelectMultiple(options=dim_list,value=[],description='Axes to invert',style={'description_width': 'initial'})
display(invert_axes_wid)
```
%%%% Output: display_data
**Don't forget to run this cell!**
%% Cell type:code id: tags:
``` python
printmd("**Don't forget to run this cell!**") # no output cell, make it visible
if refresh_db:
if not ori_onimage_wid.value:
origin_coord={}
all_zeros=True
for d,wid in enumerate(origin_coord_wid_list):
origin_coord[dim_list[d]]=wid.value
if wid.value>0:
all_zeros=False
if all_zeros: # if no change of origin
origin_coord = False
set_origin_ = origin_coord
else:
set_origin_ = True
#remove None tracks
df = df[df['track']!='None'] # remove
data = tpr.get_data(data_dir,df=df,refresh=refresh_db,split_traj=split_traj,
set_origin_=set_origin_,image=image,reset_dim=reset_dim_wid.value,
invert_axes=invert_axes_wid.value,custom_var=custom_var)
else:
# reload from database
data = tpr.get_data(data_dir,df=None,refresh=refresh_db)
# useful variables
df = data['df']
lengthscale = data['lengthscale']
timescale = data['timescale']
dim = data['dim']
dimensions = data['dimensions']
custom_var = data['custom_var']
```
%%%% Output: display_data
**Don't forget to run this cell!**
%% Cell type:code id: tags:
``` python
# general plotting configuration
printmd("## General plotting configuration")
fig_w_wid = widgets.BoundedIntText(value=plot_param['figsize'][0],min=0,max=20,
description='Figure width (inches):',style={'description_width': 'initial'})
fig_h_wid = widgets.BoundedIntText(value=plot_param['figsize'][1],min=0,max=20,
description='Figure height (inches):',style={'description_width': 'initial'})
fig_dpi_wid = widgets.BoundedIntText(value=plot_param['dpi'],min=50,max=1e4,
description='Figure resolution (dpi):',style={'description_width': 'initial'})
fig_resfac_wid = widgets.FloatSlider(value=1,min=0.01,max=30,step=0.01,
description='Figure size factor:',style={'description_width': 'initial'})
fig_format_wid = widgets.Dropdown(options=['.png','.svg'],value='.png',
description='Single plot format',style={'description_width': 'initial'})
save_as_stack_wid = widgets.Checkbox(value=True, description='Save as tiff stack')
despine_wid = widgets.ToggleButton(value=plot_param['despine'],
description='despine figure')
replace_color_wid = widgets.BoundedIntText(value=0,min=0,max=20,
description='Number of colors:',style={'description_width': 'initial'})
add_replace_wid = widgets.Dropdown(options=['add','replace'],value='add',
description='add or replace?',style={'description_width': 'initial'})
invert_yaxis_wid = widgets.ToggleButton(value=True,description='y axis origin: top')
export_data_pts_wid = widgets.ToggleButton(value=True,description='export data points')
display(HBox([fig_w_wid,fig_h_wid]),HBox([fig_dpi_wid,fig_format_wid]),despine_wid)
printmd('Adjust figure resolution (if orginal image is too small or too large)')
display(fig_resfac_wid)
printmd('When plotting over timelapse, plot as a multidimensional tiff stack or as a series of individual image')
display(save_as_stack_wid)
printmd('Do you want to add/replace the first default colors used for plotting? Give the number of colors you want to select:')
display(HBox([replace_color_wid,add_replace_wid]))
printmd('How do you want to display the y-axis (standard orientation: origin at top)')
display(invert_yaxis_wid)
printmd('Do you want to export the data points of your plots as .csv files?')
display(export_data_pts_wid)
```
%%%% Output: display_data
## General plotting configuration
%%%% Output: display_data
%%%% Output: display_data
%%%% Output: display_data
%%%% Output: display_data
Adjust figure resolution (if orginal image is too small or too large)
%%%% Output: display_data
%%%% Output: display_data
When plotting over timelapse, plot as a multidimensional tiff stack or as a series of individual image
%%%% Output: display_data
%%%% Output: display_data
Do you want to add/replace the first default colors used for plotting? Give the number of colors you want to select:
%%%% Output: display_data
%%%% Output: display_data
How do you want to display the y-axis (standard orientation: origin at top)
%%%% Output: display_data
%%%% Output: display_data
Do you want to export the data points of your plots as .csv files?
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
printmd("**Don't forget to run this cell!**") # no output cell, make it visible
# replace colors
color_wid_list=[]
for i in range(replace_color_wid.value):
color_wid=widgets.ColorPicker(description='Pick color #{}'.format(i),value=color_list[i])
color_wid_list.append(color_wid)
display(*color_wid_list)
```
%%%% Output: display_data
**Don't forget to run this cell!**
%% Cell type:code id: tags:
``` python
printmd("**Don't forget to run this cell!**") # no output cell, make it visible
# retreive plotting configuration
color_list_=list(color_list)
new_color_list = [color_wid_list[i].value for i in range(replace_color_wid.value)]
if add_replace_wid.value=='replace':
color_list_[:replace_color_wid.value]=new_color_list
else:
color_list_=new_color_list+color_list_
plot_param={'figsize':(fig_w_wid.value,fig_h_wid.value),
'dpi':fig_dpi_wid.value,
'figsize_factor':fig_resfac_wid.value,
'color_list':color_list_,
'format':fig_format_wid.value,
'despine':despine_wid.value,
'invert_yaxis':invert_yaxis_wid.value,
'export_data_pts':export_data_pts_wid.value,
'save_as_stack': save_as_stack_wid.value,
}
```
%%%% Output: display_data
**Don't forget to run this cell!**
%% Cell type:markdown id: tags:
# Filter data
%% Cell type:code id: tags:
``` python
z_step = info['z_step']
if z_step == 0:
z_step = lengthscale # if z_step not given, same as lengthscale
printmd('**View trajectories on a Napari viewer before plotting**')
printmd('If not working, please check Napari installation: https://napari.org/')
printmd('Warning: large image can lead to rendering issues')
if image['z_dim'] is None:
printmd('Warning: you have a 2D+t image, no 3D redering is available then.')
viewer_wid = widgets.Button(value=True, description='Show viewer!')
viewer_wid.on_click(lambda obj: tpl.view_traj(df, image=image, z_step=info['z_step']))
display(viewer_wid)
```
%%%% Output: display_data
**View trajectories on a Napari viewer before plotting**
%%%% Output: display_data
If not working, please check Napari installation: https://napari.org/
%%%% Output: display_data
Warning: large image can lead to rendering issues
%%%% Output: display_data
Warning: you have a 2D+t image, no 3D redering is available then.
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
printmd("Your data can be filtered into subsets. How many subsets do you want to analyze?")
subset_num_wid = widgets.BoundedIntText(value=1,min=1,max=10,description='Number of subsets:',style={'description_width': 'initial'})
display(subset_num_wid)
printmd("If you define several subsets, do you want to analyze them separately or together?")
printmd("If analyzed together, subsets will be plotted together. If analyzed separately, each subset will be plotted on individual plots.")
separate_widget = widgets.ToggleButtons(options=['separately', 'together'], description='Analysis',style={'description_width': 'initial'})
display(separate_widget)
```
%%%% Output: display_data
Your data can be filtered into subsets. How many subsets do you want to analyze?
%%%% Output: display_data
%%%% Output: display_data
If you define several subsets, do you want to analyze them separately or together?
%%%% Output: display_data
If analyzed together, subsets will be plotted together. If analyzed separately, each subset will be plotted on individual plots.
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
# prepare default values for initializing widgets
xlim = [df['x'].min(), df['x'].max()] # maybe use image dimensions instead
ylim = [df['y'].min(), df['y'].max()]
zlim = [df['z'].min(), df['z'].max()] if 'z' in df.columns else []
frame_list = df['frame'].unique()
frame_min = df['frame'].min()
frame_max = df['frame'].max()
# cropping widget lists
xlim_wid_list = []
ylim_wid_list = []
zlim_wid_list = []
drawer_wid_list = []
frame_subset_wid_list = []
min_length_wid_list = []
max_length_wid_list = []
name_wid_list = []
# retrieve drawer coordinates
class LoadedButton(widgets.Button):
"""A button that can holds a value as a attribute."""
def __init__(self, value=None, *args, **kwargs):
super(LoadedButton, self).__init__(*args, **kwargs)
# Create the value attribute.
self.add_traits(value=traitlets.Any(value))
def get_image_coord(ex):
"""Call get_coordinates, display instruction and store coordinates in widget value """
ex.value = tpr.get_coordinates(image,df=df,verbose=True)
# create a set of filtering widget for each subset
for i in range(subset_num_wid.value):
printmd("""### Subset #{}""".format(i + 1))
# subset name
printmd("""You can give it a custom name that will be used for saving data""")
name_wid = widgets.Text(value='', placeholder='optional', description='Subset name:',
style={'description_width': 'initial'})
name_wid_list.append(name_wid)
display(name_wid)
# spatial filtering
xlim_wid = widgets.FloatRangeSlider(value=xlim, min=xlim[0], max=xlim[1], step=1,
description='x range (px):', style={'description_width': 'initial'})
ylim_wid = widgets.FloatRangeSlider(value=ylim, min=ylim[0], max=ylim[1], step=1,
description='y range (px):', style={'description_width': 'initial'})
if len(zlim) > 0:
zlim_wid = widgets.FloatRangeSlider(value=zlim, min=zlim[0], max=zlim[1], step=1,
description='z range (px):', style={'description_width': 'initial'})
drawer_wid = LoadedButton(description="Draw ROI", value={})
drawer_wid.on_click(get_image_coord)
# store widgets
xlim_wid_list.append(xlim_wid)
ylim_wid_list.append(ylim_wid)
drawer_wid_list.append(drawer_wid)
if len(zlim) > 0:
zlim_wid_list.append(zlim_wid)
else:
zlim_wid_list.append(None)
#display
printmd("**Crop a region**")
printmd("You can draw it on the image or select it with the slider (values in pixels)."
"If you do both, only the drawn region will be kept. If you select several regions on the image"
", they will be divided into several subsets")
printmd("Draw using the rectangle shape, hit ENTER while you're done."
"If you want more details about the email viewer please visit https://napari.org/")
if len(zlim) > 0:
display(VBox([drawer_wid, HBox([xlim_wid, ylim_wid, zlim_wid])]))
else:
display(VBox([drawer_wid, HBox([xlim_wid, ylim_wid])]))
# time filtering
frame_subset_wid = widgets.IntRangeSlider(value=[frame_min, frame_max], min=frame_min, max=frame_max, step=1,
description='Frame subset:', style={'description_width': 'initial'})
min_length_wid = widgets.IntSlider(value=frame_min, min=frame_min, max=frame_max + 1, step=1,
description='Minimum traj length:', style={'description_width': 'initial'})
max_length_wid = widgets.IntSlider(value=frame_max + 1, min=frame_min, max=frame_max + 1, step=1,
description='Maximum traj length:', style={'description_width': 'initial'})
# store widgets
frame_subset_wid_list.append(frame_subset_wid)
min_length_wid_list.append(min_length_wid)
max_length_wid_list.append(max_length_wid)
# display
printmd("**Select data based on trajectories duration or frame subset**")
display(HBox([frame_subset_wid, min_length_wid, max_length_wid]))
```
%%%% Output: display_data
### Subset #1
%%%% Output: display_data
You can give it a custom name that will be used for saving data
%%%% Output: display_data
%%%% Output: display_data
**Crop a region**
%%%% Output: display_data
You can draw it on the image or select it with the slider (values in pixels).If you do both, only the drawn region will be kept. If you select several regions on the image, they will be divided into several subsets
%%%% Output: display_data
Draw using the rectangle shape, hit ENTER while you're done.If you want more details about the email viewer please visit https://napari.org/
%%%% Output: display_data
%%%% Output: display_data
**Select data based on trajectories duration or frame subset**
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
# retrieve filters values
def retrieve_region_wid_values(drawer_wid,xlim_wid,ylim_wid,zlim_wid):
"""
Get values of region selection giving priority to drawer widgets over sliders
"""
# xylim
use_sliders = False
drawer_value = drawer_wid.value
if drawer_value: #if not empty
if len(drawer_value['rectangle']) > 0:
#get list of xlim, ylim in case of several ROIs selected
xlim_list = [r['xlim'] for r in drawer_value['rectangle']]
ylim_list = [r['ylim'] for r in drawer_value['rectangle']]
else:
use_sliders = True
else:
use_sliders = True
if use_sliders:
xlim_list = [xlim_wid.value]
ylim_list = [ylim_wid.value]
# zlim
if zlim_wid is None:
zlim = None
else:
zlim = zlim_wid.value
return xlim_list, ylim_list, zlim
filters=[]
for i in range(subset_num_wid.value):
xlim_list, ylim_list, zlim_ = retrieve_region_wid_values(drawer_wid_list[i],
xlim_wid_list[i],
ylim_wid_list[i],
zlim_wid_list[i])
# if several subsets get values of xlim, ylim, while keeping other filters constant
for j in range(len(xlim_list)):
#name
if len(xlim_list) > 1: # if several subsets, modify name: name_number if name is empty: number
name = name_wid_list[i].value + '_{}'.format(j) if name_wid_list[i].value != '' else '{}'.format(j)
else:
name = name_wid_list[i].value
# initialize filter dict
default_filter = tpr.init_filters(data_dir=None, export_config=False)
filt_ = default_filter['filters_list'][0]
# fill info
filt_['xlim'] = xlim_list[j]
filt_['ylim'] = ylim_list[j]
filt_['zlim'] = zlim_
filt_['frame_subset'] = frame_subset_wid_list[i].value
filt_['min_traj_len'] = min_length_wid_list[i].value
filt_['max_traj_len'] = max_length_wid_list[i].value
filt_['name'] = name
# add to filter list
filters.append(filt_)
printmd("**Select specific trajectories**")
printmd("You can select specific sets of trajectories. "
"This tool can be useful to perform fate mapping or retrospective mapping. "
"If you selected several subsets before, this specific set will be applied to all of the subsets."
)
printmd("How many sets of trajectories do you want to select?")
set_num_wid = widgets.BoundedIntText(value=0,min=0,max=10,description='Number of sets:',style={'description_width': 'initial'})
display(set_num_wid)
#or by selecting trajectories in a specific region at a specific frame. "
#just by giving a list of ids,
```
%%%% Output: display_data
**Select specific trajectories**
%%%% Output: display_data
You can select specific sets of trajectories. This tool can be useful to perform fate mapping or retrospective mapping. If you selected several subsets before, this specific set will be applied to all of the subsets.
%%%% Output: display_data
How many sets of trajectories do you want to select?
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
printmd("**Don't forget to run this cell!**") # no output cell, make it visible
# select specific trajectories
# track selection widget lists
track_name_wid_list = []
track_xlim_wid_list = []
track_ylim_wid_list = []
track_zlim_wid_list = []
track_drawer_wid_list = []
track_frame_subset_wid_list = []
track_list_wid_list = []
for i in range(set_num_wid.value):
printmd("""### Set #{}""".format(i + 1))
# subset name
printmd("""You can give it a custom name that will be used for saving data""")
track_name_wid = widgets.Text(value='', placeholder='optional', description='Set name:',
style={'description_width': 'initial'})
track_name_wid_list.append(track_name_wid)
display(track_name_wid)
track_list_wid = widgets.Text(value='', placeholder='comma separated ids', description='Id list:')
track_xlim_wid = widgets.FloatRangeSlider(value=xlim, min=xlim[0], max=xlim[1], step=1,
description='x range (px):', style={'description_width': 'initial'})
track_ylim_wid = widgets.FloatRangeSlider(value=ylim, min=ylim[0], max=ylim[1], step=1,
description='y range (px):', style={'description_width': 'initial'})
if len(zlim) > 0:
track_zlim_wid = widgets.FloatRangeSlider(value=zlim, min=zlim[0], max=zlim[1], step=1,
description='z range (px):', style={'description_width': 'initial'})
track_frame_subset_wid = widgets.IntRangeSlider(value=[frame_min, frame_max], min=frame_min, max=frame_max, step=1,
description='Frame intervalle:', style={'description_width': 'initial'})
track_drawer_wid = LoadedButton(description="Draw ROI", value={})
track_drawer_wid.on_click(get_image_coord)
# store widgets
track_list_wid_list.append(track_list_wid)
track_xlim_wid_list.append(track_xlim_wid)
track_ylim_wid_list.append(track_ylim_wid)
track_drawer_wid_list.append(track_drawer_wid)
track_frame_subset_wid_list.append(track_frame_subset_wid)
if len(zlim) > 0:
track_zlim_wid_list.append(track_zlim_wid)
else:
track_zlim_wid_list.append(None)
#display
printmd("Give a list of ids or select trajectories in a specific region during a specific frame intervalle using the viewer.")
printmd("Use the ids given by the track analyzer, you need to generate the database once to access them, "
"(visualizing the trajectories with the printed labels can be helpful)")
if len(zlim) > 0:
display(VBox([track_list_wid,track_drawer_wid, HBox([track_xlim_wid, track_ylim_wid, track_zlim_wid]),track_frame_subset_wid]))
else:
display(VBox([track_list_wid,track_drawer_wid, HBox([track_xlim_wid, track_ylim_wid]),track_frame_subset_wid]))
```
%%%% Output: display_data
**Don't forget to run this cell!**
%% Cell type:code id: tags:
``` python
printmd("**Don't forget to run this cell!**") # no output cell, make it visible
if set_num_wid.value == 0:
new_filters = list(filters)
else:
new_filters = []
# for each set of filters, copy them to new sets of filters modified by the trajectory filters
for filt in filters:
for i in range(set_num_wid.value):
# trajectory list selection
track_list_val = track_list_wid_list[i].value
if track_list_val == '':
track_list_val = None
else:
try:
track_list_val = [int(e) for e in track_list_val.split(',')]
except:
print("ERROR: a value in the list is not a number")
track_list_val = None
# ROI selection
track_xlim_list, track_ylim_list, track_zlim_ = retrieve_region_wid_values(track_drawer_wid_list[i],
track_xlim_wid_list[i],
track_ylim_wid_list[i],
track_zlim_wid_list[i])
# if several sets, get values of xlim, ylim, while keeping other filters constant
for j in range(len(track_xlim_list)):
ROI = {'xlim': track_xlim_list[j],
'ylim': track_ylim_list[j],
'zlim': track_zlim_,
'frame_lim': track_frame_subset_wid_list[i].value}
#name
if len(track_xlim_list) > 1: # if several subsets, modify name
name = track_name_wid_list[i].value + '_{}'.format(j)
else:
name = track_name_wid_list[i].value
# add new filters to existing filters
new_filt = dict(filt) # make copy of old filters
new_filt['track_list'] = track_list_val
new_filt['track_ROI'] = ROI
if new_filt['name'] == '':
new_filt['name'] = name # name = setname
else:
if name != '':
new_filt['name'] += '_' + name # name = subsetname_setname
# store in a new list of filters
new_filters.append(new_filt)
printmd('You set {} subsets. Edit their names and order to be plotted if needed.'.format(len(new_filters)))
filt_names_wid_list = []
order_wid_list = []
for i,filt in enumerate(new_filters):
print(filt)
name_wid = widgets.Text(value=filt['name'], placeholder='optional', description='Subset name:',
style={'description_width': 'initial'})
filt_names_wid_list.append(name_wid)
# using numbering starting at 1 for users
order_wid = widgets.BoundedIntText(value=i+1,min=1,max=len(new_filters)+1,description='order',style={'description_width': 'initial'})
order_wid_list.append(order_wid)
display(HBox([name_wid,order_wid]))
```
%%%% Output: display_data
**Don't forget to run this cell!**
%%%% Output: display_data
You set 1 subsets. Edit their names and order to be plotted if needed.
%%%% Output: stream
{'xlim': (36.61438636861541, 472.0845405438229), 'ylim': (38.13919994626437, 473.7006114895953), 'zlim': (21.689340569848213, 473.7984788052534), 'min_traj_len': 0, 'max_traj_len': 25, 'frame_subset': (0, 5), 'track_list': None, 'track_ROI': None, 'name': ''}
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
printmd("**Don't forget to run this cell!**") # no output cell, make it visible
order_list = [] # list for subsets indices
for i in range(len(new_filters)):
new_filters[i]['name'] = filt_names_wid_list[i].value
order_list.append(order_wid_list[i].value - 1) # using numbering starting at 1 for users
if any(x not in order_list for x in range(len(new_filters))): # check if all indices have been set
print("Warning: the ordering is wrong. Reverting to default order.")
order_list = [x for x in range(len(new_filters))]
order_list_ = [new_filters[i]['name'] for i in order_list] # order_list of names
filters_dict = {'subset': separate_widget.value,
'filters_list': new_filters,
'subset_order': order_list_,}
```
%%%% Output: display_data
**Don't forget to run this cell!**
%% Cell type:markdown id: tags:
# Trajectory analysis module
%% Cell type:code id: tags:
``` python
# prepare default values for widgets
if data['dim'] == 2:
color_code_list = ['t', 'group', 'random', 'none'] + list(custom_var.keys())
# if several subset plotted together, color code default: ROI
if len(filters_dict['filters_list']) and filters_dict['subset'] == 'together':
color_code_default = 'group'
else:
color_code_default = 'random'
elif data['dim'] == 3:
color_code_list = ['z', 't', 'group', 'random', 'none'] + list(custom_var.keys())
# if several subset plotted together, color code default: ROI
if len(filters_dict['filters_list']) and filters_dict['subset'] == 'together':
color_code_default = 'group'
else:
color_code_default = 'z'
### Section 1
printmd('### Plotting options')
printmd("**1. Trajectory plotting**")
## TAB 1
# widgets
traj_module_wid = widgets.ToggleButton(value=True, description='Run module')
show_axis_wid = widgets.Checkbox(value=False, description='show axes')
bkg_wid = widgets.Checkbox(value=False, description='hide background image')
show_tail_wid = widgets.Checkbox(value=True, description='show trajectory tail')
marker_size_wid = widgets.FloatSlider(value=1., min=0, max=20, steps=0.1,
description='Relative size of dots and lines:',
style={'description_width': 'initial'})
hide_lab_wid = widgets.Checkbox(value=True, description='hide track label')
lab_size_wid = widgets.IntSlider(value=6, min=0, max=100, description='Track label size (pt):',
style={'description_width': 'initial'})
color_code_wid = widgets.Dropdown(options=color_code_list, value=color_code_default, description='color code',
style={'description_width': 'initial'})
colormap_wid = widgets.Dropdown(options=['plasma', 'viridis', 'cividis', 'jet'], value='plasma', description='colormap',
style={'description_width': 'initial'})
lab_1 = Label('Plot trajectories frame by frame')
# layout
left_box_1 = VBox([show_axis_wid,bkg_wid, show_tail_wid, hide_lab_wid])
right_box_1 = VBox([lab_size_wid, marker_size_wid, color_code_wid, colormap_wid])
tab_1_ = HBox([left_box_1, right_box_1])
tab_1 = VBox([lab_1, traj_module_wid, tab_1_])
## TAB 2
# widgets
xrange = np.abs(df['x_scaled'].max() - df['x_scaled'].min())
yrange = np.abs(df['y_scaled'].max() - df['y_scaled'].min())
xlim = [df['x_scaled'].min() - xrange, df['x_scaled'].max() + xrange] # define custom xlim with wider boundaries
ylim = [df['y_scaled'].min() - yrange, df['y_scaled'].max() + yrange] # define custom ylim with wider boundaries
all_traj_module_wid = widgets.ToggleButton(value=True, description='Run module')
hide_lab_wid_2 = widgets.Checkbox(value=True, description='hide track label')
center_wid = widgets.Checkbox(value=True, description='center origin')
equal_axis_wid = widgets.Checkbox(value=False, description='equal scale on x/y axes')
setlim_wid = widgets.Checkbox(value=False, description='set custom axis limits')
lab_size_wid_2 = widgets.IntSlider(value=6, min=0, max=100, description='Track label size (pt):',
style={'description_width': 'initial'})
color_code_wid_2 = widgets.Dropdown(options=color_code_list, value=color_code_default, description='color code',
style={'description_width': 'initial'})
colormap_wid2 = widgets.Dropdown(options=['plasma', 'viridis', 'cividis', 'jet'], value='plasma',
description='colormap',
style={'description_width': 'initial'})
xlim_wid = widgets.FloatRangeSlider(value=xlim, min=xlim[0], max=xlim[1], step=1,
description='x range ({}):'.format(info['length_unit']),
style={'description_width': 'initial'})
ylim_wid = widgets.FloatRangeSlider(value=ylim, min=ylim[0], max=ylim[1], step=1,
description='y range ({}):'.format(info['length_unit']),
style={'description_width': 'initial'})
traj_alpha_wid = widgets.FloatSlider(value=1, min=0, max=1, steps=0.01, description='transparency',
style={'description_width': 'initial'})
lab_2 = Label('Plot total trajectories')
# layout
left_box_2 = VBox([hide_lab_wid_2, center_wid, equal_axis_wid, setlim_wid,traj_alpha_wid])
right_box_2 = VBox([lab_size_wid_2, color_code_wid_2, colormap_wid2, xlim_wid, ylim_wid])
tab_2_ = HBox([left_box_2, right_box_2])
tab_2 = VBox([lab_2, all_traj_module_wid, tab_2_])
# display Section 1
tab_titles = ['Plot frame by frame', 'Plot total trajectories']
tab = widgets.Tab()
tab.children = [tab_1, tab_2]
for i in range(len(tab_titles)):
tab.set_title(i, tab_titles[i])
display(tab)
### Section 2
printmd("**2. Parameter plotting**")
param_module_wid = widgets.ToggleButton(value=True, description='Run module')
display(param_module_wid)
printmd("*Two kinds of parameters can be plotted: instantaneous parameters (measured at each time point), and parameters calculated over a whole track.*")
printmd("*You can plot histograms of single parameters or scatter plots of a couple of parameters (e.g. v vs y)*")
printmd(
"How many instantaneous parameters (histogram or couples) do you want to plot? (enter 0 if you don't want to plot parameters)")
param_hist_num_wid = widgets.BoundedIntText(value=1, min=0, max=20, description='Number of histograms:',
style={'description_width': 'initial'})
param_couple_num_wid = widgets.BoundedIntText(value=3, min=0, max=20, description='Number of couples:',
style={'description_width': 'initial'})
display(HBox([param_hist_num_wid, param_couple_num_wid]))
printmd(
"How many whole-trajectory parameters (histogram or couples) do you want to plot? (enter 0 if you don't want to plot parameters)")
tparam_hist_num_wid = widgets.BoundedIntText(value=1, min=0, max=20, description='Number of histograms:',
style={'description_width': 'initial'})
tparam_couple_num_wid = widgets.BoundedIntText(value=3, min=0, max=20, description='Number of couples:',
style={'description_width': 'initial'})
display(HBox([tparam_hist_num_wid, tparam_couple_num_wid]))
### Section 3
printmd("**3. Mean Squared Displacement (MSD) analysis**")
MSD_module_wid = widgets.ToggleButton(value=True, description='Run module')
display(MSD_module_wid)
printmd("You can either plot the MSD, or/and fit it with a random walk model")
MSD_mode_wid = widgets.Dropdown(options=['only plot MSD', 'plot MSD and fit'], value='plot MSD and fit',
description='Choose analysis: ',
style={'description_width': 'initial'})
display(MSD_mode_wid)
printmd("***")
printmd("*Plotting section*")
printmd(
"Plot MSD altogether or as single plots. For a large number of tracks, plotting single MSDs can be long... Consider not plotting them.")
all_MSD_plot_wid = widgets.ToggleButton(value=True, description='plot MSD altogether')
single_MSD_plot_wid = widgets.ToggleButton(value=False, description='single MSD plots')
logplot_wid_x = widgets.Checkbox(value=True, description='x axis')
logplot_wid_y = widgets.Checkbox(value=True, description='y axis')
alpha_lab = Label('For all MSD plots, set the transparency (0=transparent, 1=opaque)')
alpha_wid = widgets.FloatSlider(value=0.2, min=0, max=1, steps=0.01, description='transparency',
style={'description_width': 'initial'})
display(HBox([all_MSD_plot_wid, single_MSD_plot_wid]))
display(HBox([Label('log plot: '), logplot_wid_x, logplot_wid_y]))
display(HBox([alpha_lab, alpha_wid]))
printmd("***")
printmd("*Fitting section*")
printmd("The MSD can be fitted with three different random walk models")
MSD_wid = widgets.Dropdown(options=['random walk', 'biased random walk', 'persistent random walk'], value='random walk',
description='Choose model: ',
style={'description_width': 'initial'})
display(MSD_wid)
dim_wid = widgets.Dropdown(options=['2D', '3D'], value='2D', description='dimension: ',
style={'description_width': 'initial'})
fitrange_wid = widgets.IntSlider(value=5 * timescale, min=0, max=df['t'].max(), step=1,
description='Maximum lag time ({})'.format(info['time_unit']),
style={'description_width': 'initial'})
printmd("Perform MSD analysis in 2D (along the xy dimensions) or 3D")
display(dim_wid)
printmd(
"Fitting MSDs can be difficult (at long lag times the calculation is very noisy because of the poor statistics). It is often necessary to restrict the fit to short lag times. ")
display(fitrange_wid)
### Section 4
printmd("**4. Voronoi analysis**")
vor_module_wid = widgets.ToggleButton(value=True, description='Run module')
display(vor_module_wid)
# plotting parameters
vor_show_axis_wid = widgets.Checkbox(value=False, description='show axes')
vor_bkg_wid = widgets.Checkbox(value=False, description='hide background image')
vor_plot_wid = widgets.Checkbox(value=True, description='plot diagram')
vor_area_wid = widgets.Checkbox(value=True, description='show cell area')
vor_area_thr_wid = widgets.BoundedFloatText(value=3, min=0, max=100, step=0.1,
description='Max area threshold:',
style={'description_width': 'initial'})
vor_cmap_wid = widgets.Dropdown(options=['plasma', 'viridis', 'cividis', 'jet'], value='plasma', description='colormap',
style={'description_width': 'initial'})
vor_linewidth_wid = widgets.FloatSlider(value=1., min=0.01, max=20, steps=0.1,
description='Diagram line width:',
style={'description_width': 'initial'})
vor_vmin_val_wid = widgets.BoundedFloatText(value=0, min=1e-6, max=1e6, step=1e-6,
description='Minimal limit:',
style={'description_width': 'initial'})
vor_vmin_bool_wid = widgets.Checkbox(value=False, description='set custom limit')
vor_vmax_val_wid = widgets.BoundedFloatText(value=0, min=1e-6, max=1e6, step=1e-6,
description='Maximal limit:',
style={'description_width': 'initial'})
vor_vmax_bool_wid = widgets.Checkbox(value=False, description='set custom limit')
display(HBox([VBox([vor_show_axis_wid, vor_bkg_wid, vor_plot_wid]),VBox([vor_area_wid, vor_area_thr_wid, vor_cmap_wid])]),vor_linewidth_wid)
printmd('Optional: set custom plotting limits to area color code (in squared unit)')
display(VBox([HBox([vor_vmin_bool_wid,vor_vmin_val_wid]),HBox([vor_vmax_bool_wid,vor_vmax_val_wid])]))
```
%%%% Output: display_data
### Plotting options
%%%% Output: display_data
**1. Trajectory plotting**
%%%% Output: display_data
%%%% Output: display_data
**2. Parameter plotting**
%%%% Output: display_data
%%%% Output: display_data
*Two kinds of parameters can be plotted: instantaneous parameters (measured at each time point), and parameters calculated over a whole track.*
%%%% Output: display_data
*You can plot histograms of single parameters or scatter plots of a couple of parameters (e.g. v vs y)*
%%%% Output: display_data
How many instantaneous parameters (histogram or couples) do you want to plot? (enter 0 if you don't want to plot parameters)
%%%% Output: display_data
%%%% Output: display_data
How many whole-trajectory parameters (histogram or couples) do you want to plot? (enter 0 if you don't want to plot parameters)
%%%% Output: display_data
%%%% Output: display_data
**3. Mean Squared Displacement (MSD) analysis**
%%%% Output: display_data
%%%% Output: display_data
You can either plot the MSD, or/and fit it with a random walk model
%%%% Output: display_data
%%%% Output: display_data
***
%%%% Output: display_data
*Plotting section*
%%%% Output: display_data
Plot MSD altogether or as single plots. For a large number of tracks, plotting single MSDs can be long... Consider not plotting them.
%%%% Output: display_data
%%%% Output: display_data
%%%% Output: display_data
%%%% Output: display_data
***
%%%% Output: display_data
*Fitting section*
%%%% Output: display_data
The MSD can be fitted with three different random walk models
%%%% Output: display_data
%%%% Output: display_data
Perform MSD analysis in 2D (along the xy dimensions) or 3D
%%%% Output: display_data
%%%% Output: display_data
Fitting MSDs can be difficult (at long lag times the calculation is very noisy because of the poor statistics). It is often necessary to restrict the fit to short lag times.
%%%% Output: display_data
%%%% Output: display_data
**4. Voronoi analysis**
%%%% Output: display_data
%%%% Output: display_data
%%%% Output: display_data
%%%% Output: display_data
Optional: set custom plotting limits to area color code (in squared unit)
%%%% Output: display_data
%% Cell type:code id: tags:
``` python
printmd("**Don't forget to run this cell!**") # no output cell, make it visible
## Get additional information about parameters plotting
# get MSD parameters
if not MSD_module_wid.value:
MSD_fit = False
else:
if MSD_mode_wid.value == 'only plot MSD':
MSD_fit = None
else:
MSD_model_dict = {'random walk': 'pure_diff', 'biased random walk': 'biased_diff',
'persistent random walk': 'PRW'}
MSD_fit = MSD_model_dict[MSD_wid.value]
# prepare parameters lists
if param_module_wid.value:
dimensions = ['x', 'y'] if data['dim'] == 2 else ['x', 'y', 'z']
scaled_dimensions = [dim + '_scaled' for dim in dimensions]
vel = ['v' + dim for dim in dimensions]
acc = ['a' + dim for dim in dimensions]
params = ['track', 't'] + dimensions + scaled_dimensions + vel + acc + ['v', 'a'] + list(custom_var.keys())
params_track = ['track', 'track_length', 't'] + dimensions + scaled_dimensions + vel + acc + ['v', 'a'] + list(custom_var.keys())
# add MSD output to track parameters
if MSD_fit is not None and MSD_fit is not False:
MSD_param = 'P' if MSD_fit == 'PRW' else 'D'
params_track += [MSD_param]
# add voronoi output to instantaneous parameters
if vor_module_wid.value:
params += ['area']
params_track += ['area']
# default
default_param = 'v'
default_xparam = ['x', 'y', 't']
# histogram widgets
param_hist_wid_list = []
tparam_hist_wid_list = []
for i in range(param_hist_num_wid.value):
w = widgets.Dropdown(options=params, value=default_param, description='parameter',
style={'description_width': 'initial'})
param_hist_wid_list.append(w)
box_1 = VBox(param_hist_wid_list)
for i in range(tparam_hist_num_wid.value):
w = widgets.Dropdown(options=params_track, value=default_param, description='parameter',
style={'description_width': 'initial'})
tparam_hist_wid_list.append(w)
box_2 = VBox(tparam_hist_wid_list)