In [1]:
%load_ext autoreload
%autoreload 2
%reload_ext XTIPython
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
In [136]:
%imaris_screenshot
Out[136]:
In [3]:
%imaris_pull spots
Out[3]:
In [6]:
vSpot = spots.values()[0]
In [38]:
track_ids = BridgeLib.GetItemTrackIds(vSpot)
track_ids
Out[38]:
In [39]:
BridgeLib.GetItemIds(vSpot,track_ids[0])
Out[39]:
In [41]:
arr = BridgeLib.GetItemXYZT(vImaris,vSpot,physdim=True)
In [53]:
arr[BridgeLib.GetItemIds(vSpot,track_ids[-1])]
Out[53]:
In [37]:
track_ids = BridgeLib.GetItemTrackIds(vSpot)
arr = BridgeLib.GetItemXYZT(vImaris,vSpot,physdim=True)
xmi = np.min(arr['x'])
xma = np.max(arr['x'])
ymi = np.min(arr['y'])
yma = np.max(arr['y'])
fig, ax = plt.subplots(1, 1,figsize=(15,10))
for tid in track_ids:
idx = BridgeLib.GetItemIds(vSpot,tid)
#values = subset["Value"][idx]
#ti = subset["Time"][idx]
xyzt = arr[BridgeLib.GetItemIds(vSpot,tid)]
ax.plot(xyzt['x'],xyzt['y'],label='%d'%(tid))
ax.set_xlabel('X coordinates (um)')
ax.set_ylabel('Y coordinates (um)')
ax.set_xlim(xmi,xma)
ax.set_ylim(ymi,yma)
ax.legend()
plt.show()
In [50]:
#https://stackoverflow.com/questions/4694478/center-origin-in-matplotlib
import matplotlib as mpl
import matplotlib.patheffects
def center_spines(ax=None, centerx=0, centery=0):
"""Centers the axis spines at <centerx, centery> on the axis "ax", and
places arrows at the end of the axis spines."""
if ax is None:
ax = plt.gca()
# Set the axis's spines to be centered at the given point
# (Setting all 4 spines so that the tick marks go in both directions)
ax.spines['left'].set_position(('data', centerx))
ax.spines['bottom'].set_position(('data', centery))
ax.spines['right'].set_position(('data', centerx - 1))
ax.spines['top'].set_position(('data', centery - 1))
# Hide the line (but not ticks) for "extra" spines
for side in ['right', 'top']:
ax.spines[side].set_color('none')
# On both the x and y axes...
for axis, center in zip([ax.xaxis, ax.yaxis], [centerx, centery]):
# Turn on minor and major gridlines and ticks
axis.set_ticks_position('both')
axis.grid(True, 'major', ls='solid', lw=0.5, color='gray')
axis.grid(True, 'minor', ls='solid', lw=0.1, color='gray')
axis.set_minor_locator(mpl.ticker.AutoMinorLocator())
# Hide the ticklabels at <centerx, centery>
formatter = CenteredFormatter()
formatter.center = center
axis.set_major_formatter(formatter)
# Add offset ticklabels at <centerx, centery> using annotation
# (Should probably make these update when the plot is redrawn...)
xlabel, ylabel = map(formatter.format_data, [centerx, centery])
ax.annotate('(%s, %s)' % (xlabel, ylabel), (centerx, centery),
xytext=(-4, -4), textcoords='offset points',
ha='right', va='top')
class CenteredFormatter(mpl.ticker.ScalarFormatter):
"""Acts exactly like the default Scalar Formatter, but yields an empty
label for ticks at "center"."""
center = 0
def __call__(self, value, pos=None):
if value == self.center:
return ''
else:
return mpl.ticker.ScalarFormatter.__call__(self, value, pos)
In [102]:
track_ids = BridgeLib.GetItemTrackIds(vSpot)
arr = BridgeLib.GetItemXYZT(vImaris,vSpot,physdim=True)
fig, ax = plt.subplots(1, 1,figsize=(15,10))
for tid in track_ids:
idx = BridgeLib.GetItemIds(vSpot,tid)
#values = subset["Value"][idx]
#ti = subset["Time"][idx]
xyzt = arr[BridgeLib.GetItemIds(vSpot,tid)]
x = xyzt['x'] - xyzt['x'][0]
y = xyzt['y'] - xyzt['y'][0]
ax.plot(x,y)
center_spines()
plt.axis('equal')
plt.show()
In [56]:
vStatisticValues = vSpot.GetStatistics()
In [57]:
list_stats = list(set(vStatisticValues.mNames))
list_stats.sort()
print list_stats
In [131]:
statistic_name = "Track Straightness"
subset = BridgeLib.GetStatistics(vStatisticValues,statistic_name)
In [132]:
import matplotlib.colors as colors
import matplotlib.cm as cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
track_ids = BridgeLib.GetItemTrackIds(vSpot)
arr = BridgeLib.GetItemXYZT(vImaris,vSpot,physdim=True)
vmi = np.min(subset["Value"])
vma = np.max(subset["Value"])
fig, ax = plt.subplots(1, 1,figsize=(15,10))
cmap = plt.get_cmap('jet')
norm = colors.Normalize(vmin=vmi, vmax=vma)
parameterToColorBy = np.linspace(vmi, vma, 6, dtype=float)
scalarMap = cm.ScalarMappable(norm=norm, cmap=cmap)
scalarMap.set_array([])
for tid in track_ids:
idx = BridgeLib.GetItemIds(vSpot,tid)
xyzt = arr[idx]
if not tid in subset["Id"]:
# This shouldn't happen but still, if don't have a
# statistics to display, then move on to the next track
continue
value = subset["Value"][subset["Id"] == tid][0]
x = xyzt['x'] - xyzt['x'][0]
y = xyzt['y'] - xyzt['y'][0]
col = scalarMap.to_rgba(value)
line, = ax.plot(x,y,color=col)
center_spines()
plt.axis('equal')
divider = make_axes_locatable(ax)
ax_cb = divider.new_horizontal(size="5%", pad=0.05)
cb = mpl.colorbar.ColorbarBase(ax_cb,
cmap=cmap,
norm=norm,
ticks=parameterToColorBy,
orientation='vertical')
cb.set_label(statistic_name)
fig.add_axes(ax_cb)
plt.show()
Slightly more complicated, here we choose a spot statistic such as acceleration and color code each of the tracks accordingly.
TODO:* There are some statistical values that cannot be mapped back to a spot id. This is annoying but for now can be worked around using numpy.take() with a "wrap" mode. Of course the values are completely wrong, but at least look-up doesn't crash.
So using:
values = np.take(subset["Value"],idx,mode="wrap")
instead of:
values = subset["Value"][idx]
In [133]:
#https://stackoverflow.com/questions/36074455/python-matplotlib-with-a-line-color-gradient-and-colorbar
import matplotlib.collections as mcoll
def make_segments(x, y):
"""
Create list of line segments from x and y coordinates, in the correct format
for LineCollection: an array of the form numlines x (points per line) x 2 (x
and y) array
"""
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
return segments
def colorline(
x, y, z=None, cmap='copper', norm=plt.Normalize(0.0, 1.0),
linewidth=3, alpha=1.0):
"""
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
Plot a colored line with coordinates x and y
Optionally specify colors in the array z
Optionally specify a colormap, a norm function and a line width
"""
# Default colors equally spaced on [0,1]:
if z is None:
z = np.linspace(0.0, 1.0, len(x))
# Special case if a single number:
# to check for numerical input -- this is a hack
if not hasattr(z, "__iter__"):
z = np.array([z])
z = np.asarray(z)
segments = make_segments(x, y)
lc = mcoll.LineCollection(segments, array=z, cmap=cmap, norm=norm,
linewidth=linewidth, alpha=alpha)
ax = plt.gca()
ax.add_collection(lc)
return lc
In [129]:
statistic_name = "Speed"
subset = BridgeLib.GetStatistics(vStatisticValues,statistic_name)
In [130]:
import matplotlib.colors as colors
import matplotlib.cm as cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
track_ids = BridgeLib.GetItemTrackIds(vSpot)
arr = BridgeLib.GetItemXYZT(vImaris,vSpot,physdim=True)
vmi = np.min(subset["Value"])
vma = np.max(subset["Value"])
fig, ax = plt.subplots(1, 1,figsize=(15,10))
cmap = plt.get_cmap('jet')
norm = colors.Normalize(vmin=vmi, vmax=vma)
parameterToColorBy = np.linspace(vmi, vma, 6, dtype=float)
scalarMap = cm.ScalarMappable(norm=norm, cmap=cmap)
scalarMap.set_array([])
for tid in track_ids:
idx = BridgeLib.GetItemIds(vSpot,tid)
xyzt = arr[idx]
#TODO! This is wrong, but there are indexes for which a value is not defined.
#If that's the case, wrap around to at least get a value
#Speed and Acceleration, because no value for last 1 or 2 points?
#Solution is to check the subset first maybe...
#values = subset["Value"][idx]
values = np.take(subset["Value"],idx,mode="wrap")
x = xyzt['x'] - xyzt['x'][0]
y = xyzt['y'] - xyzt['y'][0]
#print x.shape, y.shape,values.shape
lc = colorline(x, y, values, cmap=cmap, norm=norm, linewidth=2)
center_spines()
plt.axis('equal')
divider = make_axes_locatable(ax)
ax_cb = divider.new_horizontal(size="5%", pad=0.05)
cb = mpl.colorbar.ColorbarBase(ax_cb,
cmap=cmap,
norm=norm,
ticks=parameterToColorBy,
orientation='vertical')
cb.set_label(statistic_name)
fig.add_axes(ax_cb)
plt.show()
In [ ]: