Commit 8d560731 authored by amichaut's avatar amichaut
Browse files

added option to save as tiff stacks

parent d45981d6
......@@ -52,12 +52,13 @@ def make_plot_config(data_dir=None, export_config=False):
plot_config = {'figsize': (5, 5),
'dpi': 300,
'color_list': color_list,
'format': '.png',
'despine': True,
'logx': False,
'logy': False,
'invert_yaxis': True,
'export_data_pts': True
'format': '.png', # plot image format
'despine': True, # use seaborn despine function
'logx': False, # use log for x axis
'logy': False, # use log for y axis
'invert_yaxis': True, # to flip plot towards bottom as convential image orientation (origin at the top)
'export_data_pts': True, # for numerical plots, export data points to csv
'save_as_stack': True, # for movies, save as a tiff file, if false save as a series of files in a folder
}
if export_config:
......@@ -91,7 +92,7 @@ def stack_max_proj(image_fn, z_dim, t_dim=None):
tifff.imsave(out_fn, new_im)
def plot_cmap(plot_dir, label, cmap, vmin, vmax, plot_config=None):
def plot_cmap(plot_dir, label, cmap, vmin, vmax, plot_config=None, suffix=''):
""" Plot colormap given by cmap with boundaries vmin and vmax."""
plot_config = make_plot_config() if plot_config is None else plot_config
......@@ -102,7 +103,7 @@ def plot_cmap(plot_dir, label, cmap, vmin, vmax, plot_config=None):
cb = mpl.colorbar.ColorbarBase(ax, cmap=plt.get_cmap(cmap), norm=norm, orientation='horizontal')
ax.tick_params(labelsize=16)
cb.set_label(label=label, size=24)
filename = osp.join(plot_dir, 'colormap.png')
filename = osp.join(plot_dir, 'colormap'+suffix+plot_config['format'])
fig.savefig(filename, dpi=plot_config['dpi'], bbox_inches='tight')
plt.close(fig)
......@@ -136,6 +137,7 @@ def plot_traj(df, frame, data_dir, groups=None, image={'image_fn': None, 't_dim'
angle = traj_parameters['angle']
lab_size = traj_parameters['lab_size']
invert_yaxis = plot_config['invert_yaxis']
save_as_stack = plot_config['save_as_stack']
# get image size
......@@ -267,9 +269,12 @@ def plot_traj(df, frame, data_dir, groups=None, image={'image_fn': None, 't_dim'
if show_axis:
fig.tight_layout()
filename = osp.join(plot_dir, '{:04d}{}'.format(int(frame), plot_config['format']))
fig.savefig(filename, dpi=plot_config['dpi'])
plt.close(fig)
if save_as_stack:
return fig
else:
filename = osp.join(plot_dir, '{:04d}{}'.format(int(frame), plot_config['format']))
fig.savefig(filename, dpi=plot_config['dpi'])
plt.close(fig)
def plot_scalar_field(data_dir, df, data, field, frame, image={'image_fn': None, 't_dim': None, 'z_dim': None},
......@@ -288,6 +293,7 @@ def plot_scalar_field(data_dir, df, data, field, frame, image={'image_fn': None,
# misc param
plot_config = make_plot_config() if plot_config is None else plot_config
save_as_stack = plot_config['save_as_stack']
no_bkg = map_param['no_bkg']
show_axis = map_param['show_axis']
cmap = map_param['cmap']
......@@ -339,11 +345,12 @@ def plot_scalar_field(data_dir, df, data, field, frame, image={'image_fn': None,
if invert_yaxis:
ax.axis([xmin, xmax, ymax, ymin])
if not dont_save:
if save_as_stack or dont_save:
return fig
else:
filename = osp.join(plot_dir, field + '_{:04d}.png'.format(int(frame)))
fig.savefig(filename, dpi=plot_config['dpi'])
return fig, ax
plt.close(fig)
def plot_vector_field(data_dir, df, data, field, frame, plot_on_field=None, dim=3,
......@@ -363,6 +370,7 @@ def plot_vector_field(data_dir, df, data, field, frame, plot_on_field=None, dim=
# misc param
plot_config = make_plot_config() if plot_config is None else plot_config
save_as_stack = plot_config['save_as_stack']
no_bkg = map_param['no_bkg']
show_axis = map_param['show_axis']
# cmap=map_param['cmap']
......@@ -386,9 +394,10 @@ def plot_vector_field(data_dir, df, data, field, frame, plot_on_field=None, dim=
map_param_['cmap'] = plot_on_field['cmap']
map_param_['vlim'] = plot_on_field['vlim']
dim = 2 # to ensure that arrows are plotted in black and the z data is not use
fig, ax = plot_scalar_field(data_dir, df, data, plot_on_field['plot_on'], frame, image=image,
fig = plot_scalar_field(data_dir, df, data, plot_on_field['plot_on'], frame, image=image,
map_param=map_param_, plot_dir=plot_dir, plot_config=None,
dont_print_count=True, dont_save=True)
ax = fig.gca()
invert_yaxis = False # to ensure it's not inverted a second time
else:
no_plot_on_field = True
......@@ -425,9 +434,12 @@ def plot_vector_field(data_dir, df, data, field, frame, plot_on_field=None, dim=
ylim = ax.get_ylim()
ax.set_ylim(ylim[1], ylim[0])
filename = osp.join(plot_dir, 'vector_' + field + '_{:04d}.png'.format(int(frame)))
fig.savefig(filename, dpi=plot_config['dpi'])
plt.close(fig)
if save_as_stack:
return fig
else:
filename = osp.join(plot_dir, 'vector_' + field + '_{:04d}.png'.format(int(frame)))
fig.savefig(filename, dpi=plot_config['dpi'])
plt.close(fig)
def plot_Voronoi(data_dir, df, frame, data, show_local_area=True,
......@@ -459,6 +471,7 @@ def plot_Voronoi(data_dir, df, frame, data, show_local_area=True,
# misc param
plot_config = make_plot_config() if plot_config is None else plot_config
save_as_stack = plot_config['save_as_stack']
no_bkg = map_param['no_bkg']
show_axis = map_param['show_axis']
cmap = map_param['cmap']
......@@ -512,10 +525,13 @@ def plot_Voronoi(data_dir, df, frame, data, show_local_area=True,
if invert_yaxis:
ylim = ax.get_ylim()
ax.set_ylim(ylim[1], ylim[0])
filename = osp.join(plot_dir, 'voronoi_{:04d}.png'.format(int(frame)))
fig.savefig(filename, dpi=plot_config['dpi'])
plt.close(fig)
if save_as_stack:
return fig
else:
filename = osp.join(plot_dir, 'voronoi_{:04d}.png'.format(int(frame)))
fig.savefig(filename, dpi=plot_config['dpi'])
plt.close(fig)
def plot_hist_persistence_length(data_dir, track_groups, tracks, minimal_traj_length=40, normalize=True, dim=3,
......@@ -892,13 +908,25 @@ def plot_all_traj(data_dir, df, image={'image_fn': None, 't_dim': None, 'z_dim':
plot_dir=None,traj_parameters=None,plot_config=None):
"""Plot traj for all frames"""
if plot_dir is None:
plot_dir = osp.join(data_dir, 'traj')
else:
plot_dir = osp.join(plot_dir, 'traj')
# plotting directory
plot_config = make_plot_config() if plot_config is None else plot_config
save_as_stack = plot_config['save_as_stack']
if save_as_stack:
if plot_dir is None:
plot_dir = data_dir
config_dir = osp.join(plot_dir, 'config')
else: # save series of images in a separate directory
if plot_dir is None:
plot_dir = osp.join(data_dir, 'traj')
config_dir = osp.join(plot_dir, 'config')
else:
config_dir = osp.join(plot_dir, 'config') # keep config_dir outside of traj
plot_dir = osp.join(plot_dir, 'traj')
tpr.safe_mkdir(plot_dir)
#get info
info = tpr.get_info(data_dir)
# initialize config if None
......@@ -912,12 +940,9 @@ def plot_all_traj(data_dir, df, image={'image_fn': None, 't_dim': None, 'z_dim':
traj_parameters[k] = traj_config["traj_config_"][k]
# save config
config_dir = osp.join(plot_dir, 'config')
tpr.safe_mkdir(config_dir)
fn = osp.join(config_dir, 'traj_config_.csv')
tpr.write_dict(traj_parameters, fn)
plot_config = make_plot_config() if plot_config is None else plot_config
# color map
color_code = traj_parameters['color_code']
......@@ -934,7 +959,7 @@ def plot_all_traj(data_dir, df, image={'image_fn': None, 't_dim': None, 'z_dim':
param = "z_scaled" if color_code == 'z' else color_code
label = tpr.make_param_label(param, l_unit=info["length_unit"], t_unit=info["time_unit"])
plot_cmap(plot_dir, label, traj_parameters['cmap'], traj_parameters['cmap_lim'][0],
traj_parameters['cmap_lim'][1])
traj_parameters['cmap_lim'][1],suffix='_traj')
# make a colmuns of indices to be used for color_cylce
elif color_code == "group":
......@@ -958,12 +983,25 @@ def plot_all_traj(data_dir, df, image={'image_fn': None, 't_dim': None, 'z_dim':
num_cores = multiprocessing.cpu_count()
# Parallel(n_jobs=num_cores)(delayed(plot_cells)(df_list,groups_list,frame,data_dir,plot_traj,z_lim,hide_labels,no_bkg,lengthscale) for frame in df['frame'].unique())
else:
stack = [] # stack to store images
groups = df.groupby('frame')
for frame in df['frame'].unique():
frame = int(frame)
plot_traj(df, frame, data_dir, groups=groups, image=image, plot_dir=plot_dir,
fig = plot_traj(df, frame, data_dir, groups=groups, image=image, plot_dir=plot_dir,
traj_parameters=traj_parameters,
dim=dim, plot_config=plot_config)
# append to stack
if save_as_stack:
fig.canvas.draw()
fig_image = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
fig_image = fig_image.reshape(fig.canvas.get_width_height()[::-1] + (3,))
stack.append(fig_image)
plt.close(fig)
if save_as_stack:
stack = np.array(stack)
tifff.imsave(osp.join(plot_dir,'traj.tiff'), stack)
def plot_all_scalar_fields(data_dir, df, data, field, image={'image_fn': None, 't_dim': None, 'z_dim': None},
......@@ -971,14 +1009,16 @@ def plot_all_scalar_fields(data_dir, df, data, field, image={'image_fn': None, '
plot_dir=None, plot_config=None, dont_print_count=False):
"""Plot scalar fields as colormap for all frames."""
# plotting directory
plot_config = make_plot_config() if plot_config is None else plot_config
save_as_stack = plot_config['save_as_stack']
if plot_dir is None:
plot_dir = osp.join(data_dir, field)
tpr.safe_mkdir(plot_dir)
info = tpr.get_info(data_dir)
plot_config = make_plot_config() if plot_config is None else plot_config
# get vlim
map_param_ = dict(map_param)
vlim_default = tca.compute_vlim(df, data, field)
......@@ -991,13 +1031,26 @@ def plot_all_scalar_fields(data_dir, df, data, field, image={'image_fn': None, '
map_param_['vlim'][i] = vlim_default[i]
label = tpr.make_param_label(field, l_unit=info['length_unit'], t_unit=info['time_unit'])
plot_cmap(plot_dir, label, map_param_['cmap'], map_param_['vlim'][0], map_param_['vlim'][1])
plot_cmap(plot_dir, label, map_param_['cmap'], map_param_['vlim'][0], map_param_['vlim'][1],suffix='_'+field)
stack = [] # stack to store images
for frame in df['frame'].unique():
frame = int(frame)
fig, ax = plot_scalar_field(data_dir, df, data, field, frame, image=image,
fig = plot_scalar_field(data_dir, df, data, field, frame, image=image,
map_param=map_param_, plot_dir=plot_dir, plot_config=plot_config)
plt.close(fig)
# append to stack
if save_as_stack:
fig.canvas.draw()
fig_image = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
fig_image = fig_image.reshape(fig.canvas.get_width_height()[::-1] + (3,))
stack.append(fig_image)
plt.close(fig)
if save_as_stack:
stack = np.array(stack)
tifff.imsave(osp.join(plot_dir, field +'.tiff'), stack)
def plot_all_vector_fields(data_dir, df, data, field, plot_on_field=None, dim=3,
......@@ -1007,14 +1060,16 @@ def plot_all_vector_fields(data_dir, df, data, field, plot_on_field=None, dim=3,
plot_dir=None, plot_config=None, dont_print_count=False):
"""Plot vector fields for all frames."""
# plotting directory
plot_config = make_plot_config() if plot_config is None else plot_config
save_as_stack = plot_config['save_as_stack']
if plot_dir is None:
plot_dir = osp.join(data_dir, field)
tpr.safe_mkdir(plot_dir)
info = tpr.get_info(data_dir)
plot_config = make_plot_config() if plot_config is None else plot_config
# get vlim
if plot_on_field is not None:
vlim_default = tca.compute_vlim(df, data, plot_on_field['plot_on'])
......@@ -1026,13 +1081,25 @@ def plot_all_vector_fields(data_dir, df, data, field, plot_on_field=None, dim=3,
plot_on_field['vlim'][i] = vlim_default[i]
label = tpr.make_param_label(plot_on_field['plot_on'], l_unit=info['length_unit'], t_unit=info['time_unit'])
plot_cmap(plot_dir, label, plot_on_field['cmap'], plot_on_field['vlim'][0], plot_on_field['vlim'][1])
plot_cmap(plot_dir, label, plot_on_field['cmap'], plot_on_field['vlim'][0], plot_on_field['vlim'][1],suffix='_vector_'+plot_on_field['plot_on'])
stack = [] # stack to store images
for frame in df['frame'].unique():
frame = int(frame)
plot_vector_field(data_dir, df, data, field, frame, plot_on_field=plot_on_field, dim=dim, image=image,
fig = plot_vector_field(data_dir, df, data, field, frame, plot_on_field=plot_on_field, dim=dim, image=image,
map_param=map_param, plot_dir=plot_dir, plot_config=plot_config)
# append to stack
if save_as_stack:
fig.canvas.draw()
fig_image = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
fig_image = fig_image.reshape(fig.canvas.get_width_height()[::-1] + (3,))
stack.append(fig_image)
plt.close(fig)
if save_as_stack:
stack = np.array(stack)
tifff.imsave(osp.join(plot_dir,'vector_' + field +'.tiff'), stack)
def plot_all_Voronoi(data_dir, df, data, show_local_area=True, df_mean = None,
image={'image_fn': None, 't_dim': None, 'z_dim': None},
......@@ -1040,10 +1107,16 @@ def plot_all_Voronoi(data_dir, df, data, show_local_area=True, df_mean = None,
"""
Plot Voronoi for all frames and calculate voronoi cell area.
"""
# plotting directory
plot_config = make_plot_config() if plot_config is None else plot_config
save_as_stack = plot_config['save_as_stack']
if plot_dir is None:
plot_dir = osp.join(data_dir, 'voronoi')
tpr.safe_mkdir(plot_dir)
#get info
info = tpr.get_info(data_dir)
# initialize config if None
......@@ -1062,8 +1135,6 @@ def plot_all_Voronoi(data_dir, df, data, show_local_area=True, df_mean = None,
fn = osp.join(config_dir, 'voronoi_config.csv')
tpr.write_dict(map_param, fn)
plot_config = make_plot_config() if plot_config is None else plot_config
# get vlim
if show_local_area:
if 'area' in df.columns:
......@@ -1082,13 +1153,26 @@ def plot_all_Voronoi(data_dir, df, data, show_local_area=True, df_mean = None,
if show_local_area:
label = tpr.make_param_label('area', l_unit=info['length_unit'], t_unit=info['time_unit'])
plot_cmap(plot_dir, label, map_param['cmap'], map_param['vlim'][0], map_param['vlim'][1])
plot_cmap(plot_dir, label, map_param['cmap'], map_param['vlim'][0], map_param['vlim'][1],suffix='_area')
stack = [] # stack to store images
for frame in df['frame'].unique():
frame = int(frame)
plot_Voronoi(data_dir, df, frame, data, show_local_area=show_local_area, image=image, map_param=map_param,
fig = plot_Voronoi(data_dir, df, frame, data, show_local_area=show_local_area, image=image, map_param=map_param,
plot_dir=plot_dir, plot_config=plot_config, dont_print_count=dont_print_count)
# append to stack
if save_as_stack:
fig.canvas.draw()
fig_image = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
fig_image = fig_image.reshape(fig.canvas.get_width_height()[::-1] + (3,))
stack.append(fig_image)
plt.close(fig)
if save_as_stack:
stack = np.array(stack)
tifff.imsave(osp.join(plot_dir,'voronoi.tiff'), stack)
def plot_all_MSD(data_dir, df=None, df_out=None, fit_model="biased_diff", msd_all=None, refresh=False, hue=None,
hue_order=None, MSD_parameters=None, plot_config=None, plot_dir=None):
......
......@@ -1032,7 +1032,7 @@ def get_background(image=None, frame=None, df=None, no_bkg=False, image_size=Non
ymax = df['y'].max() + 0.05 * (df['y'].max() - df['y'].min())
figsize = ((xmax - xmin) / dpi, (ymax - ymin) / dpi)
fig = plt.figure(frameon=False, figsize=figsize)
fig = plt.figure(frameon=False, figsize=figsize, dpi=dpi)
ax = fig.add_axes([0, 0, 1, 1])
ax.set_aspect('equal')
......@@ -1054,7 +1054,7 @@ def get_background(image=None, frame=None, df=None, no_bkg=False, image_size=Non
im = img_as_ubyte(im) # 8bit conversion
n = im.shape[0]
m = im.shape[1]
fig = plt.figure(frameon=False, figsize=(m / dpi, n / dpi))
fig = plt.figure(frameon=False, figsize=(m / dpi, n / dpi), dpi=dpi)
ax = fig.add_axes([0, 0, 1, 1])
ax.imshow(im, aspect='equal', origin=orig, cmap='gray', vmin=0, vmax=255)
xmin, xmax, ymin, ymax = ax.axis()
......
......@@ -27,6 +27,8 @@ import os.path as osp
import sys
import argparse
import matplotlib as mpl
from track_analyzer import prepare as tpr
from track_analyzer import plotting as tpl
from track_analyzer import calculate as tca
......@@ -64,6 +66,8 @@ def map_analysis(data_dir, data=None, image=None, refresh=False, parallelize=Fal
for k in plot_config_default.keys():
if k not in plot_config.keys():
plot_config[k] = plot_config_default[k]
if plot_config['save_as_stack']:
mpl.use('TkAgg') # need to switch backend to use matplotlib tostring_rgb()
# Get map_config
map_config_default = tpr.make_map_config(data_dir=data_dir, export_config=False)
......@@ -189,16 +193,22 @@ def map_analysis(data_dir, data=None, image=None, refresh=False, parallelize=Fal
# plot data
scalar_fields_ = {**scalar_fields, **vector_mean} # merge scalar data in one single dict
for field in scalar_fields_.keys():
plot_dir = osp.join(sub_dir, field)
tpr.safe_mkdir(plot_dir)
if plot_config['save_as_stack']:
plot_dir = sub_dir
else: # save series of images in a separate directory
plot_dir = osp.join(sub_dir, field)
tpr.safe_mkdir(plot_dir)
map_param_ = dict(map_param)
map_param_['vlim'] = scalar_fields_[field]['vlim']
map_param_['cmap'] = scalar_fields_[field]['cmap']
tpl.plot_all_scalar_fields(data_dir, df, field_data, field, image=image, map_param=map_param_,
plot_dir=plot_dir, plot_config=plot_config, dont_print_count=False)
for field in vector_fields.keys():
plot_dir = osp.join(sub_dir, field)
tpr.safe_mkdir(plot_dir)
if plot_config['save_as_stack']:
plot_dir = sub_dir
else: # save series of images in a separate directory
plot_dir = osp.join(sub_dir, field)
tpr.safe_mkdir(plot_dir)
map_param_ = dict(map_param)
map_param_['vlim'] = vector_fields[field]['vlim']
tpl.plot_all_vector_fields(data_dir, df, field_data, field, image=image, plot_on_field=vector_fields[field],
......
......@@ -27,6 +27,8 @@ import os.path as osp
import sys
import argparse
import matplotlib as mpl
from track_analyzer import prepare as tpr
from track_analyzer import plotting as tpl
from track_analyzer import calculate as tca
......@@ -64,6 +66,8 @@ def traj_analysis(data_dir, data=None, image=None, refresh=False, parallelize=Fa
for k in plot_config_default.keys():
if k not in plot_config.keys():
plot_config[k] = plot_config_default[k]
if plot_config['save_as_stack']:
mpl.use('TkAgg') # need to switch backend to use matplotlib tostring_rgb()
# Get traj_config
traj_config_default = tpr.make_traj_config(data_dir=data_dir, export_config=False)
......@@ -175,8 +179,11 @@ def traj_analysis(data_dir, data=None, image=None, refresh=False, parallelize=Fa
df_prop.to_csv(mean_fn)
if voronoi_config['plot']:
plot_dir = osp.join(sub_dir, 'voronoi')
tpr.safe_mkdir(plot_dir)
if plot_config['save_as_stack']:
plot_dir = sub_dir
else: # save series of images in a separate directory
plot_dir = osp.join(sub_dir, 'voronoi')
tpr.safe_mkdir(plot_dir)
tpl.plot_all_Voronoi(data_dir, df, vor_data, show_local_area=voronoi_config['show_local_area'], image=image,
map_param=voronoi_config, plot_dir=plot_dir, plot_config=plot_config, dont_print_count=False)
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment