forked from tritemio/FRETBursts
-
Notifications
You must be signed in to change notification settings - Fork 9
/
burst_plot.py
2640 lines (2323 loc) · 107 KB
/
burst_plot.py
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
# encoding: utf-8
#
# FRETBursts - A single-molecule FRET burst analysis toolkit.
#
# Copyright (C) 2013-2016 The Regents of the University of California,
# Antonino Ingargiola <tritemio@gmail.com>
#
"""
This module defines all the plotting functions for the
:class:`fretbursts.burstlib.Data` object.
The main plot function is `dplot()` that takes, as parameters, a `Data()`
object and a 1-ch-plot-function and creates a subplot for each channel.
The 1-ch plot functions are usually called through `dplot` but can also be
called directly to make a single channel plot.
The 1-ch plot functions names all start with the plot type (`timetrace`,
`ratetrace`, `hist` or `scatter`).
**Example 1** - Plot the timetrace for all ch::
dplot(d, timetrace, scroll=True)
**Example 2** - Plot a FRET histogramm for each ch with a fit overlay::
dplot(d, hist_fret, show_model=True)
For more examples refer to
`FRETBurst notebooks <http://nbviewer.ipython.org/github/tritemio/FRETBursts_notebooks/tree/master/notebooks/>`_.
"""
import warnings
from itertools import cycle
from collections.abc import Iterable
from functools import wraps
# Numeric imports
import numpy as np
from numpy import arange, r_
from scipy.stats import norm as norm
from scipy.stats import erlang, gaussian_kde
from scipy.interpolate import UnivariateSpline
# Graphics imports
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Ellipse
from matplotlib.collections import PatchCollection, PolyCollection
from matplotlib.offsetbox import AnchoredText
from matplotlib.gridspec import GridSpec
from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize
import seaborn as sns
# Local imports
from .ph_sel import Ph_sel
from . import burstlib as bl
from .phtools import phrates
from . import burstlib_ext as bext
from . import background as bg
from .utils.misc import HistData, _is_list_of_arrays, selection_mask
from .scroll_gui import ScrollingToolQT
from . import gui_selection as gs
##
# Globals
#
blue = '#0055d4'
green = '#2ca02c'
red = '#e74c3c' # '#E41A1C'
purple = '#9b59b6'
_ph_sel_color_dict = {Ph_sel('all'): blue, Ph_sel(Dex='Dem'): green,
Ph_sel(Dex='Aem'): red, Ph_sel(Aex='Aem'): purple,
Ph_sel(Aex='Dem'): 'c', }
_ph_sel_label_dict = {Ph_sel('all'): 'All-ph', Ph_sel(Dex='Dem'): 'DexDem',
Ph_sel(Dex='Aem'): 'DexAem', Ph_sel(Aex='Aem'): 'AexAem',
Ph_sel(Aex='Dem'): 'AexDem'}
# Global store for plot status
_plot_status = {}
# Global store for GUI handlers
gui_status = {'first_plot_in_figure': True}
##
# Utility functions
#
def _ax_intercept(func):
"""
Wrapper that grabs the ax keyword argument and if None or not specified,
it calls plt.gca() and adds/replaces ax argument
"""
@wraps(func)
def inner(*args, **kwargs):
if 'ax' not in kwargs or kwargs['ax'] is None:
kwargs['ax'] = plt.gca()
return func(*args, **kwargs)
return inner
def _normalize_kwargs(kwargs, kind='patch'):
"""Convert matplotlib keywords from short to long form."""
if kwargs is None:
return {}
if kind == 'line2d':
long_names = dict(c='color', ls='linestyle', lw='linewidth',
mec='markeredgecolor', mew='markeredgewidth',
mfc='markerfacecolor', ms='markersize',)
elif kind == 'scatter':
long_names = dict(ls='linestyle', lw='linewidth',
ec='edgecolor', color='c')
elif kind == 'patch':
long_names = dict(c='color', ls='linestyle', lw='linewidth',
ec='edgecolor', fc='facecolor',)
for short_name in long_names:
if short_name in kwargs:
kwargs[long_names[short_name]] = kwargs.pop(short_name)
return kwargs
def bsavefig(d, s):
"""Save current figure with name in `d`, appending the string `s`."""
plt.savefig(d.Name() + s)
##
# Multi-channel plot functions
#
@_ax_intercept
def mch_plot_bg(d, ax=None, **kwargs):
"""Plot background vs channel for DA, D and A photons."""
bg = d.bg_from(Ph_sel('all'))
bg_dd = d.bg_from(Ph_sel(Dex='Dem'))
bg_ad = d.bg_from(Ph_sel(Dex='Aem'))
ax.plot(r_[1:d.nch+1], [b.mean()*1e-3 for b in bg], lw=2, color=blue,
label=' T', **kwargs)
ax.plot(r_[1:d.nch+1], [b.mean()*1e-3 for b in bg_dd], color=green, lw=2,
label=' D', **kwargs)
ax.plot(r_[1:d.nch+1], [b.mean()*1e-3 for b in bg_ad], color=red, lw=2,
label=' A', **kwargs)
ax.set_xlabel("CH")
ax.set_ylabel("kcps")
ax.grid(True)
ax.legend(loc='best')
ax.set_title(d.name)
@_ax_intercept
def mch_plot_bg_ratio(d, ax=None):
"""Plot ratio of A over D background vs channel."""
bg_dd = d.bg_from(Ph_sel(Dex='Dem'))
bg_ad = d.bg_from(Ph_sel(Dex='Aem'))
ax.plot(r_[1:d.nch+1],
[ba.mean()/bd.mean() for bd, ba in zip(bg_dd, bg_ad)],
color=green, lw=2, label='A/D')
ax.set_xlabel("CH"); ax.set_ylabel("BG Ratio A/D"); ax.grid(True)
ax.set_title("BG Ratio A/D "+d.name)
@_ax_intercept
def mch_plot_bsize(d, ax=None):
"""Plot mean burst size vs channel."""
CH = np.arange(1, d.nch+1)
ax.plot(CH, [b.mean() for b in d.nt], color=blue, lw=2, label=' T')
ax.plot(CH, [b.mean() for b in d.nd], color=green, lw=2, label=' D')
ax.plot(CH, [b.mean() for b in d.na], color=red, lw=2, label=' A')
ax.set_xlabel("CH")
ax.set_ylabel("Mean burst size")
ax.grid(True)
ax.legend(loc='best')
ax.set_title(d.name)
##
# ALEX alternation period plots
#
def plot_alternation_hist(d, bins=None, ax=None, **kwargs):
"""Plot the ALEX alternation histogram for the variable `d`.
This function works both for us-ALEX and ns-ALEX data.
This function must be called on ALEX data **before** calling
:func:`fretbursts.loader.alex_apply_period`.
"""
assert d.alternated
if d.lifetime:
plot_alternation = plot_alternation_hist_nsalex
else:
plot_alternation = plot_alternation_hist_usalex
plot_alternation(d, bins=bins, ax=ax, **kwargs)
@_ax_intercept
def plot_alternation_hist_usalex(d, bins=None, ax=None, ich=0,
hist_style={}, span_style={}):
"""Plot the us-ALEX alternation histogram for the variable `d`.
This function must be called on us-ALEX data **before** calling
:func:`fretbursts.loader.alex_apply_period`.
"""
if bins is None:
bins = 100
D_ON, A_ON = d._D_ON_multich[ich], d._A_ON_multich[ich]
d_ch, a_ch = d._det_donor_accept_multich[ich]
offset = d.get('offset', 0)
ph_times_t, det_t = d.ph_times_t[ich][:], d.det_t[ich][:]
period = d.alex_period
d_em_t = selection_mask(det_t, d_ch)
hist_style_ = dict(bins=bins, histtype='step', lw=2, alpha=0.9, zorder=2)
hist_style_.update(hist_style)
span_style_ = dict(alpha=0.2, zorder=1)
span_style_.update(span_style)
D_label = 'Donor: %d-%d' % (D_ON[0], D_ON[1])
A_label = 'Accept: %d-%d' % (A_ON[0], A_ON[1])
ax.hist((ph_times_t[d_em_t] - offset) % period, color=green, label=D_label,
**hist_style_)
ax.hist((ph_times_t[~d_em_t] - offset) % period, color=red, label=A_label,
**hist_style_)
ax.set_xlabel('Timestamp MODULO Alternation period')
if D_ON[0] < D_ON[1]:
ax.axvspan(D_ON[0], D_ON[1], color=green, **span_style_)
else:
ax.axvspan(0, D_ON[1], color=green, **span_style_)
ax.axvspan(D_ON[0], period, color=green, **span_style_)
if A_ON[0] < A_ON[1]:
ax.axvspan(A_ON[0], A_ON[1], color=red, **span_style_)
else:
ax.axvspan(0, A_ON[1], color=red, **span_style_)
ax.axvspan(A_ON[0], period, color=red, **span_style_)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), frameon=False)
@_ax_intercept
def plot_alternation_hist_nsalex(d, bins=None, ax=None, ich=0,
hist_style={}, span_style={}):
"""Plot the ns-ALEX alternation histogram for the variable `d`.
This function must be called on ns-ALEX data **before** calling
:func:`fretbursts.loader.alex_apply_period`.
"""
if bins is None:
bins = np.arange(d.nanotimes_params[ich]['tcspc_num_bins'])
D_ON_multi, A_ON_multi = d._D_ON_multich[ich], d._A_ON_multich[ich]
D_ON = [(D_ON_multi[i], D_ON_multi[i+1]) for i in range(0, len(D_ON_multi), 2)]
A_ON = [(A_ON_multi[i], A_ON_multi[i+1]) for i in range(0, len(A_ON_multi), 2)]
d_ch, a_ch = d._det_donor_accept_multich[ich]
hist_style_ = dict(bins=bins, histtype='step', lw=1.3, alpha=0.9, zorder=2)
hist_style_.update(hist_style)
span_style_ = dict(alpha=0.2, zorder=1)
span_style_.update(span_style)
D_label = 'Donor: '
for d_on in D_ON:
D_label += '%d-%d' % (d_on[0], d_on[1])
A_label = 'Accept: '
for a_on in A_ON:
A_label += '%d-%d' % (a_on[0], a_on[1])
nanotimes_d = d.nanotimes_t[ich][selection_mask(d.det_t[ich], d_ch)]
nanotimes_a = d.nanotimes_t[ich][selection_mask(d.det_t[ich], a_ch)]
ax.hist(nanotimes_d, label=D_label, color=green, **hist_style_)
ax.hist(nanotimes_a, label=A_label, color=red, **hist_style_)
ax.set_xlabel('Nanotime bin')
ax.set_yscale('log')
for d_on in D_ON:
ax.axvspan(d_on[0], d_on[1], color=green, **span_style_)
for a_on in A_ON:
ax.axvspan(a_on[0], a_on[1], color=red, **span_style_)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), frameon=False)
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
## Multi-channel plots
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
##
# Timetrace plots
#
def _burst_info(d, ich, burst_index):
"""Generates burst information message for the burst in data.mburst[ich][burst_index]"""
burst = d.mburst[ich][burst_index]
params = dict(
b_index=burst_index,
start_ms=float(burst.start) * d.clk_p * 1e3,
width_ms=float(burst.width) * d.clk_p * 1e3,
nt=d.nt[ich][burst_index],
nd=d.nd[ich][burst_index],
na=d.na[ich][burst_index],
E=d.E[ich][burst_index])
msg = ("[{b_index}]: w={width_ms:4.2f} ms\n"
"size=(T{nt:3.0f}, D{nd:3.0f}, A{na:3.0f}")
if d.alternated:
msg += ", AA{naa:3.0f}"
params['naa'] = d.naa[ich][burst_index]
msg += ")\n E={E:4.2%}"
if d.alternated:
msg += " S={S:4.2%}"
params['S'] = d.S[ich][burst_index]
return msg.format(**params)
def _plot_bursts(d, i, tmin_clk, tmax_clk, ax, pmax=1e3, pmin=0, color="#999999",
ytext=20):
"""Highlights bursts in a timetrace plot."""
b = d.mburst[i]
if b.num_bursts == 0:
return
burst_mask = (tmin_clk < b.start) * (b.start < tmax_clk)
bs = b[burst_mask]
burst_indices = np.where(burst_mask)[0]
start = bs.start * d.clk_p
end = bs.stop * d.clk_p
R = []
width = end - start
#TODO: decide how to use axvspan or other better function
for b, bidx, s, w, sign, va in zip(bs, burst_indices, start, width,
cycle([-1, 1]),
cycle(['top', 'bottom'])):
r = Rectangle(xy=(s, pmin), height=pmax - pmin, width=w)
r.set_clip_box(ax.bbox)
r.set_zorder(0)
R.append(r)
ax.text(s, sign * ytext, _burst_info(d, i, bidx), fontsize=6, rotation=45,
horizontalalignment='center', va=va)
ax.add_artist(PatchCollection(R, lw=0, color=color))
def _plot_rate_th(d, i, F, ph_sel, ax, invert=False, scale=1,
plot_style_={}, rate_th_style={}):
"""Plots background_rate*F as a function of time.
`plot_style_` is the style of a timetrace/ratetrace plot used as starting
style. Linestyle and label are changed. Finally, `rate_th_style` is
applied and can override any style property.
If rate_th_style_['label'] is 'auto' the label is generated from
plot_style_['label'] and F.
"""
if F is None:
F = d.F if F in d else 6
rate_th_style_ = dict(plot_style_)
rate_th_style_.update(linestyle='--', label='auto')
rate_th_style_.update(_normalize_kwargs(rate_th_style, kind='line2d'))
if rate_th_style_['label'] == 'auto':
rate_th_style_['label'] = 'bg_rate*%d %s' % \
(F, plot_style_['label'])
x_rate = np.hstack(d.Ph_p[i]) * d.clk_p
y_rate = F * np.hstack([(rate, rate) for rate in d.bg_from(ph_sel)[i]])
y_rate *= scale
if invert:
y_rate *= -1
ax.plot(x_rate, y_rate, **rate_th_style_)
def _gui_timetrace_burst_sel(d, fig, ax):
"""Add GUI burst selector via mouse click to the current plot."""
global gui_status
if gui_status['first_plot_in_figure']:
gui_status['burst_sel'] = gs.MultiAxPointSelection(fig, ax, d)
else:
gui_status['burst_sel'].ax_list.append(ax)
def _gui_timetrace_scroll(fig):
"""Add GUI to scroll a timetrace wi a slider."""
global gui_status
if gui_status['first_plot_in_figure']:
gui_status['scroll_gui'] = ScrollingToolQT(fig)
@_ax_intercept
def timetrace_single(d, i=0, binwidth=1e-3, bins=None, tmin=0, tmax=200,
ph_sel=Ph_sel('all'), invert=False, bursts=False,
burst_picker=True, scroll=False, cache_bins=True,
plot_style=None, show_rate_th=True, F=None,
rate_th_style={}, set_ax_limits=True,
burst_color='#BBBBBB', ax=None):
"""Plot the timetrace (histogram) of timestamps for a photon selection.
See :func:`timetrace` to plot multiple photon selections (i.e.
Donor and Acceptor photons) in one step.
"""
if tmax is None or tmax < 0 or tmax > d.time_max:
tmax = d.time_max
def _get_cache():
return (timetrace_single.bins, timetrace_single.x,
timetrace_single.binwidth,
timetrace_single.tmin, timetrace_single.tmax)
def _set_cache(bins, x, binwidth, tmin, tmax):
cache = dict(bins=bins, x=x, binwidth=binwidth, tmin=tmin, tmax=tmax)
for name, value in cache.items():
setattr(timetrace_single, name, value)
def _del_cache():
names = ['bins', 'x', 'binwidth', 'tmin', 'tmax']
for name in names:
delattr(timetrace_single, name)
def _has_cache():
return hasattr(timetrace_single, 'bins')
def _has_cache_for(binwidth, tmin, tmax):
if _has_cache():
return (binwidth, tmin, tmax) == _get_cache()[2:]
return False
# If cache_bins is False delete any previously saved attribute
if not cache_bins and _has_cache:
_del_cache()
tmin_clk, tmax_clk = tmin / d.clk_p, tmax / d.clk_p
binwidth_clk = binwidth / d.clk_p
# If bins is not passed try to use the cached one
if bins is None:
if cache_bins and _has_cache_for(binwidth, tmin, tmax):
bins, x = timetrace_single.bins, timetrace_single.x
else:
bins = np.arange(tmin_clk, tmax_clk + 1, binwidth_clk)
x = bins[:-1] * d.clk_p + 0.5 * binwidth
if cache_bins:
_set_cache(bins, x, binwidth, tmin, tmax)
# Compute histogram
ph_times = d.get_ph_times(i, ph_sel=ph_sel)
timetrace, _ = np.histogram(ph_times, bins=bins)
if invert:
timetrace *= -1
# Plot bursts
if bursts:
_plot_bursts(d, i, tmin_clk, tmax_clk, ax, pmax=500, pmin=-500,
color=burst_color)
# Plot timetrace
plot_style_ = dict(linestyle='-', linewidth=1.2, marker=None)
if ph_sel in _ph_sel_color_dict:
plot_style_['color'] = _ph_sel_color_dict[ph_sel]
plot_style_['label'] = _ph_sel_label_dict[ph_sel]
else:
plot_style_['label'] = str(ph_sel)
plot_style_.update(_normalize_kwargs(plot_style, kind='line2d'))
ax.plot(x, timetrace, **plot_style_)
# Plot burst-search rate-threshold
if show_rate_th and 'bg' in d:
_plot_rate_th(d, i, F=F, ph_sel=ph_sel, ax=ax, invert=invert,
scale=binwidth, plot_style_=plot_style_,
rate_th_style=rate_th_style)
ax.set_xlabel('Time (s)')
ax.set_ylabel('# ph')
if burst_picker and 'mburst' in d:
_gui_timetrace_burst_sel(d, ax.figure, ax)
if scroll:
_gui_timetrace_scroll(ax.figure)
if set_ax_limits:
ax.set_xlim(tmin, tmin + 1)
if not invert:
ax.set_ylim(top=100)
else:
ax.set_ylim(bottom=-100)
_plot_status['timetrace_single'] = {'autoscale': False}
# do not concatenate, timetrace should always be shown per channel
@_ax_intercept
def timetrace(d, i=0, binwidth=1e-3, bins=None, tmin=0, tmax=200,
bursts=False, burst_picker=True, scroll=False,
show_rate_th=True, F=None, rate_th_style={'label': None},
show_aa=True, legend=False, set_ax_limits=True,
burst_color='#BBBBBB', plot_style=None,
#dd_plot_style={}, ad_plot_style={}, aa_plot_style={}
ax=None):
"""Plot the timetraces (histogram) of photon timestamps.
Arguments:
d (Data object): the measurement's data to plot.
i (int): the channel to plot. Default 0.
binwidth (float): the bin width (seconds) of the timetrace histogram.
bins (array or None): If not None, defines the bin edges for the
timetrace (overriding `binwidth`). If None, `binwidth` is use
to generate uniform bins.
tmin, tmax (float): min and max time (seconds) to include in the
timetrace. Note that a long time range and a small `binwidth`
can require a significant amount of memory.
bursts (bool): if True, plot the burst start-stop times.
burst_picker (bool): if True, enable the ability to click on bursts
to obtain burst info. This function requires the matplotlib's QT
backend.
scroll (bool): if True, activate a scrolling bar to quickly scroll
through the timetrace. This function requires the matplotlib's QT
backend.
show_rate_th (bool): if True, plot the burst search threshold rate.
F (bool): if `show_rate` is True, show a rate `F` times larger
than the background rate.
rate_th_style (dict): matplotlib style for the rate line.
show_aa (bool): if True, plot a timetrace for the AexAem photons.
If False (default), plot timetraces only for DexDem and DexAem
streams.
legend (bool): whether to show the legend or not.
set_ax_limits (bool): if True, set the xlim to zoom on a small portion
of timetrace. If False, do not set the xlim, display the full
timetrace.
burst_color (string): string containing the the HEX RGB color to use
to highlight the burst regions.
plot_style (dict): matplotlib's style for the timetrace lines.
ax (mpl.axes): axis where plot will be generated
"""
# Plot bursts
if bursts:
tmin_clk, tmax_clk = tmin / d.clk_p, tmax / d.clk_p
_plot_bursts(d, i, tmin_clk, tmax_clk, ax, pmax=500, pmin=-500,
color=burst_color)
# Plot multiple timetraces
ph_sel_list = [Ph_sel(Dex='Dem'), Ph_sel(Dex='Aem')]
invert_list = [False, True]
burst_picker_list = [burst_picker, False]
scroll_list = [scroll, False]
if d.alternated and show_aa:
ph_sel_list.append(Ph_sel(Aex='Aem'))
invert_list.append(True)
burst_picker_list.append(False)
scroll_list.append(False)
for ix, (ph_sel, invert) in enumerate(zip(ph_sel_list, invert_list)):
if not bl.mask_empty(d.get_ph_mask(i, ph_sel=ph_sel)):
timetrace_single(
d, i, binwidth=binwidth, bins=bins, tmin=tmin,
tmax=tmax, ph_sel=ph_sel, invert=invert, bursts=False,
burst_picker=burst_picker_list[ix],
scroll=scroll_list[ix], cache_bins=True,
show_rate_th=show_rate_th, F=F, ax=ax,
rate_th_style=rate_th_style, set_ax_limits=set_ax_limits,
plot_style=plot_style)
if legend:
ax.legend(loc='best', fancybox=True)
@_ax_intercept
def ratetrace_single(d, i=0, m=None, max_num_ph=1e6, tmin=0, tmax=200,
ph_sel=Ph_sel('all'), invert=False, bursts=False,
burst_picker=True, scroll=False, plot_style={},
show_rate_th=True, F=None, rate_th_style={},
set_ax_limits=True, burst_color='#BBBBBB', ax=None):
"""Plot the ratetrace of timestamps for a photon selection.
See :func:`ratetrace` to plot multiple photon selections (i.e.
Donor and Acceptor photons) in one step.
"""
if tmax is None or tmax < 0:
tmax = d.time_max
if m is None:
m = d.m if m in d else 10
tmin_clk, tmax_clk = tmin / d.clk_p, tmax / d.clk_p
# Plot bursts
if bursts:
_plot_bursts(d, i, tmin_clk, tmax_clk, pmax=500, pmin=-500,
color=burst_color)
# Compute ratetrace
ph_times = d.get_ph_times(i, ph_sel=ph_sel)
iph1 = np.searchsorted(ph_times, tmin_clk)
iph2 = np.searchsorted(ph_times, tmax_clk)
if iph2 - iph1 > max_num_ph:
iph2 = iph1 + int(max_num_ph)
tmax = ph_times[iph2] * d.clk_p
warnings.warn(('Max number of photons reached in ratetrace_single().'
'\n tmax is reduced to %ds. To plot a wider '
'time range increase `max_num_ph`.') % tmax,
UserWarning)
ph_times = ph_times[iph1:iph2]
rates = 1e-3 * phrates.mtuple_rates(ph_times, m) / d.clk_p
if invert:
rates *= -1
times = phrates.mtuple_rates_t(ph_times, m) * d.clk_p
# Plot ratetrace
plot_style_ = dict(linestyle='-', linewidth=1.2, marker=None)
if ph_sel in _ph_sel_color_dict:
plot_style_['color'] = _ph_sel_color_dict[ph_sel]
plot_style_['label'] = _ph_sel_label_dict[ph_sel]
plot_style_.update(_normalize_kwargs(plot_style, kind='line2d'))
ax.plot(times, rates, **plot_style_)
# Plot burst-search rate-threshold
if show_rate_th and 'bg' in d:
_plot_rate_th(d, i, F=F, ph_sel=ph_sel, ax=ax, scale=1e-3, invert=invert,
plot_style_=plot_style_, rate_th_style=rate_th_style)
ax.set_xlabel('Time (s)')
ax.set_ylabel('Rate (kcps)')
if burst_picker:
_gui_timetrace_burst_sel(d, ax.figure, ax)
if scroll:
_gui_timetrace_scroll(ax.figure)
if set_ax_limits:
ax.set_xlim(tmin, tmin + 1)
if not invert:
ax.set_ylim(top=100)
else:
ax.set_ylim(bottom=-100)
_plot_status['ratetrace_single'] = {'autoscale': False}
# same, must be plotted per channel always
@_ax_intercept
def ratetrace(d, i=0, m=None, max_num_ph=1e6, tmin=0, tmax=200,
bursts=False, burst_picker=True, scroll=False,
show_rate_th=True, F=None, rate_th_style={'label': None},
show_aa=True, legend=False, set_ax_limits=True,
#dd_plot_style={}, ad_plot_style={}, aa_plot_style={}
burst_color='#BBBBBB', ax=None):
"""Plot the rate timetraces of photon timestamps.
Arguments:
d (Data object): the measurement's data to plot.
i (int): the channel to plot. Default 0.
max_num_ph (int): Clip the rate timetrace after the
max number of photons `max_num_ph` is reached.
tmin, tmax (float): min and max time (seconds) to include in the
timetrace. Note that a long time range and a small `binwidth`
can require a significant amount of memory.
bursts (bool): if True, plot the burst start-stop times.
burst_picker (bool): if True, enable the ability to click on bursts
to obtain burst info. This function requires the matplotlib's QT
backend.
scroll (bool): if True, activate a scrolling bar to quickly scroll
through the timetrace. This function requires the matplotlib's QT
backend.
show_rate_th (bool): if True, plot the burst search threshold rate.
F (bool): if `show_rate` is True, show a rate `F` times larger
than the background rate.
rate_th_style (dict): matplotlib style for the rate line.
show_aa (bool): if True, plot a timetrace for the AexAem photons.
If False (default), plot timetraces only for DexDem and DexAem
streams.
legend (bool): whether to show the legend or not.
set_ax_limits (bool): if True, set the xlim to zoom on a small portion
of timetrace. If False, do not set the xlim, display the full
timetrace.
burst_color (string): string containing the the HEX RGB color to use
to highlight the burst regions.
ax (mpl.axes): axis where plot will be generated
"""
# Plot bursts
if bursts:
tmin_clk, tmax_clk = tmin / d.clk_p, tmax / d.clk_p
_plot_bursts(d, i, tmin_clk, tmax_clk, ax, pmax=500, pmin=-500,
color=burst_color)
# Plot multiple timetraces
ph_sel_list = [Ph_sel(Dex='Dem'), Ph_sel(Dex='Aem')]
invert_list = [False, True]
burst_picker_list = [burst_picker, False]
scroll_list = [scroll, False]
if d.alternated and show_aa:
ph_sel_list.append(Ph_sel(Aex='Aem'))
invert_list.append(True)
burst_picker_list.append(False)
scroll_list.append(False)
for ix, (ph_sel, invert) in enumerate(zip(ph_sel_list, invert_list)):
if not bl.mask_empty(d.get_ph_mask(i, ph_sel=ph_sel)):
ratetrace_single(
d, i, m=m, max_num_ph=max_num_ph, tmin=tmin,
tmax=tmax, ph_sel=ph_sel, invert=invert, bursts=False,
burst_picker=burst_picker_list[ix],
scroll=scroll_list[ix],
show_rate_th=show_rate_th, F=F, ax=ax,
rate_th_style=rate_th_style, set_ax_limits=set_ax_limits)
if legend:
ax.legend(loc='best', fancybox=True)
def sort_burst_sizes(sizes, levels=np.arange(1, 102, 20)):
"""Return a list of masks that split `sizes` in levels.
Used by timetrace_fret to select burst based on size groups.
"""
masks = []
for level1, level2 in zip(levels[:-1], levels[1:]):
masks.append((sizes >= level1)*(sizes < level2))
masks.append(sizes >= level2)
return masks
# plot per channel always
@_ax_intercept
def timetrace_fret(d, i=0, gamma=1., ax=None, **kwargs):
"""Timetrace of burst FRET vs time. Uses `plot`."""
b = d.mburst[i]
bsizes = d.burst_sizes_ich(ich=i, gamma=gamma)
style_kwargs = dict(marker='o', mew=0.5, color=blue, mec='grey',
alpha=0.4, ls='')
style_kwargs.update(**kwargs)
t, E = b.start*d.clk_p, d.E[i]
levels = sort_burst_sizes(bsizes)
for ilev, level in enumerate(levels):
ax.plot(t[level], E[level], ms=np.sqrt((ilev+1)*15),
**style_kwargs)
ax.plot(b.start*d.clk_p, d.E[i], '-k', alpha=0.1, lw=1)
ax.set_xlabel('Time (s)')
ax.set_ylabel('E')
_gui_timetrace_burst_sel(d, ax.figure, ax)
# plot per channel always
@_ax_intercept
def timetrace_fret_scatter(d, i=0, gamma=1., ax=None, **kwargs):
"""Timetrace of burst FRET vs time. Uses `scatter` (slow)."""
b = d.mburst[i]
bsizes = d.burst_sizes_ich(ich=i, gamma=gamma)
style_kwargs = dict(s=bsizes, marker='o', alpha=0.5)
style_kwargs.update(**kwargs)
ax.scatter(b.start*d.clk_p, d.E[i], **style_kwargs)
ax.set_xlabel('Time (s)')
ax.set_ylabel('E')
# plot per channel always
@_ax_intercept
def timetrace_bg(d, i=0, nolegend=False, ncol=2, plot_style={}, show_da=False, ax=None):
"""Timetrace of background rates."""
bg = d.bg_from(Ph_sel('all'))
bg_dd = d.bg_from(Ph_sel(Dex='Dem'))
bg_ad = d.bg_from(Ph_sel(Dex='Aem'))
t = arange(bg[i].size) * d.bg_time_s
plot_style_ = dict(linewidth=2, marker='o', markersize=6)
plot_style_.update(_normalize_kwargs(plot_style, kind='line2d'))
label = "T: %d cps" % d.bg_mean[Ph_sel('all')][i]
ax.plot(t, 1e-3 * bg[i], color='k', label=label, **plot_style_)
label = "DD: %d cps" % d.bg_mean[Ph_sel(Dex='Dem')][i]
ax.plot(t, 1e-3 * bg_dd[i], color=green, label=label, **plot_style_)
label = "AD: %d cps" % d.bg_mean[Ph_sel(Dex='Aem')][i]
ax.plot(t, 1e-3 * bg_ad[i], color=red, label=label, **plot_style_)
if d.alternated:
bg_aa = d.bg_from(Ph_sel(Aex='Aem'))
label = "AA: %d cps" % d.bg_mean[Ph_sel(Aex='Aem')][i]
ax.plot(t, 1e-3 * bg_aa[i], label=label, color=purple, **plot_style_)
if show_da:
bg_da = d.bg_from(Ph_sel(Aex='Dem'))
label = "DA: %d cps" % d.bg_mean[Ph_sel(Aex='Dem')][i]
ax.plot(t, 1e-3 * bg_da[i], label=label,
color=_ph_sel_color_dict[Ph_sel(Aex='Dem')], **plot_style_)
if not nolegend:
ax.legend(loc='best', frameon=False, ncol=ncol)
ax.set_xlabel("Time (s)")
ax.set_ylabel("BG rate (kcps)")
ax.grid(True)
ax.set_ylim(bottom=0)
# plot per channel always
@_ax_intercept
def timetrace_b_rate(d, i=0, ax=None):
"""Timetrace of bursts-per-second in each period."""
t = arange(d.bg[i].size)*d.bg_time_s
b_rate = r_[[(d.bp[i] == p).sum() for p in range(d.bp[i].max()+1)]]
b_rate /= d.bg_time_s
if t.size == b_rate.size+1:
t = t[:-1] # assuming last period without bursts
else:
assert t.size == b_rate.size
ax.plot(t, b_rate, lw=2, label="CH%d" % (i+1))
ax.legend(loc='best', fancybox=True, frameon=False, ncol=3)
ax.set_xlabel("Time (s)")
ax.set_ylabel("Burst per second")
ax.grid(True)
ax.set_ylim(bottom=0)
# plot per channel always
@_ax_intercept
def time_ph(d, i=0, num_ph=1e4, ph_istart=0, ax=None):
"""Plot 'num_ph' ph starting at 'ph_istart' marking burst start/end.
TODO: Update to use the new matplotlib eventplot.
"""
b = d.mburst[i]
num_ph = int(num_ph)
SLICE = slice(ph_istart, ph_istart+num_ph)
ph_d = d.ph_times_m[i][SLICE][~d.A_em[i][SLICE]]
ph_a = d.ph_times_m[i][SLICE][d.A_em[i][SLICE]]
BSLICE = (b.stop < ph_a[-1])
start, end = b[BSLICE].start, b[BSLICE].stop
u = d.clk_p # time scale
ax.vlines(ph_d*u, 0, 1, color='k', alpha=0.02)
ax.vlines(ph_a*u, 0, 1, color='k', alpha=0.02)
ax.vlines(start*u, -0.5, 1.5, lw=3, color=green, alpha=0.5)
ax.vlines(end*u, -0.5, 1.5, lw=3, color=red, alpha=0.5)
ax.set_xlabel("Time (s)")
##
# Histogram plots
#
def _bins_array(bins):
"""When `bins` is a 3-element sequence returns an array of bin edges.
Otherwise returns the `bins` unchanged.
"""
if np.size(bins) == 3:
bins = np.arange(*bins)
return bins
# not channel specific hidden function
def _hist_burst_taildist(data, bins, pdf, ax, weights=None, yscale='log',
color=None, label=None, plot_style=None, vline=None):
hist = HistData(*np.histogram(data[~np.isnan(data)],
bins=_bins_array(bins), weights=weights))
ydata = hist.pdf if pdf else hist.counts
default_plot_style = dict(marker='o')
if plot_style is None:
plot_style = {}
if color is not None:
plot_style['color'] = color
if label is not None:
plot_style['label'] = label
default_plot_style.update(_normalize_kwargs(plot_style, kind='line2d'))
ax.plot(hist.bincenters, ydata, **default_plot_style)
if vline is not None:
ax.axvline(vline, ls='--')
ax.set_yscale(yscale)
if pdf:
ax.set_ylabel('PDF')
else:
ax.set_ylabel('# Bursts')
@_ax_intercept
def hist_width(d, i=0, bins=(0, 10, 0.025), pdf=True, weights=None,
yscale='log', color=None, plot_style=None, vline=None, ax=None):
"""Plot histogram of burst durations.
Parameters:
d (Data): Data object
i (int): channel index
bins (array or None): array of bin edges. If len(bins) == 3
then is interpreted as (start, stop, step) values.
pdf (bool): if True, normalize the histogram to obtain a PDF.
color (string or tuple or None): matplotlib color used for the plot.
yscale (string): 'log' or 'linear', sets the plot y scale.
plot_style (dict): dict of matplotlib line style passed to `plot`.
vline (float): If not None, plot vertical line at the specified x
position.
ax (mpl.axes): axis where plot will be generated
"""
if i is None:
burst_widths = np.concatenate([mb.width for mb in d.mburst]) * d.clk_p * 1e3
else:
weights = weights[i] if weights is not None else None
burst_widths = d.mburst[i].width * d.clk_p * 1e3
_hist_burst_taildist(burst_widths, bins, pdf, ax, weights=weights, vline=vline,
yscale=yscale, color=color, plot_style=plot_style)
ax.set_xlabel('Burst width (ms)')
ax.set_xlim(xmin=0)
@_ax_intercept
def hist_brightness(d, i=0, bins=(0, 60, 1), pdf=True, weights=None,
yscale='log', gamma=1, add_naa=False, ph_sel=Ph_sel('all'), beta=1.,
donor_ref=True, naa_aexonly=False, naa_comp=False, na_comp=False,
label_prefix=None, color=None, plot_style=None, vline=None, ax=None):
"""Plot histogram of burst brightness, i.e. burst size / duration.
Parameters:
d (Data): Data object
i (int): channel index
bins (array or None): array of bin edges. If len(bins) == 3
then is interpreted as (start, stop, step) values.
gamma, beta (floats): factors used to compute the corrected burst
size. See :meth:`fretbursts.burstlib.Data.burst_sizes_ich`.
add_naa (bool): if True, include `naa` to the total burst size.
donor_ref (bool): convention used for corrected burst size computation.
See :meth:`fretbursts.burstlib.Data.burst_sizes_ich` for details.
na_comp (bool): **[PAX-only]** If True, multiply the `na` term
by `(1 + Wa/Wd)`, where Wa and Wd are the D and A alternation
durations (typically Wa/Wd = 1).
naa_aexonly (bool): **[PAX-only]** if True, the `naa` term is
corrected to include only A emission due to A excitation.
If False, the `naa` term includes all the counts in DAexAem.
The `naa` term also depends on the `naa_comp` argument.
naa_comp (bool): **[PAX-only]** If True, multiply the `naa` term by
`(1 + Wa/Wd)` where Wa and Wd are the D and A alternation
durations (typically Wa/Wd = 1). The `naa` term also depends on
the `naa_aexonly` argument.
label_prefix (string or None): a custom prefix for the legend label.
color (string or tuple or None): matplotlib color used for the plot.
pdf (bool): if True, normalize the histogram to obtain a PDF.
yscale (string): 'log' or 'linear', sets the plot y scale.
plot_style (dict): dict of matplotlib line style passed to `plot`.
vline (float): If not None, plot vertical line at the specified x
position.
ax (mpl.axes): axis where plot will be generated
"""
weights = weights[i] if weights is not None else None
if plot_style is None:
plot_style = {}
if i is None:
burst_widths = np.concatenate([mb.width for mb in d.mburst]) * d.clk_p * 1e3
else:
burst_widths = d.mburst[i].width * d.clk_p * 1e3
sizes, label = _get_sizes_and_formula(
d=d, ich=i, gamma=gamma, beta=beta, donor_ref=donor_ref,
add_naa=add_naa, ph_sel=ph_sel, naa_aexonly=naa_aexonly,
naa_comp=naa_comp, na_comp=na_comp)
brightness = sizes / burst_widths
label = '$(' + label[1:-1] + ') / w$'
if label_prefix is not None:
label = label_prefix + ' ' + label
# Use default label (with optional prefix) only if not explicitly
# specified in `plot_style`
if 'label' not in plot_style:
plot_style['label'] = label
_hist_burst_taildist(brightness, bins, pdf, ax, weights=weights, vline=vline,
yscale=yscale, color=color, plot_style=plot_style)
ax.set_xlabel('Burst brightness (kHz)')
ax.legend(loc='best')
def _get_sizes_and_formula(d, ich, gamma, beta, donor_ref, add_naa,
ph_sel, naa_aexonly, naa_comp, na_comp):
label = ('${FD} + {FA}/\\gamma$'
if donor_ref else '$\\gamma {FD} + {FA}$')
kws = dict(gamma=gamma, beta=beta, donor_ref=donor_ref)
if 'PAX' in d.meas_type and ph_sel is not None:
kws_pax = dict(ph_sel=ph_sel, naa_aexonly=naa_aexonly,
naa_comp=naa_comp, na_comp=na_comp)
if ich is None:
sizes = np.concatenate([d.burst_sizes_pax_ich(ich=i, **dict(kws, **kws_pax)) for i in range(d.nch)])
else:
sizes = d.burst_sizes_pax_ich(ich=ich, **dict(kws, **kws_pax))
label = '$ %s $' % d._burst_sizes_pax_formula(**dict(kws, **kws_pax))
else:
if ich is None:
sizes = np.concatenate([d.burst_sizes_ich(ich=i, add_naa=add_naa, **kws)
for i in range(d.nch)])
else:
sizes = d.burst_sizes_ich(ich=ich, add_naa=add_naa, **kws)
label = label.format(FD='n_d', FA='n_a')
if add_naa:
corr = '(\\gamma\\beta) ' if donor_ref else '\\beta '
label = label[:-1] + ' + n_{aa} / %s$' % corr
return sizes, label
# dependent on _hist_burst_taildist
@_ax_intercept
def hist_size(d, i=0, which='all', bins=(0, 600, 4), pdf=False, weights=None,
yscale='log', gamma=1, beta=1, donor_ref=True, add_naa=False,
ph_sel=None, naa_aexonly=False, naa_comp=False, na_comp=False,
vline=None, label_prefix=None, legend=True, color=None,
plot_style=None, ax=None):
"""Plot histogram of "burst sizes", according to different definitions.
Arguments:
d (Data): Data object
i (int): channel index
bins (array or None): array of bin edges. If len(bins) == 3
then is interpreted as (start, stop, step) values.
which (string): what photons to include in "size". Valid values are
'all', 'nd', 'na', 'naa'. When 'all', sizes are computed with
`d.burst_sizes()` (by default nd + na); 'nd', 'na', 'naa' get
counts from `d.nd`, `d.na`, `d.naa` (respectively Dex-Dem,
Dex-Aem, Aex-Aem).
gamma, beta (floats): factors used to compute the corrected burst
size. Ignored when `which` != 'all'.
See :meth:`fretbursts.burstlib.Data.burst_sizes_ich`.
add_naa (bool): if True, include `naa` to the total burst size.
donor_ref (bool): convention used for corrected burst size computation.
See :meth:`fretbursts.burstlib.Data.burst_sizes_ich` for details.
na_comp (bool): **[PAX-only]** If True, multiply the `na` term
by `(1 + Wa/Wd)`, where Wa and Wd are the D and A alternation
durations (typically Wa/Wd = 1).
naa_aexonly (bool): **[PAX-only]** if True, the `naa` term is
corrected to include only A emission due to A excitation.
If False, the `naa` term includes all the counts in DAexAem.