-
Notifications
You must be signed in to change notification settings - Fork 0
/
flo_histograms.py
executable file
·1808 lines (1291 loc) · 45.9 KB
/
flo_histograms.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
import os
import sys
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from matplotlib.patches import Rectangle
import scipy.stats
import scipy.optimize
from scipy.special import erf
from datetime import datetime
import inspect
from threading import Thread, Event
# my packages
from default_bins import *
from flo_fancy import *
import flo_functions as ff
default_colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
def cmaps_default_colors(base_color = "white", colors = True):
if not isinstance(colors, np.ndarray):
colors = default_colors
return(
[mpl.colors.LinearSegmentedColormap.from_list("", [base_color, color]) for color in default_colors]
)
def next_color(ax):
return(
ax.plot([])[0].get_color()
)
def nice_log_label(ax, axis = "y", loglim = 3):
def nicelabel(l, exp):
if l == 0:
return("0")
else:
return(f"${l} \\times 10^{{{exp}}}$")
if axis == "b":
nice_log_label(ax = ax, axis = "x", loglim = loglim)
nice_log_label(ax = ax, axis = "y", loglim = loglim)
return()
elif axis == "y":
tp = ax.get_yticks()
f_set = ax.set_yticklabels
elif axis == "x":
tp = ax.get_xticks()
f_set = ax.set_xticklabels
else:
raise ValueError("axis must be either 'x', 'y', or 'b'")
tp_log10 = np.log10(tp[tp>0])
if np.all(tp_log10 >= loglim):
print("scaling")
exp = int(np.max(tp_log10))
fact = 10**exp
tl = [nicelabel(l/fact, exp) for l in tp]
f_set(tl)
default_folder_out = f"/data/storage/userdata/{os.environ.get('USER')}"
def make_folder(path, msg_on_exist = False):
try:
os.mkdir(path)
print(f"created folder: {path}")
except FileExistsError:
if msg_on_exist is True:
print(f"folder exists already: {path}")
return(None)
def get_path(folder_name):
f'''
creates a folder in {default_folder_out}/
and returns full path
'''
path = f"{default_folder_out}/{folder_name}"
make_folder(path)
return(path)
def save_axs_individuially(axs, basename, fig = False, expand = True):
axs_ = axs.reshape(-1)
if fig is False:
fig = axs_[0].get_figure()
# turning all axis off to bot bleed into other plots
axs_on = [ax.axison for ax in axs_]
for ax in axs_:
ax.set_axis_off()
if expand is True:
expand = (1.3, 1.4)
for i_ax, ax in enumerate(axs_):
ax.set_axis_on()
title = ax.get_title()
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
if expand is not False:
extent = extent.expanded(1.3, 1.4)
fig.savefig(f'{basename}_{i_ax}_{title}.png', bbox_inches=extent)
ax.set_axis_off()
for ax, ax_on in zip(axs_, axs_on):
if ax_on is True:
ax.set_axis_on()
def calc_range(x, thr = False):
x_ = np.array(x)
if thr is not False:
x_ = x_[x_ > thr]
else:
x_ = x_
min_ = np.nanmin(x_)
max_ = np.nanmax(x_)
diff = max_ - min_
return(min_, max_, diff)
try:
from IPython.display import clear_output
def clear(*args, **kwargs):
clear_output(True)
except:
def clear(*args, **kwargs):
pass
# Info on Krypton:
# from wikipedia: https://en.wikipedia.org/wiki/Isotopes_of_krypton
# halflife 154.4(11) ns
tau_kr_lit = 154.4/np.log(2)
stau_kr_lit = 1.1/np.log(2)
str_tau_kr_lit = f"τ = ({tau_kr_lit:.1f} ± {stau_kr_lit:.1f}) ns"
label_tau_kr_lit = f"$\\tau = ({tau_kr_lit:.1f} \\pm {stau_kr_lit:.1f})$ ns"
def now():
return(datetime.now())
def snow(fmt = "%H:%M:%S"):
return(now().strftime(fmt))
def fraction_exp(a = 0, b = np.inf, tau = tau_kr_lit):
'''
calculates the integral of a normalized expoential function from a to b6
parameters:
a (default: 0): start of integration
b (default: inf): end of integration
tau (default: 222.6): mean lifetime of exponential
'''
return(np.exp(-a/tau) - np.exp(-b/tau))
def frac_sigmas(sigmas):
'''
calculates the area under a normal distribution sigmas sigmas around mu
'''
return(erf(np.array(sigmas)/(2)**.5))
def make_dict(**kwargs):
'''
a function for lazy people to turn the arguemnts of a fucntion call into a dictionary (via copy paste)
'''
return(
{n:v for n, v in kwargs.items()}
)
def make_fig(
nrows=1, ncols=1,
w=6, h=4,
rax = True,
n_tot = False,
axis_off = False,
custom_style = False,
*args, **kwargs):
'''
creates a figure with nrows by ncols plots
n_tot: total number of cells, overwrites nrow and ncols, set negative to make plot wider than tall
set its size to w*ncols and h*nrows
returns fig and reshapen ax (as 1d list) elements
axis_off (False): turns all axis off. Turn them on again with ax.set_axis_on()
'''
if "reshape_ax" in kwargs:
print("\33[31mfound old parameter reshape_ax. Use 'rax' from now on\33[0m")
rax = kwargs["reshape_ax"]
if n_tot is not False:
ncols = int(abs(n_tot)**.5)
nrows = int(np.ceil(abs(n_tot) / ncols))
if n_tot < 0:
ncols, nrows = nrows, ncols
fig, axs = plt.subplots(nrows, ncols, *args, **kwargs)
if custom_style is False:
plt.subplots_adjust(
left = .15,
right = .98,
top = .90,
bottom = .15,
hspace = .3,
wspace = .3,
)
fig.set_size_inches(ncols*w, nrows*h)
fig.set_facecolor("white")
fig.set_dpi(200)
if rax is True:
if isinstance(axs, plt.Axes):
axs = np.array([axs])
else:
axs = axs.reshape(-1)
if axis_off is True:
for ax in axs.reshape(-1):
ax.set_axis_off()
return(fig, axs)
def add_labs(ax, labs):
'''
order of labs: x, y, title
or dict with keys: x, y, t
'''
fs = {
"x": ax.set_xlabel,
"y": ax.set_ylabel,
"t": ax.set_title,
}
if isinstance(labs, (tuple, list)):
for l, f in zip(labs, "xyt"):
fs[f](l)
if isinstance(labs, dict):
for k, l in labs.items():
if k in fs:
fs[k](l)
def ax(*labs, **kwargs):
fig, ax = make_fig(**{"rax": False, **kwargs})
add_labs(ax, labs)
return(ax)
def ax2(*labs, reminder = True, **kwargs):
'''
use
'ax2.set_ylim(ax.get_ylim())'
before saving!!!!
'''
ax2 = ax(*labs, **kwargs)
ax_ = ax2.twinx()
if reminder is not False:
ax_.set_ylabel("call fhist.fax(ax, ax2) before saving to fix axis")
return(ax_, ax2)
def fax(ax_, ax2, setlabels_auto = True):
ax_.set_axis_off()
ax2.set_xscale(ax_.get_xscale())
ax2.set_yscale(ax_.get_yscale())
ax2.set_xlim(ax_.get_xlim())
ax2.set_ylim(ax_.get_ylim())
if (ax2.get_ylabel() == "") and (setlabels_auto is True):
ax2.set_xlabel(ax_.get_xlabel())
ax2.set_ylabel(ax_.get_ylabel())
def errorbar(
ax, x, y, sy,
sx = None,
ax2 = False,
color = None,
capsize = 0, capthick = 0,
linestyle = "", label = "",
marker = "", plot = False,
slimit = False,
*args, **kwargs):
if plot is True:
if marker is not "":
marker_plot = marker
else:
marker_plot = "."
color = ax.plot(x, y, marker = marker_plot, color = color, linestyle = linestyle, label = label, *args, **kwargs)[0].get_color()
label = None
if slimit is not False:
if slimit is True:
slimit = 10 * np.median(clean(sy))
sy[~np.isfinite(sy)] = slimit * 100
if isinstance(ax2, plt.Axes):
ax2.errorbar(x, y, yerr = sy, xerr = sx, color = color, capsize=capsize, capthick=capthick, linestyle=linestyle, marker=marker, *args, **kwargs)
if len(np.shape(sy)) == 2:
sy_ = np.max(sy, axis = 0)
else:
sy_ = sy
_, x, y, sy, sx = remove_zero(np.abs(sy_) < np.abs(slimit), x, y, sy, sx)
ax.errorbar(x, y, yerr = sy, xerr = sx, label = label, color = color, capsize=capsize, capthick=capthick, linestyle=linestyle, marker=marker, *args, **kwargs)
return(color)
def errorband(
ax,
x, y, sy,
color = "black",
alpha = .1,
alpha_line = 1,
**kwargs
):
ax.plot(x, y, color = color, alpha = alpha_line, **kwargs)
ax.fill_between(x, y-sy, y+sy, color = color, alpha = alpha)
return()
def median_gauss(
values,
bins_median = "auto",
f = ff.gauss,
ax = False,
bining_width_in_mads = 4,
show_fit_result = True,
show_p0 = False,
show_bw = False,
show_f = False,
show_gof = False,
return_chi2 = False,
return_all = False,
strict_positive = False,
label = "data",
capsize = 0,
capthick = 0,
*args, **kwargs
):
'''
returns mu, sigma, s_mu and the chi2-tuple (in that order) of an arbitrary distribution by a gaus fit
if the fit crashes returns 4 x nan
parameters:
bins_median ('auto'):
the bins for the values to be binned into (np.histogram(values, bins_median))
if set to 'auto' or number it will use the median +- 3 x mad and turn it into
25 or bins_median bins; otherwise use bins_median as bins
if set to negative number: dont use the smart aproch but just pass -1* that number to np.histogram
ax (False): if this is set to an matplotlib axis the fit is ploted into that axis
return_chi2 (False): wheter or not chi2 should be returned
return_all (False): wheter or not to return all available data
*args, *kwargs: the are not fed anywhere
'''
x_ = np.array(values)*1
x_ = x_[np.isfinite(x_)]
if strict_positive is True:
x_ = x_[x_ > 0]
med = np.median(x_)
width = bining_width_in_mads*np.median(np.abs(x_ - med))
if not isinstance(bins_median, (np.ndarray, list, tuple)):
lower_bound, upper_bound = med-width, med+width
if strict_positive is True:
lower_bound = np.max([0, lower_bound])
if bins_median == "auto":
bins_median = np.linspace(lower_bound, upper_bound, 12)
elif isinstance(bins_median, (int, float)):
if bins_median > 0:
bins_median = np.linspace(lower_bound, upper_bound, int(bins_median))
else:
bins_median = int(-bins_median)
counts, bins = np.histogram(values, bins = bins_median)
bc = get_bin_centers(bins)
bw = np.diff(bins)
s_counts = s_pois(counts)
s_counts_fit = np.max(s_counts, axis = 0)
density = counts / bw
s_density = s_counts / bw
p0 = f.p0(bc, counts)
color = False
if isinstance(ax, plt.Axes):
xf = np.linspace(min(bins), max(bins), 1000)
color = errorbar(
ax, bc, counts, s_counts,
label = f"{label} (N = {np.sum(counts):.0f}/{len(values)})",
plot = True,
capsize = capsize,
capthick = capthick,
)
if show_bw is True:
str_bw = (", ").join(np.unique([f"{bwi:.3g}" for bwi in bw]))
addlabel(ax, f"bin width: {str_bw}")
if show_p0 is True:
y0 = f(xf, *p0)
ax.plot(xf, y0, label = "p0")
for par_i, p, v in enumezip(f, p0):
add_fit_parameter(ax, p, v)
ret_all = {
"values": values,
"x_": x_,
"bins": bins,
"bc": bc,
"bw": bw,
"counts": counts,
"N": int(np.sum(counts)),
"s_counts": s_counts,
"density": density,
"s_density": s_density,
"p0": p0,
}
try:
fit, cov = scipy.optimize.curve_fit(
f,
bc,
counts,
p0 = p0,
absolute_sigma = True,
sigma = s_counts_fit,
)
sfit = np.diag(cov)**.5
chi2 = chi_sqr(f, bc, counts, s_counts, *fit, **kwargs)
ret_all["fit"] = fit
ret_all["sfit"] = sfit
ret_all["cov"] = cov
ret_all["chi2"] = chi2
if isinstance(ax, plt.Axes):
yf = f(xf, *fit)
if show_f is True:
addlabel(ax, f)
if show_gof is True:
label_f = f"fit {chi2[-1]}"
else:
label_f = ""
ax.plot(xf, yf, label = label_f, color = color)
if show_fit_result is True:
for i_par, par, val, sval in enumezip(f, fit, sfit):
if i_par > 0:
add_fit_parameter(ax, par, val, sval)
ax.legend(loc = "upper right")
ax.set_ylabel("counts")
out = (fit[1], np.abs(fit[2]), sfit[1])
except RuntimeError as e:
ret_all["error"] = e
out = (float("nan"), float("nan"), float("nan"))
if return_chi2 is True:
out = (*out, chi2)
if return_all is True:
out = (*out, ret_all)
return(out)
def sliding(*x, f = False, ext = 1):
if f is False:
def f(*args):
return(args)
x_ = np.array(x).T
return(
[f(x_[np.arange(max(0, i-ext), min(len(x_), i+ext+1))].T) for i in np.arange(len(x_))]
)
def median(x, percentile = 68.2, clean = True, ax=False, return_all = False, *args, **kwargs):
'''
strict_positive is just for comatablitiy with median_gauss
'''
x_ = np.array(x)*1
if clean is True:
x_ = x_[np.isfinite(x_)]
n = len(x_)
med = np.median(x_)
mad = np.percentile(np.abs(x_ - med), percentile)
mn, std, unc_mn = mean(x_)
unc_med = unc_mn * (np.pi*((2*n+1)/4/n))**.5
if isinstance(ax, plt.Axes):
x_sort = np.sort(x_)
ax.set_ylabel("fraction")
fraction = np.linspace(0,1, len(x_sort))
ax.plot(x_sort, fraction, ".-", label = f"datapoints (N = {n})")
col = ax.plot([], "")[0].get_color()
ax.axhline(.5, color = col, linestyle = "dashed")
ax.axvline(med, label = f"median: ${tex_value(med, unc_med)}$", color = col)
ax.axvspan(med-unc_med,med+unc_med, color = col, alpha = .25)
ax.axvspan(med-mad,med+mad, label = f"68% spread: {mad:.1f}", color = col, alpha = .1)
ax.legend(loc = "lower right")
ret_all = {
"N": len(x_),
}
out = med, mad, unc_med
if return_all is True:
out = (*out, ret_all)
return(out)
def mean(x, clean = True, *args, **kwargs):
x_ = np.array(x)*1
if clean is True:
x_ = x_[np.isfinite(x_)]
med = np.mean(x_)
mad = np.std(x_, ddof = 1)
unc_med = mad/len(x_)**.5
return(med, mad, unc_med)
def mean_w(x, sx, clean = True, *args, **kwargs):
'''
weighted mean with uncertainty
weights are calculated from sx by 1/sx**2 (inverse variance)
'''
x_ = np.array(x)*1
sx_ = np.array(sx)*1
if clean is True:
_, x_, sx_ = remove_zero((np.isfinite(x_) & np.isfinite(sx_) & (sx_ > 0)), x_, sx_)
w = sx_**-2
w_ = w/np.sum(w)
mean = np.sum(w_ * x_)
std = np.std(x_, ddof = 1)
# from Kamke
unc_mean = 1/np.sum(w)**.5
return(mean, std, unc_mean)
def median_w(
x,
sx,
percentile = 68.2,
percentile_med = 50
):
'''
returns the weighted median for x with uncertainty sx
further parameters:
* percentile (def.: 68.2):
percentile for calculation of uncertainty
* percentile_med (def.: 50.0) :
percentil for median
returns:
median, mad and uncertainty
'''
x, sx = sort(x, sx)
w = 1/sx
wx = w * x
s_wx = np.sum(wx)
c_wx = np.cumsum(wx)
thr = s_wx * percentile_med/100
id_l = max(np.nonzero(c_wx <= thr)[0])
id_r = min(np.nonzero(c_wx >= thr)[0])
ids = np.array([id_l, id_r])
med = np.interp(thr, c_wx[ids], x[ids])
mad = np.percentile(np.abs(x - med), percentile)
unc_med = mad/len(x)**.5
return(med, mad, unc_med)
def count(x):
'''
counts each unique value in x
returns a dict
'''
return(
{
entrie: np.count_nonzero(np.array(x) == entrie)
for entrie in np.unique(x)
}
)
def s_pois(counts, rng = .682, return_range = False):
'''
# uses poissonian statistics to calculate asymmetric(!) uncertainties for given counts
'''
alpha = 1-rng
counts_ = np.array(counts)
low = scipy.stats.chi2.ppf(alpha/2, 2*counts_) / 2
high = scipy.stats.chi2.ppf(1-alpha/2, 2*counts_ + 2) / 2
low[counts_ == 0] = 0.0
if return_range is True:
return(np.array([low, high]))
return(np.array([counts_ - low, high - counts_]))
def binning(x, y, bins, label=None, fmt = ".1f"):
'''
returns y sorted into x-bins
x and y need to have the same form
label: how to name the bins
"bc" (default): use bin centers as name of bin
"br": use bin range as name of bin
'''
bin_centers = get_bin_centers(bins)
bin_ids = np.digitize(x, bins)-1
if label == "br":
bnames = [f"{x:{fmt}} to {y:{fmt}}" for x, y in zip(bins[:-1], bins[1:])]
elif label == "bc":
bnames = [f"{c:{fmt}}" for c in bin_centers]
else:
bnames = [c for c in bin_centers]
bin_contents = {bin_name: y[bin_ids==bin_id] for bin_id, bin_name in zip(range(len(bins)), bnames)}
return(bin_contents)
def dynamic_binning(x, y, N = 50):
x_sorted = np.sort(x)
bins = x_sorted[[*np.array(np.arange(0,len(x)-1, N)), len(x)-1]]
data = binning(x, y, bins = bins)
return(bins, data)
def get_binned_median(x, y, bins, f_median = median_gauss, n_counts_min=10, path_medians = False, xlabel= "value", title = "", strict_positive = False, md_min_value = False, ax = False, color = True):
'''
replaces %BC% in path_medians with current bin/label
'''
ax_ = False
if "ax" not in inspect.getfullargspec(f_median).args:
path_medians = False
binned_data = binning(x, y, bins, label = None)
bc_all = get_bin_centers(bins)
bw = np.diff(bins)
df = pd.DataFrame()
if isinstance(ax, plt.Axes) and isinstance(color, bool):
color = ax.plot([])[0].get_color()
if (strict_positive is True) and (md_min_value is False):
md_min_value = 0
for bwi, bc_i, (bc, values) in zip(bw, bc_all, binned_data.items()):
N = len(values)
if N >= n_counts_min:
if isinstance(path_medians, str):
ax_ = ax()
ax_.set_xlabel(xlabel)
ax_.set_title(title.replace("%BC%", f'{bc:.1f}'))
*median_result, ret_all = f_median(values, ax = ax_, strict_positive = strict_positive, return_all = True)
if np.all(np.isfinite(median_result)) and (ret_all["N"] >= n_counts_min):
md, spr, smd = median_result
if (md_min_value is False) or (md >= md_min_value):
res = {
"bc": bc,
"N": len(values),
"median": md,
"s_median": smd,
"spread": spr,
}
df = df.append(res, ignore_index = True)
if isinstance(ax, plt.Axes):
bc_y = ret_all["bc"]
cx = ret_all["counts"]
scx = ret_all["s_counts"]
scale = (bwi * .9) / np.max(cx+scx)
xp = cx*scale + bc_i - bwi/2
sxp = [scx[0]*scale, scx[1]*scale]
errorbar(ax, x = xp, sx = sxp, sy = None, y = bc_y, plot = True, color = color, alpha = .1)
yp_fit = lin_or_logspace(bc_y, 100)
xp_fit = ff.gauss(yp_fit, *ret_all["fit"]) * scale + bc_i - bwi/2
ax.plot(xp_fit, yp_fit, color = color, alpha = .5)
if isinstance(ax_, plt.Axes):
plt.subplots_adjust(top = .85)
plt.savefig(path_medians.replace("%BC%", f'{bc:.1f}'))
plt.close()
try:
df = df.astype({"N": int})
except KeyError:
pass
return(df)
def draw_counts(
ax,
bc, counts, s_counts = False,
draw_unc = True,
color = None,
normalize = True,
label = "",
skip_zero = True,
y_offset = 0,
verbose = False,
**kwargs
):
if not isinstance(ax, plt.Axes):
raise TypeError("ax must be of type plt.Axes")
if (s_counts is False):
s_counts = s_pois(counts)
if len(bc) == (len(counts)+1):
bc = get_bin_centers(bc)
n_tot = np.sum(counts)
if n_tot == 0:
if skip_zero is True:
return(0)
else:
raise ValueError("no counts found")
if normalize is True:
counts_plot = counts/n_tot
s_counts_plot = s_counts / n_tot
y_offset = y_offset/n_tot
else:
counts_plot = counts
s_counts_plot = s_counts
counts_plot += y_offset
color = ax.plot(bc, counts_plot, drawstyle = "steps-mid", label = f"{label}", color = color, **kwargs)[0].get_color()
if draw_unc is True:
ax.fill_between(bc, counts_plot-s_counts_plot[0], counts_plot+s_counts_plot[1], step = "mid", alpha = .2, color = color)
return(color)
def calc_linearity(x, y, sy, ax = False, color = None, units_xy = False, **kwargs):
if units_xy is False:
units_0 = [""]
units_1 = ["", ""]
elif isinstance(units_xy, (list, tuple, np.ndarray)):
if len(units_xy) != 2:
raise ValueError("units_xy must have two entries!")
unit_x, unit_y = units_xy
units_0 = [unit_y]
if unit_x == "":
units_1 = [unit_y, unit_y]
else:
units_1 = [f"{unit_y}/{unit_x}", unit_y]
# f_fit_poly_0 = ff.poly_0
# fit_poly_0 = ff.fit(f_fit_poly_0, x, y, sy, ax = ax, color = color, units = units_0, label = "constant fit")
f_fit_poly_1 = ff.poly_1
fit_poly_1 = ff.fit(f_fit_poly_1, x, y, sy, ax = ax, color = color, units = units_1, label = "linear fit", kwargs_plot=dict(linestyle = "dashed"))
out = {
# "fit_poly_0": fit_poly_0,
# "f_fit_poly_0": f_fit_poly_0,
"fit_poly_1": fit_poly_1,
"f_fit_poly_1": f_fit_poly_1,
}
return(out)
def draw_binned_median_df(
df_median,
ax = False,
ax2 = False,
slimit = True,
bool_calc_linearity = False,
units_xy = False,
alpha_spr = 0,
draw_x_offset = 0,
**kwargs,
):
out = {}
x = df_median["bc"]
y = df_median["median"]
sy = df_median["s_median"]
spr = df_median["spread"]
out["data_binned"] = [x, y, sy, spr]
color = False
if isinstance(ax, plt.Axes):
color = errorbar(ax, x+draw_x_offset, y, sy, plot = True, slimit = slimit, **kwargs, ax2 = ax2)
if alpha_spr > 0:
_ = errorbar(ax, x+draw_x_offset, y, spr, color = color, alpha = .5, slimit = slimit, ax2 = ax2)
out["color"] = color
if bool_calc_linearity is True:
out_lin = calc_linearity(x, y, sy, ax = ax, color = color, units_xy = units_xy, **kwargs)
out = {**out, **out_lin}
return(out)
def str_range(x, op = False, debug = False):
'''
returns the range of x ("min to max") as a string
some operations (op) can be applied:
- "log10" takes the log10 of the absolute values
and adds the values sign
'''
try:
dp(f"len(x) at start: {len(x)}")
x = x[~np.isnan(x)]
dp(f"len(x) after removing nans: {len(x)}")
if op == False:
min_ = min(x)
max_ = max(x)
appendix = ""
elif op == "log10":
x = x[np.nonzero(x)]
dp(f"len(x) after removing zeros: {len(x)}")
min_ = min(x)
max_ = max(x)
min_ = np.sign(min_) * np.log10(abs(min_))
max_ = np.sign(max_) * np.log10(abs(max_))
appendix = " (log10)"
elif op == "abs":
abs_x = abs(x)
min_ = min(abs_x)
max_ = max(abs_x)
appendix = " (abs)"
digits = max(1, int(np.ceil(np.log10(abs(min_)))+2), int(np.ceil(np.log10(abs(max_)))+2), )
return(f"{min_:.{digits}f} to {max_:.{digits}f} {appendix}")
except Exception as e:
return(f"error: {e}")
def get_parameters(func, start = 0):