-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot.py
More file actions
2525 lines (2296 loc) · 87.6 KB
/
Copy pathplot.py
File metadata and controls
2525 lines (2296 loc) · 87.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as n
import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl
import matplotlib.colors as mcolors
from . import mathfuncs as math
from . import utils
from scipy import stats
colors = ["#90be6d", "#e98a15", "#b26c98", "#1b9aaa", "#3a405a"]
# when importing this, set the following rcParams:
# by default, save with dpi 200
# save without whitespace, bbox_in='tight' and pad_inched = 0.1
# save fonts as text, not images
# ALL fonts should be Arial.
# Axis ticks should be 8 pts
# axis labels should be 12 pts
# titles should be 12 pts
# legends should be 10 pts
mpl.rcParams["savefig.dpi"] = 200
mpl.rcParams["savefig.bbox"] = "tight"
mpl.rcParams["savefig.pad_inches"] = 0.1
mpl.rcParams["font.family"] = "sans-serif"
mpl.rcParams["font.sans-serif"] = ["Arial", "Liberation Sans", "DejaVu Sans"]
mpl.rcParams["font.size"] = 12
mpl.rcParams["axes.titlesize"] = 12
mpl.rcParams["axes.labelsize"] = 12
mpl.rcParams["xtick.labelsize"] = 10
mpl.rcParams["ytick.labelsize"] = 10
mpl.rcParams["legend.fontsize"] = 10
# save text as text, not images
# set default figsize to (4,3)
mpl.rcParams["figure.figsize"] = (4, 3)
# set default dpi to 150
mpl.rcParams["figure.dpi"] = 150
mpl.rcParams["svg.fonttype"] = "none"
# default filetype is svg
mpl.rcParams["savefig.format"] = "svg"
def multiple_timeseries(
yss,
ts=None,
colors=None,
labels=None,
alphas=None,
lws=None,
zscore=True,
dy=3.0,
auto_ylim=True,
ax=None,
tick_labels=True,
legend=False,
lw=1.0,
alpha=1.0,
color=None,
filt=None,
swap_yorder=False,
ylabel_rot=0,
dy_offset=0,
yposs=None,
idx_lims=None,
tlims=None,
):
if ax is None:
f, ax = plt.subplots()
n_lines = len(yss)
yticks = []
lines = []
if ts is None:
ts = n.arange(len(yss[0]))
elif len(n.shape(ts)) == 0:
ts = n.arange(len(yss[0])) * ts
ts = n.array(ts)
print(ts.shape)
print(tlims)
if tlims is not None:
idx0 = n.argmin(n.abs(ts - tlims[0]))
idx1 = n.argmin(n.abs(ts - tlims[1]))
idx_lims = (idx0, idx1)
# print(idx_lims)
if idx_lims is not None:
ts = ts[idx_lims[0] : idx_lims[1]]
for i in range(n_lines):
color = colors[i] if colors is not None else color
alpha = alphas[i] if alphas is not None else alpha
label = labels[i] if labels is not None else None
lw = lws[i] if lws is not None else lw
ys = yss[i]
if idx_lims is not None:
ys = ys[idx_lims[0] : idx_lims[1]]
if zscore:
ys = math.zscore(ys)
if filt is not None:
ys = math.filt(ys, filt)
if yposs is None:
ypos = dy * i + dy_offset
if swap_yorder:
ypos = dy * (n_lines - 1 - i)
else:
ypos = yposs[i]
lines += ax.plot(ts, ys + ypos, color=color, alpha=alpha, linewidth=lw, label=label)
yticks.append(ypos)
if labels is not None and legend:
ax.legend(lines[::-1], labels[::-1], frameon=True, facecolor="white")
ax.set_yticks(yticks)
if labels is not None and tick_labels:
ax.set_yticklabels(labels, rotation=ylabel_rot)
else:
ax.set_yticklabels([""] * len(yticks))
if auto_ylim:
ax.set_ylim(-dy, dy * (i + 1))
ax.set_xlim(ts.min(), ts.max())
return ax
# ...existing code...
def density_scatter(
x, y,
*,
cmap: str = "viridis",
ax=None,
s: float = 10,
cbar: bool = False,
density: str = 'hist',
density_bins: int = 64, # for 'hist'
gaussian_sigma: float | int = 0, # smoothing on histogram (pixels)
knn_k: int = 20, # for 'knn'
log_scale: bool = False, # use logarithmic color scale
# colorbar inside-axis options
cbar_loc: str = 'lower right',
cbar_size: str = '3%',
cbar_height: str = '20%',
cbar_borderpad: float = 0.2,
cbar_orientation: str = 'vertical',
# identity line options
identity_line: bool = False,
max_pts = 5000, # max points to plot, randomly subsampled if more
# statistics / legend options
show_stats: bool = False,
stats_loc: str = 'best',
stats_fmt: str = 'slope={slope:.3g}, r={r:.3g}, p={p:.1e}',
stats_frameon: bool = False,
**scatter_kwargs
):
"""Scatter plot colored by local point density.
Parameters
----------
x, y : array-like
1D arrays of the same length.
density : {'gaussian','hist','knn','uniform'}
- 'gaussian': scipy.stats.gaussian_kde (slow for large n)
- 'hist': 2D histogram (+ optional Gaussian blur) then per-point lookup
- 'knn': k-NN density via cKDTree using 1/(pi r_k^2)
- 'uniform': constant color (fallback)
density_bins : int
Number of bins per axis for 'hist'.
gaussian_sigma : float
Gaussian blur sigma (in bins) for 'hist'. 0 disables smoothing.
knn_k : int
k for k-NN density.
log_scale : bool
If True, use a logarithmic color scale (matplotlib.colors.LogNorm).
identity_line : bool
If True, draw a gray dashed identity line (y = x) behind the scatter without
changing axis limits.
show_stats : bool
If True, compute linear regression (scipy.stats.linregress) and add a legend entry
containing slope, Pearson r, and p-value using stats_fmt.
stats_loc : str
Matplotlib legend location for the stats string (if show_stats=True).
stats_fmt : str
Format string with placeholders {slope}, {r}, {p}, {intercept}.
stats_frameon : bool
Whether the legend frame is shown when displaying stats.
"""
# Convert and clean inputs
x = n.asarray(x).ravel()
y = n.asarray(y).ravel()
if x.shape != y.shape:
raise ValueError("x and y must have the same shape")
if x.size > max_pts:
idx = n.random.choice(x.size, size=max_pts, replace=False)
x = x[idx]
y = y[idx]
mask = n.isfinite(x) & n.isfinite(y)
x = x[mask]
y = y[mask]
if x.size == 0:
raise ValueError("No finite points to plot")
# Compute point density
xy = n.vstack([x, y])
z = None
if density == 'gaussian':
try:
kde = stats.gaussian_kde(xy)
z = kde(xy)
except Exception:
# Fallback to fast histogram method if KDE fails (e.g., singular covariance)
density = 'hist'
if density == 'hist':
# 2D histogram on a grid
H, xedges, yedges = n.histogram2d(x, y, bins=density_bins)
if gaussian_sigma and gaussian_sigma > 0:
from scipy.ndimage import gaussian_filter
H = gaussian_filter(H, gaussian_sigma, mode='constant')
# Map each point to its bin count (fast)
ix = n.clip(n.digitize(x, xedges) - 1, 0, H.shape[0] - 1)
iy = n.clip(n.digitize(y, yedges) - 1, 0, H.shape[1] - 1)
z = H[ix, iy] + 1e-12 # avoid zeros
elif density == 'knn':
# k-NN density estimate using area of circle to k-th neighbor
from scipy.spatial import cKDTree
tree = cKDTree(n.c_[x, y])
dists, _ = tree.query(n.c_[x, y], k=knn_k + 1) # include self
rk = dists[:, -1]
area = n.pi * n.maximum(rk, 1e-12) ** 2
z = 1.0 / area
elif density == 'uniform':
z = n.full_like(x, fill_value=1.0 / max(1, x.size), dtype=float)
if z is None:
raise ValueError("Unknown density method. Use 'gaussian', 'hist', 'knn', or 'uniform'.")
# Sort so densest points are plotted last
idx = n.argsort(z)
x_sorted = x[idx]
y_sorted = y[idx]
z_sorted = z[idx]
created_fig = False
if ax is None:
fig, ax = plt.subplots(figsize=(3, 3))
created_fig = True
else:
fig = None
# Apply logarithmic normalization if requested (unless user already provided a norm)
if log_scale and ('norm' not in scatter_kwargs):
# Ensure strictly positive vmin for LogNorm
zpos = z_sorted[z_sorted > 0]
if zpos.size == 0:
zpos = n.array([1.0])
vmin = scatter_kwargs.get('vmin', float(zpos.min()))
vmax = scatter_kwargs.get('vmax', float(z_sorted.max()))
scatter_kwargs['norm'] = mpl.colors.LogNorm(vmin=max(vmin, 1e-12), vmax=max(vmax, vmin * 1.000001))
sc = ax.scatter(x_sorted, y_sorted, c=z_sorted, s=s, cmap=cmap, **scatter_kwargs)
# Optional identity line (y=x) behind points; restore limits so it doesn't affect view
if identity_line:
xlim0 = ax.get_xlim()
ylim0 = ax.get_ylim()
lo = float(min(xlim0[0], ylim0[0]))
hi = float(max(xlim0[1], ylim0[1]))
try:
zbase = float(sc.get_zorder())
except Exception:
zbase = 1.0
ax.plot([lo, hi], [lo, hi], color='0.6', linestyle='--', linewidth=1.0, zorder=zbase - 1)
ax.set_xlim(xlim0)
ax.set_ylim(ylim0)
# Optional stats legend (after plotting so limits unaffected)
if show_stats and x.size > 1:
try:
lr = stats.linregress(x, y)
label = stats_fmt.format(slope=lr.slope, r=lr.rvalue, p=lr.pvalue, intercept=lr.intercept)
sc.set_label(label)
# Only draw legend if not already present (or user wants it explicitly)
existing_legend = ax.get_legend()
if existing_legend is None:
ax.legend(loc=stats_loc, frameon=stats_frameon)
except Exception:
# Silently ignore regression errors (e.g., constant input)
pass
if cbar:
# Create an inset colorbar inside the plotting axes using fixed bounds to avoid
# AnchoredLocator issues during save/render.
fig_for_cb = ax.figure if ax is not None else plt.gcf()
def _as_frac(v, default_frac):
# Convert values like '3%' -> 0.03, numbers <=1 kept as-is, >1 treated as percent.
if isinstance(v, str) and v.endswith('%'):
try:
return float(v[:-1]) / 100.0
except Exception:
return default_frac
try:
vf = float(v)
if vf <= 1.0:
return vf
# Treat e.g. 3 as 3%
return vf / 100.0
except Exception:
return default_frac
w_frac = _as_frac(cbar_size, 0.03)
h_frac = _as_frac(cbar_height, 0.4)
pad = float(cbar_borderpad) if cbar_borderpad is not None else 0.02
# If pad looks like inches (large), clamp to a small fraction
if pad > 0.5:
pad = 0.02
# Compute bounds in axes fraction coordinates based on location keyword
loc = (cbar_loc or 'upper right').lower()
if loc == 'upper right':
x0 = 1 - w_frac - pad
y0 = 1 - h_frac - pad
elif loc == 'upper left':
x0 = pad
y0 = 1 - h_frac - pad
elif loc == 'lower right':
x0 = 1 - w_frac - pad
y0 = pad
elif loc == 'lower left':
x0 = pad
y0 = pad
else:
# fallback: upper right
x0 = 1 - w_frac - pad
y0 = 1 - h_frac - pad
cbax = ax.inset_axes([x0, y0, w_frac, h_frac])
cbar_obj = mpl.colorbar.Colorbar(cbax, sc, orientation=cbar_orientation)
# Optional: keep the colorbar tidy inside the axis
for spine in cbax.spines.values():
spine.set_linewidth(0.5)
return fig, ax, sc
# ...existing code...
def plot_onsets(onset_times, offset_times, ax, alpha=0.5, color="grey"):
ylim = ax.get_ylim()
xlim = ax.get_xlim()
for i in range(len(onset_times)):
patch1 = ax.fill_between([onset_times[i], offset_times[i]], *ylim, color=color, alpha=alpha)
ax.set_ylim(ylim)
ax.set_xlim(xlim)
return patch1
def fill_cells_vol(coords, fill_vals, shape=None, empty=n.nan, filt=None, squeeze=True, proj=None):
"""
create a 3d volume (or a 2d projection of it) of all cells filled with specified values
Args:
coords (list): length n_cells, coords output from Suite3D
fill_vals (ndarray): one value per cell to fill
shape (tuple, optional): shape of the volume. if empty, try to estimate automatically. Defaults to None.
empty (float, optional): value to fill pixels that aren't in any cells. Defaults to n.nan.
filt (ndarray, optional): bool array of size n_cells to filter out unwanted cells. Defaults to None.
squeeze (bool, optional): honestly i'm not sure. Defaults to True.
proj (str, optional): whether to project result into a 2d array with a 'max', 'mean' or 'median' projection. Defaults to None.
Returns:
vols: 3d or 2d array, where each pixel belonging to a cell is filled with specified values
"""
expanded = False
if len(fill_vals.shape) == 1:
fill_vals = fill_vals[n.newaxis]
expanded = True
# print(fil#l_vals.shape)
n_dims = fill_vals.shape[0]
vols = []
# print(filt.shape)
for idx in range(n_dims):
if shape is None:
shape = n.array([n.max(n.concatenate([c[i] for c in coords]) + 1) for i in range(3)])
vol = n.zeros(shape) * empty
i = -1
for coord, fill_val in zip(coords, fill_vals[idx]):
i += 1
if filt is not None:
# print(i,filt[i])
if not filt[i]:
continue
# print(i, filt[i])
vol[coord[0], coord[1], coord[2]] = fill_val
vols.append(vol)
# print(n.nanmean(vol))
vols = n.array(vols)
if expanded and squeeze:
vols = vols[0]
if proj == "max":
vols = n.nanmax(vols, axis=0)
elif proj == "median":
vols = n.nanmedian(vols, axis=0)
elif proj == "mean":
vols = n.nanmean(vols, axis=0)
return vols
def fill_cells_plane(coords, fill_vals, shape=None, empty=n.nan, filt=None, squeeze=True):
"""
Create a 2D (y, x) plane by ignoring z and directly computing the mean projection over z.
This is a faster alternative to building a full 3D volume and then projecting with proj='mean'.
Args:
coords (list): length n_cells, Suite3D-like coords where each element is a tuple/list
of index arrays (z, y, x). Only y and x are used.
fill_vals (ndarray): one value per cell to fill. Shape (n_cells,) or (n_dims, n_cells).
shape (tuple, optional): If 3D, interpreted as (z, y, x) and we use (y, x).
If 2D, interpreted directly as (y, x). If None, inferred from coords.
empty (float, optional): value to fill pixels that aren't in any cells. Defaults to n.nan.
filt (ndarray, optional): bool array of size n_cells to filter out unwanted cells. Defaults to None.
squeeze (bool, optional): If fill_vals was 1D, return a 2D array when True. Defaults to True.
Returns:
planes: 2D array (y, x) or 3D array (n_dims, y, x) depending on fill_vals shape and squeeze.
"""
expanded = False
fill_vals = n.asarray(fill_vals)
if fill_vals.ndim == 1:
fill_vals = fill_vals[n.newaxis, :]
expanded = True
n_dims = fill_vals.shape[0]
# Determine (y, x) shape
if shape is None:
ny = int(n.max(n.concatenate([c[1] for c in coords])) + 1)
nx = int(n.max(n.concatenate([c[2] for c in coords])) + 1)
else:
if len(shape) == 3:
ny, nx = int(shape[1]), int(shape[2])
elif len(shape) == 2:
ny, nx = int(shape[0]), int(shape[1])
else:
# Best effort: expect last two entries are (y, x)
ny, nx = int(shape[-2]), int(shape[-1])
planes = []
for d in range(n_dims):
sum2d = n.zeros((ny, nx), dtype=n.float32)
cnt2d = n.zeros((ny, nx), dtype=n.int32)
for i, (coord, v) in enumerate(zip(coords, fill_vals[d])):
if filt is not None and not filt[i]:
continue
ys = coord[1]
xs = coord[2]
# Accumulate value per voxel projected onto (y, x)
n.add.at(sum2d, (ys, xs), v)
n.add.at(cnt2d, (ys, xs), 1)
# Compute mean while preserving 'empty' on pixels with zero count
plane = n.full((ny, nx), empty, dtype=n.float32)
mask = cnt2d > 0
plane[mask] = (sum2d[mask] / cnt2d[mask]).astype(n.float32)
planes.append(plane)
planes = n.array(planes)
if expanded and squeeze:
planes = planes[0]
return planes
# light wrapper around show_img that sets cmap='RdBu_r', symmetric_cmap=True, and has the additional optional parameter
def show_covmat(covmat, ax=None, fscale = 3, vscale=None, nan_diag=True, sort=None, **kwargs):
"""
Show a covariance/correlation matrix with RdBu_r colormap, symmetric scaling.
Args:
covmat: 2D numpy array
ax: matplotlib axis (optional)
vscale: float or None, if set, vmin/vmax = -vscale, vscale
**kwargs: extra arguments to show_img
Returns:w
fig, ax, axim
"""
if nan_diag:
covmat = covmat.copy()
covmat[n.diag_indices_from(covmat)] = n.nan
if sort is not None:
covmat = covmat.copy()
covmat = covmat[:,sort][sort]
cmap = "RdBu_r"
symmetric_cmap = True
if vscale is not None:
vminmax = (-vscale, vscale)
vminmax_percentile = None
else:
vminmax = None
return show_img(
covmat,
cmap=cmap,
symmetric_cmap=symmetric_cmap,
ax=ax,
figsize=(fscale,fscale),
vminmax=vminmax,
**kwargs,
)
def linear_cmap(
low_color="white",
high_color="darkred",
name="linear",
nan_color="lightgrey",
scale="linear",
vmin=None,
vmax=None,
clip=False,
):
"""
Create a 2-color colormap (low->high) with configurable NaN color and normalization.
Args:
low_color (str): Color for the low end of the colormap. Default "white".
high_color (str): Color for the high end of the colormap. Default "darkred".
name (str): Name of the colormap.
nan_color (str): Color for NaN values. Default "lightgrey".
scale (str): "linear" or "log". Controls the norm used.
vmin (float|None): Minimum value for normalization.
vmax (float|None): Maximum value for normalization.
clip (bool): Whether to clip values outside vmin/vmax.
Returns:
(cmap, norm): A matplotlib colormap and a matching Normalize/LogNorm instance.
"""
if scale not in ("linear", "log"):
raise ValueError("scale must be 'linear' or 'log'")
cmap = mpl.colors.LinearSegmentedColormap.from_list(name, [low_color, high_color])
# Set NaN color
try:
# Matplotlib >= 3.3
cmap = cmap.with_extremes(bad=nan_color)
except Exception:
cmap.set_bad(nan_color)
if scale == "log":
norm = mpl.colors.LogNorm(vmin=vmin, vmax=vmax, clip=clip)
else:
norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax, clip=clip)
return cmap, norm
def show_img(
im,
flip=1,
cmap="Greys_r",
colorbar=False,
other_args={},
figsize=(8, 6),
dpi=150,
alpha=None,
return_fig=True,
transpose=False,
bin=None,
ticks=False,
ax=None,
px_py=None,
exact_pixels=False,
vminmax_percentile=(0.5, 99.5),
vminmax=None,
facecolor="white",
xticks=None,
yticks=None,
flip_y = False,
return_cax=False,
cbar_fontsize=9,
norm=None,
cbar=False,
cbar_loc="left",
cbar_ori="vertical",
cbar_title="",
interpolation="nearest",
ax_off=False,
cax_kwargs={"frameon": False},
extent=None,
spines=False,
symmetric_cmap=False,
aspect=None,
cax_fontcolor="k",
cax_label_format="%.2f",
):
f = None
im = im.copy()
if type(bin) is tuple:
im = math.bin1d(math.bin1d(im, bin[0], axis=0), bin[1], axis=1)
elif bin is not None:
im = math.bin1d(math.bin1d(im, bin, axis=0), bin, axis=1)
# print("binned")
if transpose:
# print(im.shape)
im = n.moveaxis(im, (0, 1), (1, 0))
# print(im.shape)
if alpha is not None:
alpha = alpha.T
if exact_pixels:
ny, nx = im.shape
figsize = (nx / dpi, ny / dpi)
px_py = None
print(ny, nx, figsize, dpi)
new_args = {}
new_args.update(other_args)
if ax is None:
f, ax = plt.subplots(figsize=figsize, dpi=dpi)
if facecolor is not None:
ax.set_facecolor(facecolor)
ax.grid(False)
new_args["interpolation"] = interpolation
if vminmax_percentile is not None and vminmax is None:
new_args["vmin"] = n.nanpercentile(im, vminmax_percentile[0])
new_args["vmax"] = n.nanpercentile(im, vminmax_percentile[1])
if vminmax is not None:
new_args["vmin"] = vminmax[0]
new_args["vmax"] = vminmax[1]
if symmetric_cmap:
# print(new_args["vmin"])
# print(new_args["vmax"])
vmax_abs = max(n.abs(new_args["vmin"]), n.abs(new_args["vmax"]))
new_args["vmin"] = -vmax_abs
new_args["vmax"] = vmax_abs
# print(new_args["vmin"])
# print(new_args["vmax"])
if px_py is not None:
new_args["aspect"] = px_py[1] / px_py[0]
if aspect is not None:
new_args["aspect"] = aspect
if alpha is not None:
new_args["alpha"] = alpha.copy()
if norm is not None:
new_args["norm"] = norm
new_args["vmin"] = None
new_args["vmax"] = None
if extent is not None:
new_args["extent"] = extent
# print(new_args)
axim = ax.imshow(flip * im, cmap=cmap, **new_args)
if colorbar:
plt.colorbar()
if not ticks:
ax.set_xticks([])
ax.set_yticks([])
if exact_pixels:
plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
# plt.tight_layout()
if norm:
new_args["vmin"] = norm.vmin
new_args["vmax"] = norm.vmax
if cbar:
if cbar_loc == "left":
cbar_loc = [0.025, 0.4, 0.02, 0.2]
cbar_ori = "vertical"
if cbar_loc == "lower left":
cbar_loc = [0.025, 0.025, 0.02, 0.2]
cbar_ori = "vertical"
elif cbar_loc == "right":
cbar_loc = [0.88, 0.4, 0.02, 0.2]
cbar_ori = "vertical"
elif cbar_loc == "top":
cbar_loc = [0.4, 0.95, 0.2, 0.02]
cbar_ori = "horizontal"
elif cbar_loc == "bottom":
cbar_loc = [0.4, 0.05, 0.2, 0.02]
cbar_ori = "horizontal"
cax = ax.inset_axes(cbar_loc, **cax_kwargs)
plt.colorbar(axim, cax=cax, orientation=cbar_ori)
if cbar_ori == "vertical":
cax.set_yticks(
[new_args["vmin"], new_args["vmax"]],
[
cax_label_format % new_args["vmin"],
cax_label_format % new_args["vmax"],
],
color=cax_fontcolor,
fontsize=cbar_fontsize,
)
cax.set_ylabel(cbar_title, color=cax_fontcolor, fontsize=cbar_fontsize, labelpad=-10)
if cbar_ori == "horizontal":
cax.set_xticks(
[new_args["vmin"], new_args["vmax"]],
[
cax_label_format % new_args["vmin"],
cax_label_format % new_args["vmax"],
],
color=cax_fontcolor,
fontsize=cbar_fontsize,
)
cax.set_xlabel(cbar_title, color=cax_fontcolor, fontsize=cbar_fontsize, labelpad=-10)
if xticks is not None:
ax.set_xticks(range(len(xticks)), xticks)
if yticks is not None:
ax.set_yticks(range(len(yticks)), yticks)
if ax_off:
ax.axis("off")
if not spines:
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
if flip_y:
ax.invert_yaxis()
if return_cax:
return f, ax, axim, cax
if return_fig:
return f, ax, axim
def plot_raster(
activity,
labels=None,
ax=None,
neuron_axis=0,
sort=True,
category_order=None,
bin=None,
cmap="Greys",
boundary_color="green",
boundary_lw=0.5,
boundary_alpha=0.7,
boundary_ls="-",
label_fontsize=8,
label_axis="y",
time_bin_label=False,
return_order=False,
**show_img_kwargs,
):
"""Plot a neurons x time raster, sorted and labelled by cell type, with the image
binned for fast rendering (delegates to `show_img`).
The point of going through `show_img` with `bin` is speed: a raster is usually far
longer in time than the screen is wide, so binning the time axis (e.g. bin=(1,10))
shrinks the array `imshow` has to draw ~10x with no visible loss. Crucially the
type-block boundary lines and the per-type tick positions are rescaled by the
*neuron* bin factor so they stay aligned with the (possibly binned) image.
Parameters
----------
activity : 2D array. `neuron_axis` says which axis indexes neurons (the other is time).
labels : per-neuron category label (length = n_neurons). Drives the sort, the block
boundary lines, and one tick per category placed at the block centre.
ax : existing axis (else a new figure is made by `show_img`).
sort : if True, sort neurons by category (stable). `category_order` overrides the
category order (default = first-appearance order in `labels`).
bin : int or (neuron_bin, time_bin), forwarded to `show_img`.
label_axis : 'y' (default, neurons on rows) or 'x' for the category ticks.
time_bin_label : relabel the time axis back to original frame units after binning.
return_order : also return the neuron sort order (handy to sort a matching covariance).
Extra **show_img_kwargs (vminmax_percentile, colorbar, figsize, ...) pass straight through.
Returns (f, ax, axim) — plus `order` if `return_order`.
"""
A = np.asarray(activity)
if neuron_axis == 1:
A = A.T # -> (neurons, time)
n_neurons = A.shape[0]
order = np.arange(n_neurons)
labS = None
if labels is not None:
labels = np.asarray(labels)
if sort:
if category_order is None:
cats = list(dict.fromkeys(labels))
else:
cats = [c for c in category_order if c in set(labels)]
pos = {c: i for i, c in enumerate(cats)}
order = np.argsort([pos[l] for l in labels], kind="stable")
A = A[order]
labS = labels[order]
# bin factors used to rescale boundary/tick positions after show_img bins the image
nb = bin[0] if isinstance(bin, tuple) else (bin if bin is not None else 1)
tb = bin[1] if isinstance(bin, tuple) else (bin if bin is not None else 1)
show_img_kwargs.setdefault("ticks", True) # keep axes alive; we set our own ticks
show_img_kwargs.setdefault("aspect", "auto") # fill the axes (rasters are very wide)
f, ax, axim = show_img(A, ax=ax, bin=bin, cmap=cmap, **show_img_kwargs)
if labS is not None:
bnds = np.where(labS[1:] != labS[:-1])[0] + 1
for b in bnds:
ax.axhline(b / nb - 0.5, color=boundary_color, lw=boundary_lw,
alpha=boundary_alpha, ls=boundary_ls)
cats_present = list(dict.fromkeys(labS))
centers = [float(n.where(labS == c)[0].mean()) / nb for c in cats_present]
if label_axis == "y":
ax.set_yticks(centers); ax.set_yticklabels(cats_present, fontsize=label_fontsize)
else:
ax.set_xticks(centers)
ax.set_xticklabels(cats_present, rotation=90, fontsize=label_fontsize)
if time_bin_label and tb and tb != 1: # x is in binned pixels -> show frames
ax.set_xticklabels([f"{int(x * tb)}" for x in ax.get_xticks()])
if return_order:
return f, ax, axim, order
return f, ax, axim
def turn_off_spines(ax):
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
def compute_alphas(values, min=0, max=1):
alphas = values.copy()
alphas[alphas < min] = min
alphas[alphas > max] = max
alphas -= min
alphas /= max - min
return alphas
def fit_powerlaw(explained_vars, range=(11, 500), normalize=True):
xs = n.arange(0, explained_vars.size) + 1
if normalize:
ys = explained_vars / explained_vars.sum()
else:
ys = explained_vars
alpha, ypred, intercept = get_powerlaw(ys, n.arange(*range).astype(int))
return xs, ys, ypred, alpha, intercept
def get_powerlaw(ss, trange):
# code from github for stringer 2019 paper
"""fit exponent to variance curve"""
logss = n.log(n.abs(ss))
y = logss[trange][:, n.newaxis]
trange += 1
nt = trange.size
x = n.concatenate((-n.log(trange)[:, n.newaxis], n.ones((nt, 1))), axis=1)
w = 1.0 / trange.astype(n.float32)[:, n.newaxis]
b = n.linalg.solve(x.T @ (x * w), (w * x).T @ y).flatten()
allrange = n.arange(0, ss.size).astype(int) + 1
x = n.concatenate((-n.log(allrange)[:, n.newaxis], n.ones((ss.size, 1))), axis=1)
ypred = n.exp((x * b).sum(axis=1))
alpha = b[0]
return alpha, ypred, b[1]
def plot_powlaw(sig_vars, ax=None, color=None, label="", plaw_range=(11, 500), fit_line=True, lw_curve=4, alpha_curve=0.8, lw_fit=4, alpha_fit=0.3, normalize=True, marker=None, figsize=(3, 3)):
if ax is None:
f, ax = plt.subplots(figsize=figsize)
if color is None:
color = "k"
if normalize:
to_plot = sig_vars / sig_vars.sum()
else:
to_plot = sig_vars
# print(len(sig_vars))
if len(sig_vars) < plaw_range[1]:
plaw_range = (plaw_range[0], len(sig_vars))
alpha = None
if fit_line:
xs, alpha, yp, alpha, b = fit_powerlaw(to_plot, plaw_range, normalize=normalize)
label = label
if fit_line:
label += " $\\alpha$ = %.2f" % alpha
ax.loglog(
n.arange(1, len(to_plot) + 1),
to_plot,
color=color,
alpha=alpha_curve,
linewidth=lw_curve,
label=label,
marker=marker,
)
if fit_line:
ax.loglog(xs, yp, color=color, alpha=alpha_fit, linewidth=lw_fit)
return ax, alpha
def hist2d(
xs,
ys,
nbins=51,
xlims=None,
ylims=None,
regression=True,
ax=None,
log=True,
cbar=True,
cmap="Blues",
density=False,
clims=(None, None),
plot_identity=False,
xbins=None,
ybins=None,
regression_line_params={},
fix_nans=True,
lim_percentile=None,
slope_in_label=False,
legend_loc="upper right",
):
if fix_nans:
nans = n.isnan(xs) | n.isnan(ys)
if nans.sum() > 0:
xs = xs[~nans]
ys = ys[~nans]
if ax is None:
f, ax = plt.subplots(figsize=(6, 6))
if xlims is None:
xlims = xs.min(), xs.max() * 1.01
if ylims is None:
ylims = ys.min(), ys.max() * 1.01
if xbins is None:
if lim_percentile:
xbins = n.linspace(
n.percentile(xs, lim_percentile),
n.percentile(xs, 100 - lim_percentile),
nbins,
)
else:
xbins = n.linspace(*xlims, nbins)
if ybins is None:
if lim_percentile:
ybins = n.linspace(
n.percentile(ys, lim_percentile),
n.percentile(ys, 100 - lim_percentile),
nbins,
)
else:
ybins = n.linspace(*ylims, nbins)
if log:
norm = mpl.colors.LogNorm(vmin=clims[0], vmax=clims[1])
else:
norm = mpl.colors.Normalize(vmin=clims[0], vmax=clims[1])
if clims is None:
clims = (None, None)
hist = ax.hist2d(xs, ys, bins=(xbins, ybins), cmap=cmap, norm=norm, density=density)
if cbar:
plt.colorbar(hist[-1], ax=ax)
if plot_identity:
ax.plot(xlims, xlims, color="k", alpha=0.2, lw=3, linestyle="--")
if regression:
slopex, interceptx, rx, px, __ = stats.linregress(xs, ys)
if slope_in_label:
label = label = "y=%.2fx + %.2f\nR (CoD) : %.2f" % (slopex, interceptx, rx)
else:
label = "R: %.2f" % rx
ax.plot(
xbins,
xbins * slopex + interceptx,
color="k",
label=label,
**regression_line_params,
)
ax.legend(loc=legend_loc)
# print(hist[-1].get_clim())
return ax
def plot_timeseries(timeseries, ax=None):
if ax is None:
f, ax = plt.subplots(figsize=(8, 6))
ax.plot(timeseries.ts, timeseries.data[0])
from pandas.api.types import is_integer_dtype
def pairplot(
df,
nbin=101,
fboxsize=3,
dpi=150,
symmetric=False,
log=True,
pctile=99.9,
ticks_only_on_edge=True,
labels_only_on_edge=True,
):
ncell, ncol = df.shape