Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove pylab imports #1302

Merged
merged 11 commits into from
Mar 31, 2024
54 changes: 27 additions & 27 deletions caiman/base/movies.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@
import ipywidgets as widgets
import logging
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os
import pathlib
import pims
import pylab as pl
import scipy
import skimage
import sklearn
Expand Down Expand Up @@ -893,8 +893,8 @@ def local_correlations(self,
order_mean=order_mean)
Cn = np.maximum(Cn, rho)
if do_plot:
pl.imshow(Cn, cmap='gray')
pl.pause(.1)
plt.imshow(Cn, cmap='gray')
plt.pause(.1)

logging.debug('number of chunks:' + str(n_chunks - 1) + ' frames: ' +
str([(n_chunks - 1) * frames_per_chunk, T]))
Expand All @@ -904,8 +904,8 @@ def local_correlations(self,
order_mean=order_mean)
Cn = np.maximum(Cn, rho)
if do_plot:
pl.imshow(Cn, cmap='gray')
pl.pause(.1)
plt.imshow(Cn, cmap='gray')
plt.pause(.1)

return Cn

Expand Down Expand Up @@ -1117,7 +1117,7 @@ def to_2D(self, order='F') -> np.ndarray:
T = self.shape[0]
return np.reshape(self, (T, -1), order=order)

def zproject(self, method: str = 'mean', cmap=pl.cm.gray, aspect='auto', **kwargs) -> np.ndarray:
def zproject(self, method: str = 'mean', cmap=matplotlib.cm.gray, aspect='auto', **kwargs) -> np.ndarray:
"""
Compute and plot projection across time:

Expand All @@ -1141,7 +1141,7 @@ def zproject(self, method: str = 'mean', cmap=pl.cm.gray, aspect='auto', **kwarg
zp = np.std(self, axis=0)
else:
raise Exception('Method not implemented')
pl.imshow(zp, cmap=cmap, aspect=aspect, **kwargs)
plt.imshow(zp, cmap=cmap, aspect=aspect, **kwargs)
return zp

def play(self,
Expand Down Expand Up @@ -1175,7 +1175,7 @@ def play(self,
interpolation:
interpolation method for 'opencv' and 'embed_opencv' backends

backend: 'pylab', 'notebook', 'opencv' or 'embed_opencv'; the latter 2 are much faster
backend: 'opencv', 'embed_opencv', 'pyplot', 'notebook': the first two are much faster

do_loop: Whether to loop the video

Expand Down Expand Up @@ -2363,7 +2363,7 @@ def play_movie(movie,
interpolation:
interpolation method for 'opencv' and 'embed_opencv' backends

backend: 'pylab', 'notebook', 'opencv' or 'embed_opencv'; the latter 2 are much faster
backend: 'opencv', 'embed_opencv', 'pyplot', or 'notebook': the first two are much faster

do_loop: Whether to loop the video

Expand Down Expand Up @@ -2399,8 +2399,8 @@ def play_movie(movie,
"""
# todo: todocument
it = True if (isinstance(movie, list) or isinstance(movie, tuple) or isinstance(movie, str)) else False
if backend == 'pylab':
logging.warning('*** Using pylab. This might be slow. If you can use the opencv backend it may be faster')
if backend == 'pyplot':
logging.warning('Using pyplot back end: not recommended. Using opencv will yield faster, higher-quality results.')

gain = float(gain) # convert to float in case we were passed an int
if q_max < 100:
Expand Down Expand Up @@ -2444,26 +2444,26 @@ def process_frame(iddxx, frame, bord_px, magnification, interpolation, minmov, m
thickness=1)
return frame

if backend == 'pylab':
pl.ion()
fig = pl.figure(1)
if backend == 'pyplot':
plt.ion()
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.set_title("Play Movie")
im = ax.imshow((offset + (load(movie, subindices=slice(0,2), var_name_hdf5=var_name_hdf5) if it else movie)[0] - minmov) * gain / (maxmov - minmov + offset),
cmap=pl.cm.gray,
cmap=plt.cm.gray,
vmin=0,
vmax=1,
interpolation='none') # Blank starting image
interpolation='none') # Blank starting image
fig.show()
im.axes.figure.canvas.draw()
pl.pause(1)
plt.pause(1)

elif backend == 'notebook':
# First set up the figure, the axis, and the plot element we want to animate
fig = pl.figure()
im = pl.imshow(next(load_iter(movie, subindices=slice(0,1), var_name_hdf5=var_name_hdf5))\
if it else movie[0], interpolation='None', cmap=pl.cm.gray)
pl.axis('off')
fig = plt.figure()
im = plt.imshow(next(load_iter(movie, subindices=slice(0,1), var_name_hdf5=var_name_hdf5))\
if it else movie[0], interpolation='None', cmap=matplotlib.cm.gray)
plt.axis('off')

if it:
m_iter = load_iter(movie, subindices, var_name_hdf5)
Expand Down Expand Up @@ -2508,7 +2508,7 @@ def view(button):
frame_sum = 0
display_handle.update(Image(data=cv2.imencode(
'.jpg', np.clip((frame * 255.), 0, 255).astype('u1'))[1].tobytes()))
pl.pause(1. / fr)
plt.pause(1. / fr)
if stopButton.value==True:
break
display(stopButton)
Expand Down Expand Up @@ -2556,17 +2556,17 @@ def view(button):
elif backend == 'embed_opencv' and not save_movie:
break

elif backend == 'pylab':
elif backend == 'pyplot':
if bord_px is not None and np.sum(bord_px) > 0:
frame = frame[bord_px:-bord_px, bord_px:-bord_px]
im.set_data((offset + frame) * gain / maxmov)
ax.set_title(str(iddxx))
pl.axis('off')
plt.axis('off')
fig.canvas.draw()
pl.pause(1. / fr * .5)
ev = pl.waitforbuttonpress(1. / fr * .5)
plt.pause(1. / fr * .5)
ev = plt.waitforbuttonpress(1. / fr * .5)
if ev is not None:
pl.close()
plt.close()
break

elif backend == 'notebook':
Expand Down
2 changes: 1 addition & 1 deletion caiman/base/timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
from dateutil.tz import tzlocal
import h5py
import logging
import matplotlib.pyplot as plt
import numpy as np
import os
import pylab as plt
from pynwb import NWBHDF5IO, NWBFile
from pynwb.ophys import TwoPhotonSeries, OpticalChannel
from pynwb.device import Device
Expand Down
13 changes: 7 additions & 6 deletions caiman/base/traces.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
import cv2
import logging
import numpy as np
import pylab as pl
pl.ion()
import matplotlib
import matplotlib.pyplot as plt
plt.ion()

import caiman.base.timeseries

Expand Down Expand Up @@ -80,7 +81,7 @@ def computeDFF(self, window_sec=5, minQuantile=20):
def resample(self, fx=1, fy=1, fz=1, interpolation=cv2.INTER_AREA):
raise Exception('Not Implemented. Look at movie resize')

def plot(self, stacked=True, subtract_minimum=False, cmap=pl.cm.jet, **kwargs):
def plot(self, stacked=True, subtract_minimum=False, cmap=matplotlib.cm.jet, **kwargs):
"""Plot the data

author: ben deverett
Expand All @@ -91,7 +92,7 @@ def plot(self, stacked=True, subtract_minimum=False, cmap=pl.cm.jet, **kwargs):
subtract_minimum : bool
subtract minimum from each individual trace
cmap : matplotlib.LinearSegmentedColormap
color map for display. Options are found in pl.colormaps(), and are accessed as pl.cm.my_favourite_map
color map for display. Options are found in matplotlib.colormaps(), and are accessed as matplotlib.cm.my_favourite_map
kwargs : dict
any arguments accepted by matplotlib.plot

Expand All @@ -104,7 +105,7 @@ def plot(self, stacked=True, subtract_minimum=False, cmap=pl.cm.jet, **kwargs):
if len(d.shape) > 1:
n = d.shape[1]

ax = pl.gca()
ax = plt.gca()

colors = cmap(np.linspace(0, 1, n))
ax.set_color_cycle(colors)
Expand All @@ -122,7 +123,7 @@ def plot(self, stacked=True, subtract_minimum=False, cmap=pl.cm.jet, **kwargs):
ax2.set_yticklabels([str(i) for i in range(n)], weight='bold')
[l.set_color(c) for l, c in zip(ax2.get_yticklabels(), colors)]

pl.gcf().canvas.draw()
plt.gcf().canvas.draw()
return ax

def extract_epochs(self, trigs=None, tb=1, ta=1):
Expand Down
19 changes: 10 additions & 9 deletions caiman/behavior/behavior.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
"""

import cv2
import matplotlib
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to keep alphabetical order this should go above numpy

import matplotlib.pyplot as plt
import numpy as np
import pylab as pl
import scipy
from scipy.sparse import coo_matrix
from scipy.io import loadmat
Expand Down Expand Up @@ -38,14 +39,14 @@ def select_roi(img: np.ndarray, n_rois: int = 1) -> list:

masks = []
for _ in range(n_rois):
fig = pl.figure()
pl.imshow(img, cmap=pl.cm.gray)
fig = plt.figure()
plt.imshow(img, cmap=matplotlib.cm.gray)
pts = fig.ginput(0, timeout=0)
mask = np.zeros(np.shape(img), dtype=np.int32)
pts = np.asarray(pts, dtype=np.int32)
cv2.fillConvexPoly(mask, pts, (1, 1, 1), lineType=cv2.LINE_AA)
masks.append(mask)
pl.close()
plt.close()

return masks

Expand Down Expand Up @@ -353,12 +354,12 @@ def extract_components(mov_tot,

def plot_components(sp_filt, t_trace) -> None:
# todo: todocument
pl.figure()
plt.figure()
count = 0
for comp, tr in zip(sp_filt, t_trace):
count += 1
pl.subplot(6, 2, count)
pl.imshow(comp)
plt.subplot(6, 2, count)
plt.imshow(comp)
count += 1
pl.subplot(6, 2, count)
pl.plot(tr)
plt.subplot(6, 2, count)
plt.plot(tr)
40 changes: 20 additions & 20 deletions caiman/motion_correction.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@
import gc
import itertools
import logging
import matplotlib.pyplot as plt
import numpy as np
from numpy.fft import ifftshift
import os
import sys
import pylab as pl
import tifffile
from typing import Optional
from skimage.transform import resize as resize_sk
Expand Down Expand Up @@ -362,8 +362,8 @@ def motion_correct_pwrigid(self, save_movie:bool=True, template:np.ndarray=None,
indices=self.indices)
if not self.is3D:
if show_template:
pl.imshow(new_template_els)
pl.pause(.5)
plt.imshow(new_template_els)
plt.pause(.5) #TODO: figure out if pausing half-second is necessary
if np.isnan(np.sum(new_template_els)):
raise Exception(
'Template contains NaNs, something went wrong. Reconsider the parameters')
Expand Down Expand Up @@ -877,10 +877,10 @@ def motion_correct_online(movie_iterable, add_to_movie, max_shift_w=25, max_shif
template = np.median(buffer_templates, 0)

if show_template:
pl.cla()
pl.imshow(template, cmap='gray', vmin=250,
plt.cla()
plt.imshow(template, cmap='gray', vmin=250,
vmax=350, interpolation='none')
pl.pause(.001)
plt.pause(.001)

logging.debug('Relative change in template:' + str(
np.sum(np.abs(template - template_old)) / np.sum(np.abs(template))))
Expand Down Expand Up @@ -2687,23 +2687,23 @@ def compute_metrics_motion_correction(fname, final_size_x, final_size_y, swap_di
cv2.putText(vid_frame, 'x_flow', (2 * dims[0] + 10, 20), fontFace=5, fontScale=0.8, color=(
0, 255, 0), thickness=1)
cv2.imshow('frame', vid_frame)
pl.pause(1 / fr_play)
cv2.waitKey(1 / fr_play) # to pause between frames
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
pl.subplot(1, 3, 1)
pl.cla()
pl.imshow(fr, vmin=m_min, vmax=m_max, cmap='gray')
pl.title('movie')
pl.subplot(1, 3, 3)
pl.cla()
pl.imshow(flow[:, :, 1], vmin=vmin, vmax=vmax)
pl.title('y_flow')
pl.subplot(1, 3, 2)
pl.cla()
pl.imshow(flow[:, :, 0], vmin=vmin, vmax=vmax)
pl.title('x_flow')
pl.pause(1 / fr_play)
plt.subplot(1, 3, 1)
plt.cla()
plt.imshow(fr, vmin=m_min, vmax=m_max, cmap='gray')
plt.title('movie')
plt.subplot(1, 3, 3)
plt.cla()
plt.imshow(flow[:, :, 1], vmin=vmin, vmax=vmax)
plt.title('y_flow')
plt.subplot(1, 3, 2)
plt.cla()
plt.imshow(flow[:, :, 0], vmin=vmin, vmax=vmax)
plt.title('x_flow')
plt.pause(1 / fr_play)

n = np.linalg.norm(flow)
flows.append(flow)
Expand Down
16 changes: 8 additions & 8 deletions caiman/source_extraction/cnmf/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import numpy as np
import os
import pathlib
import pylab as pl
import matplotlib.pyplot as plt
import scipy
from scipy.sparse import spdiags, issparse, csc_matrix, csr_matrix
import scipy.ndimage as ndi
Expand Down Expand Up @@ -749,7 +749,7 @@ def manually_refine_components(Y, xxx_todo_changeme, A, C, Cn, thr=0.9, display_

x, y = np.mgrid[0:d1:1, 0:d2:1]

pl.imshow(Cn, interpolation=None, cmap=cmap)
plt.imshow(Cn, interpolation=None, cmap=cmap)
cm = caiman.base.rois.com(A, d1, d2)

Bmat = np.zeros((np.minimum(nr, max_number), d1, d2))
Expand All @@ -763,13 +763,13 @@ def manually_refine_components(Y, xxx_todo_changeme, A, C, Cn, thr=0.9, display_

T = np.shape(Y)[-1]

pl.close()
fig = pl.figure()
ax = pl.gca()
plt.close()
fig = plt.figure()
ax = plt.gca()
ax.imshow(Cn, interpolation=None, cmap=cmap,
vmin=np.percentile(Cn[~np.isnan(Cn)], 1), vmax=np.percentile(Cn[~np.isnan(Cn)], 99))
for i in range(np.minimum(nr, max_number)):
pl.contour(y, x, Bmat[i], [thr])
plt.contour(y, x, Bmat[i], [thr])

if display_numbers:
for i in range(np.minimum(nr, max_number)):
Expand Down Expand Up @@ -812,8 +812,8 @@ def manually_refine_components(Y, xxx_todo_changeme, A, C, Cn, thr=0.9, display_
Bvec = np.zeros(d)
Bvec[indx] = cumEn
bmat = np.reshape(Bvec, np.shape(Cn), order='F')
pl.contour(y, x, bmat, [thr])
pl.pause(.01)
plt.contour(y, x, bmat, [thr])
plt.pause(.01)

elif pts == []:
break
Expand Down
Loading
Loading