Skip to content

Commit 8aa0ae3

Browse files
fixing dragging in gui and linewidth=88
1 parent fea79e0 commit 8aa0ae3

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+1088
-1490
lines changed

.style.yapf

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
[style]
2-
based_on_style = pep8
3-
spaces_before_comment = 4
2+
based_on_style = google
43
split_before_named_assigns = false
5-
allow_split_before_dict_value = false
6-
column_limit = 88
4+
column_limit = 88

suite2p/__main__.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@ def add_args(parser: argparse.ArgumentParser):
1111
help="run single plane ops")
1212
parser.add_argument("--ops", default=[], type=str, help="options")
1313
parser.add_argument("--db", default=[], type=str, help="options")
14-
parser.add_argument("--version", action="store_true",
15-
help="print version number.")
14+
parser.add_argument("--version", action="store_true", help="print version number.")
1615
ops0 = default_ops()
1716
for k in ops0.keys():
1817
v = dict(default=ops0[k], help="{0} : {1}".format(k, ops0[k]))
@@ -49,8 +48,7 @@ def parse_args(parser: argparse.ArgumentParser):
4948
ops[k] = n.astype(type(default_key))
5049
print(set_param_msg.format(k, ops[k]))
5150
elif isinstance(default_key, bool):
52-
args_key = bool(
53-
int(args_key)) # bool("0") is true, must convert to int
51+
args_key = bool(int(args_key)) # bool("0") is true, must convert to int
5452
if default_key != args_key:
5553
ops[k] = args_key
5654
print(set_param_msg.format(k, ops[k]))

suite2p/classification/classifier.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,7 @@ def load(self, classfile, keys=None):
5454
self.loaded = True
5555
self.classfile = classfile
5656
self._fit()
57-
except (ValueError, KeyError, OSError, RuntimeError, TypeError,
58-
NameError):
57+
except (ValueError, KeyError, OSError, RuntimeError, TypeError, NameError):
5958
print("ERROR: incorrect classifier file")
6059
self.loaded = False
6160

@@ -77,9 +76,8 @@ def predict_proba(self, stat):
7776
needs self.keys keys
7877
7978
"""
80-
test_stats = np.array([
81-
stat[j][k] for j in range(len(stat)) for k in self.keys
82-
]).reshape(len(stat), -1)
79+
test_stats = np.array([stat[j][k] for j in range(len(stat)) for k in self.keys
80+
]).reshape(len(stat), -1)
8381
logp = self._get_logp(test_stats)
8482
y_pred = self.model.predict_proba(logp)[:, 1]
8583
return y_pred
@@ -109,8 +107,8 @@ def _get_logp(self, stats):
109107
x[x > self.grid[-1, n]] = self.grid[-1, n]
110108
x[np.isnan(x)] = self.grid[0, n]
111109
ibin = np.digitize(x, self.grid[:, n], right=True) - 1
112-
logp[:, n] = np.log(self.p[ibin, n] +
113-
1e-6) - np.log(1 - self.p[ibin, n] + 1e-6)
110+
logp[:, n] = np.log(self.p[ibin, n] + 1e-6) - np.log(1 - self.p[ibin, n] +
111+
1e-6)
114112
return logp
115113

116114
def _fit(self):

suite2p/classification/classify.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@
55

66
builtin_classfile = Path(__file__).joinpath(
77
"../../classifiers/classifier.npy").resolve()
8-
user_classfile = Path.home().joinpath(
9-
".suite2p/classifiers/classifier_user.npy")
8+
user_classfile = Path.home().joinpath(".suite2p/classifiers/classifier_user.npy")
109

1110

1211
def classify(

suite2p/default_ops.py

+141-104
Large diffs are not rendered by default.

suite2p/detection/anatomical.py

+10-15
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,7 @@ def patch_detect(patches, diam):
5050
cellprob = yi[-1]
5151
dP = yi[:2]
5252
niter = 1 / rsz * 200
53-
p = dynamics.follow_flows(-1 * dP * (cellprob > 0) / 5.,
54-
niter=niter)
53+
p = dynamics.follow_flows(-1 * dP * (cellprob > 0) / 5., niter=niter)
5554
maski = dynamics.get_masks(p, iscell=(cellprob > 0), flows=dP,
5655
threshold=1.0)
5756
maski = fill_holes_and_remove_small_masks(maski)
@@ -69,14 +68,13 @@ def refine_masks(stats, patches, seeds, diam, Lyc, Lxc):
6968
patch_masks = patch_detect(patches, diam)
7069
ly = patches[0].shape[0] // 2
7170
igood = np.zeros(nmasks, "bool")
72-
for i, (patch_mask, stat,
73-
(yi, xi)) in enumerate(zip(patch_masks, stats, seeds)):
71+
for i, (patch_mask, stat, (yi, xi)) in enumerate(zip(patch_masks, stats, seeds)):
7472
mask = np.zeros((Lyc, Lxc), np.float32)
7573
ypix0, xpix0 = stat["ypix"], stat["xpix"]
7674
mask[ypix0, xpix0] = stat["lam"]
7775
func_mask = utils.square_mask(mask, ly, yi, xi)
78-
ious = utils.mask_ious(patch_mask.astype(np.uint16),
79-
(func_mask > 0).astype(np.uint16))[0]
76+
ious = utils.mask_ious(patch_mask.astype(np.uint16), (func_mask
77+
> 0).astype(np.uint16))[0]
8078
if len(ious) > 0 and ious.max() > 0.45:
8179
mask_id = np.argmax(ious) + 1
8280
patch_mask = patch_mask[max(0, ly - yi):min(2 * ly, Lyc + ly - yi),
@@ -98,8 +96,8 @@ def refine_masks(stats, patches, seeds, diam, Lyc, Lxc):
9896
return stats
9997

10098

101-
def roi_detect(mproj, diameter=None, cellprob_threshold=0.0,
102-
flow_threshold=1.5, pretrained_model=None):
99+
def roi_detect(mproj, diameter=None, cellprob_threshold=0.0, flow_threshold=1.5,
100+
pretrained_model=None):
103101
if not os.path.exists(pretrained_model):
104102
model = CellposeModel(model_type=pretrained_model)
105103
else:
@@ -184,25 +182,22 @@ def select_rois(ops: Dict[str, Any], mov: np.ndarray, diameter=None):
184182

185183
t0 = time.time()
186184
if diameter is not None:
187-
if isinstance(diameter,
188-
(list, np.ndarray)) and len(ops["diameter"]) > 1:
185+
if isinstance(diameter, (list, np.ndarray)) and len(ops["diameter"]) > 1:
189186
rescale = diameter[1] / diameter[0]
190187
img = cv2.resize(img, (Lxc, int(Lyc * rescale)))
191188
else:
192189
rescale = 1.0
193190
diameter = [diameter, diameter]
194191
if diameter[1] > 0:
195-
print(
196-
"!NOTE! diameter set to %0.2f for cell detection with cellpose"
197-
% diameter[1])
192+
print("!NOTE! diameter set to %0.2f for cell detection with cellpose" %
193+
diameter[1])
198194
else:
199195
print(
200196
"!NOTE! diameter set to 0 or None, diameter will be estimated by cellpose"
201197
)
202198
else:
203199
print(
204-
"!NOTE! diameter set to 0 or None, diameter will be estimated by cellpose"
205-
)
200+
"!NOTE! diameter set to 0 or None, diameter will be estimated by cellpose")
206201

207202
if ops.get("spatial_hp_cp", 0):
208203
img = np.clip(normalize99(img), 0, 1)

suite2p/detection/chan2detect.py

+5-8
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,7 @@ def intensity_ratio(ops, stats):
5151
cell_pix = masks.create_cell_pix(stats, Ly=ops["Ly"], Lx=ops["Lx"])
5252
cell_masks0 = [
5353
masks.create_cell_mask(stat, Ly=ops["Ly"], Lx=ops["Lx"],
54-
allow_overlap=ops["allow_overlap"])
55-
for stat in stats
54+
allow_overlap=ops["allow_overlap"]) for stat in stats
5655
]
5756
neuropil_ipix = masks.create_neuropil_masks(
5857
ypixs=[stat["ypix"] for stat in stats],
@@ -66,8 +65,7 @@ def intensity_ratio(ops, stats):
6665
for cell_mask, cell_mask0, neuropil_mask, neuropil_mask0 in zip(
6766
cell_masks, cell_masks0, neuropil_masks, neuropil_ipix):
6867
cell_mask[cell_mask0[0]] = cell_mask0[1]
69-
neuropil_mask[neuropil_mask0.astype(
70-
np.int64)] = 1. / len(neuropil_mask0)
68+
neuropil_mask[neuropil_mask0.astype(np.int64)] = 1. / len(neuropil_mask0)
7169

7270
mimg2 = ops["meanImg_chan2"]
7371
inpix = cell_masks @ mimg2.flatten()
@@ -83,7 +81,7 @@ def cellpose_overlap(stats, mimg2):
8381
masks = anatomical.roi_detect(mimg2)[0]
8482
Ly, Lx = masks.shape
8583
redstats = np.zeros((len(stats), 2),
86-
np.float32) #changed the size of preallocated space
84+
np.float32) #changed the size of preallocated space
8785
for i in range(len(stats)):
8886
smask = np.zeros((Ly, Lx), np.uint16)
8987
ypix0, xpix0 = stats[i]["ypix"], stats[i]["xpix"]
@@ -92,7 +90,7 @@ def cellpose_overlap(stats, mimg2):
9290
iou = ious.max()
9391
redstats[
9492
i,
95-
] = np.array([iou > 0.5, iou]) #this had the wrong dimension
93+
] = np.array([iou > 0.5, iou]) #this had the wrong dimension
9694
return redstats
9795

9896

@@ -104,8 +102,7 @@ def detect(ops, stats):
104102
# non-rigid regression with nblks x nblks pieces
105103
nblks = 3
106104
Ly, Lx = ops["Ly"], ops["Lx"]
107-
ops["meanImg_chan2_corrected"] = correct_bleedthrough(
108-
Ly, Lx, nblks, mimg, mimg2)
105+
ops["meanImg_chan2_corrected"] = correct_bleedthrough(Ly, Lx, nblks, mimg, mimg2)
109106

110107
redstats = None
111108
if ops.get("anatomical_red", True):

suite2p/detection/denoise.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@
88
def pca_denoise(mov: np.ndarray, block_size: List, n_comps_frac: float):
99
t0 = time.time()
1010
nframes, Ly, Lx = mov.shape
11-
yblock, xblock, _, block_size, _ = make_blocks(Ly, Lx,
12-
block_size=block_size)
11+
yblock, xblock, _, block_size, _ = make_blocks(Ly, Lx, block_size=block_size)
1312

1413
mov_mean = mov.mean(axis=0)
1514
mov -= mov_mean

suite2p/detection/detect.py

+20-30
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,9 @@ def detect(ops, classfile=None):
1515

1616
t0 = time.time()
1717
bin_size = int(
18-
max(1, ops["nframes"] // ops["nbinned"],
19-
np.round(ops["tau"] * ops["fs"])))
18+
max(1, ops["nframes"] // ops["nbinned"], np.round(ops["tau"] * ops["fs"])))
2019
print("Binning movie in chunks of length %2.2d" % bin_size)
21-
with BinaryFile(filename=ops["reg_file"], Ly=ops["Ly"],
22-
Lx=ops["Lx"]) as f:
20+
with BinaryFile(filename=ops["reg_file"], Ly=ops["Ly"], Lx=ops["Lx"]) as f:
2321
mov = f.bin_movie(
2422
bin_size=bin_size,
2523
bad_frames=ops.get("badframes"),
@@ -37,8 +35,7 @@ def detect(ops, classfile=None):
3735
def bin_movie(f_reg, bin_size, yrange=None, xrange=None, badframes=None):
3836
""" bin registered movie """
3937
n_frames = f_reg.shape[0]
40-
good_frames = ~badframes if badframes is not None else np.ones(
41-
n_frames, dtype=bool)
38+
good_frames = ~badframes if badframes is not None else np.ones(n_frames, dtype=bool)
4239
batch_size = min(good_frames.sum(), 500)
4340
Lyc = yrange[1] - yrange[0]
4441
Lxc = xrange[1] - xrange[0]
@@ -68,8 +65,7 @@ def bin_movie(f_reg, bin_size, yrange=None, xrange=None, badframes=None):
6865
# only if current batch size exceeds or matches bin_size
6966
n_d = data.shape[0]
7067
data = data[:(n_d // bin_size) * bin_size]
71-
data = data.reshape(-1, bin_size, Lyc,
72-
Lxc).astype(np.float32).mean(axis=1)
68+
data = data.reshape(-1, bin_size, Lyc, Lxc).astype(np.float32).mean(axis=1)
7369
else:
7470
# Current batch size is below bin_size (could have many bad frames in this batch)
7571
# Downsample taking the mean of batch to get a single bin
@@ -86,8 +82,8 @@ def bin_movie(f_reg, bin_size, yrange=None, xrange=None, badframes=None):
8682
return mov
8783

8884

89-
def detection_wrapper(f_reg, mov=None, yrange=None, xrange=None,
90-
ops=default_ops(), classfile=None):
85+
def detection_wrapper(f_reg, mov=None, yrange=None, xrange=None, ops=default_ops(),
86+
classfile=None):
9187
"""
9288
Main detection function.
9389
@@ -129,8 +125,7 @@ def detection_wrapper(f_reg, mov=None, yrange=None, xrange=None,
129125

130126
if mov is None:
131127
bin_size = int(
132-
max(1, n_frames // ops["nbinned"],
133-
np.round(ops["tau"] * ops["fs"])))
128+
max(1, n_frames // ops["nbinned"], np.round(ops["tau"] * ops["fs"])))
134129
print("Binning movie in chunks of length %2.2d" % bin_size)
135130
mov = bin_movie(f_reg, bin_size, yrange=yrange, xrange=xrange,
136131
badframes=ops.get("badframes", None))
@@ -147,9 +142,8 @@ def detection_wrapper(f_reg, mov=None, yrange=None, xrange=None,
147142

148143
if ops.get("denoise", 1):
149144
mov = pca_denoise(
150-
mov,
151-
block_size=[ops["block_size"][0] // 2,
152-
ops["block_size"][1] // 2], n_comps_frac=0.5)
145+
mov, block_size=[ops["block_size"][0] // 2, ops["block_size"][1] // 2],
146+
n_comps_frac=0.5)
153147

154148
if ops.get("anatomical_only", 0):
155149
try:
@@ -158,20 +152,17 @@ def detection_wrapper(f_reg, mov=None, yrange=None, xrange=None,
158152
except Exception as e:
159153
print("Warning: cellpose did not import")
160154
print(e)
161-
print(
162-
"cannot use anatomical mode, but otherwise suite2p will run normally"
163-
)
155+
print("cannot use anatomical mode, but otherwise suite2p will run normally")
164156
CELLPOSE_INSTALLED = False
165157
if not CELLPOSE_INSTALLED:
166158
print(
167159
"~~~ tried to import cellpose to run anatomical but failed, install with: ~~~"
168160
)
169161
print("$ pip install cellpose")
170162
else:
171-
print(">>>> CELLPOSE finding masks in " + [
172-
"max_proj / mean_img", "mean_img", "enhanced_mean_img",
173-
"max_proj"
174-
][int(ops["anatomical_only"]) - 1])
163+
print(">>>> CELLPOSE finding masks in " +
164+
["max_proj / mean_img", "mean_img", "enhanced_mean_img", "max_proj"][
165+
int(ops["anatomical_only"]) - 1])
175166
stat = anatomical.select_rois(ops=ops, mov=mov,
176167
diameter=ops.get("diameter", None))
177168
else:
@@ -193,26 +184,25 @@ def detection_wrapper(f_reg, mov=None, yrange=None, xrange=None,
193184

194185
if ops["preclassify"] > 0:
195186
if classfile is None:
196-
print(
197-
f"NOTE: Applying user classifier at {str(user_classfile)}")
187+
print(f"NOTE: Applying user classifier at {str(user_classfile)}")
198188
classfile = user_classfile
199189

200190
stat = roi_stats(stat, Ly, Lx, aspect=ops.get("aspect", None),
201-
diameter=ops.get("diameter", None),
202-
do_crop=ops.get("soma_crop", 1))
191+
diameter=ops.get("diameter",
192+
None), do_crop=ops.get("soma_crop", 1))
203193
if len(stat) == 0:
204194
iscell = np.zeros((0, 2))
205195
else:
206196
iscell = classify(stat=stat, classfile=classfile)
207197
np.save(Path(ops["save_path"]).joinpath("iscell.npy"), iscell)
208198
ic = (iscell[:, 0] > ops["preclassify"]).flatten().astype("bool")
209199
stat = stat[ic]
210-
print("Preclassify threshold %0.2f, %d ROIs removed" %
211-
(ops["preclassify"], (~ic).sum()))
200+
print("Preclassify threshold %0.2f, %d ROIs removed" % (ops["preclassify"],
201+
(~ic).sum()))
212202

213203
stat = roi_stats(stat, Ly, Lx, aspect=ops.get("aspect", None),
214-
diameter=ops.get("diameter", None),
215-
max_overlap=ops["max_overlap"],
204+
diameter=ops.get("diameter",
205+
None), max_overlap=ops["max_overlap"],
216206
do_crop=ops.get("soma_crop", 1))
217207
print("After removing overlaps, %d ROIs remain" % (len(stat)))
218208

0 commit comments

Comments
 (0)