-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pomegranate_Hatzakislab_oct2020.py
1834 lines (1360 loc) · 64.3 KB
/
Pomegranate_Hatzakislab_oct2020.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 numpy as np
from pims import ImageSequence
import numpy as np
import pandas as pd
import trackpy as tp
import matplotlib as mpl
import matplotlib.pyplot as plt
from skimage.feature import peak_local_max
from scipy import ndimage
from skimage.feature import blob_log
from skimage import feature
from scipy.stats.stats import pearsonr
import os
import scipy
import scipy.ndimage as ndimage
from skimage import measure
from skimage.color import rgb2gray
from skimage import io
from pims import TiffStack
import scipy
from skimage import feature
from skimage.feature import peak_local_max
from scipy import ndimage
from skimage.feature import blob_log
from skimage import feature
from scipy.stats.stats import pearsonr
import os
import scipy
import scipy.ndimage as ndimage
from skimage import measure
from skimage.color import rgb2gray
import matplotlib.patches as mpatches
import glob
from skimage import measure
from pomegranate import *
import time
import random
import itertools
import cython
import probfit
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import ticker
from sklearn import neighbors
from tqdm import tqdm
import iminuit as Minuit
from probfit import BinnedLH, Chi2Regression, Extended, BinnedChi2, UnbinnedLH, gaussian
from matplotlib import patches
##################################################################################################################################
##################################################################################################################################
#################################### Edit below #################################################################
##################################################################################################################################
##################################################################################################################################
#save where for all below
save_path = "some_save_path" # must exist
#######################################################
#### specify parameters for challenge sets and simulated data #####
#################################################################
simulated_data = False # set to true to run
simul_data_path_training = "/some_path/"
simul_data_path_challenge = "/some_other_path/"
n_states = 2 # specify number of states
# create clustering, fit lifetimes and provide tdp
fit_tdp_simul = False # set to true to run
path_to_hmm_treated_challenge = "/some_path_to_csv_file_from_above"
n_clusters = 3 # provide number of clusters( transitions) to fit
# set framerate of data
sec_per_frame = 0.1 #
#######################################################
#### specify parameters for experimental sets #####
#################################################################
# Traces are cut to max 500 frames
experimental_sets = False # set to true to run
#please provide the enclosed model path "/The model.json"
path_to_general_model ="/some_path_to_enclosed_overall_model"
exp_data_folder_path = "/some_path_to_exp_folder_containing .dat files"
# create clustering, fit lifetimes and provide tdp
fit_tdp_exp=False#put true to run
path_to_hmm_treated_exp= "/some_path_to_csv_file_from_above"
n_clusters = 3 # provide number of clusters( transitions) to fit
# set framerate of data
sec_per_frame = 0.1 #
##################################################################################################################################
##################################################################################################################################
#################################### no more editing #################################################################
##################################################################################################################################
##################################################################################################################################
def f1(r,D):
if D> 0:
return (r/(2.*D*0.03))*np.exp(-((r**2)/(4.*D*0.03)))
else:
return 0
def f2(r,D2):
if D2> 0:
return (r/(2.*D2*0.03))*np.exp(-((r**2)/(4.*D2*0.03)))
else:
return 0
def f3(r,D3):
if D3> 0:
return (r/(2.*D3*0.03))*np.exp(-((r**2)/(4.*D3*0.03)))
else:
return 0
def f4(r,D4):
if D4> 0:
return (r/(2.*D4*0.03))*np.exp(-((r**2)/(4.*D4*0.03)))
else:
return 0
def fix_ax_probs(ax,x_label,y_label):
ax.set_ylabel(y_label, size = 12)
ax.set_xlabel(x_label, size = 12)
ax.tick_params(axis = 'both', which = 'major', labelsize = 10)
ax.tick_params(axis = 'both', which = 'minor', labelsize = 10)
return ax
def find_multiple_D_from_df(r,time_interval,distributions):
"""
Give a single list of step lengths - can thus be for a single particle or entire population
no need to create histogram as the function will find a pdf
Change time if needed
"""
r = np.asarray(r)
compdf1 = probfit.functor.AddPdfNorm(f1)
compdf2 = probfit.functor.AddPdfNorm(f1,f2)
compdf3 = probfit.functor.AddPdfNorm(f1,f2,f3)
compdf4 = probfit.functor.AddPdfNorm(f1,f2,f3,f4)
compdf5 = probfit.functor.AddPdfNorm(f1,f2,f3,f4,f5)
ulh1 = UnbinnedLH(compdf1, r, extended=False)
ulh2 = UnbinnedLH(compdf2, r, extended=False)
ulh3 = UnbinnedLH(compdf3, r, extended=False)
ulh4 = UnbinnedLH(compdf4, r, extended=False)
ulh5 = UnbinnedLH(compdf5, r, extended=False)
import iminuit
m1 = iminuit.Minuit(ulh1, D=1., limit_D = (0,5),pedantic= False,print_level = 0)
m2 = iminuit.Minuit(ulh2, D=1., limit_D = (0,5), D2=.1, limit_D2 = (0,5),pedantic= False,print_level = 0)
m3 = iminuit.Minuit(ulh2, D=1., limit_D = (0,5), D2=.1, limit_D2 = (0,5),pedantic= False,print_level = 0)
m1.migrad(ncall=10000)
m2.migrad(ncall=10000)
return m1,m2
def fix_ax_probs(ax,x_label,y_label):
ax.set_ylabel(y_label, size = 12)
ax.set_xlabel(x_label, size = 12)
ax.tick_params(axis = 'both', which = 'major', labelsize = 10)
ax.tick_params(axis = 'both', which = 'minor', labelsize = 10)
ax.grid(False)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.legend(loc = "upper right",frameon = False)
return ax
def _bic(data_len, k_states, log_likelihood):
return np.log(data_len) * k_states - 2 * log_likelihood
def get_model_from_dataframe(df,distributions,save_path,n_states_bic):
print ("Generating model...")
#df= df[df.steplength > 0.01]
data = df['FRET_E'].tolist()
data=np.asarray(data)
data = data.reshape(1, -1)
data_to_fit = []
group_all = df.groupby('particle')
for name, group in group_all:
data_to_fit.append(np.asarray(group.FRET_E.tolist()))
# learn from data
model = HiddenMarkovModel.from_samples(NormalDistribution, n_components=int(distributions), X=data_to_fit)
model.fit(data_to_fit)
model.bake()
log= model.log_probability(data)
bic = _bic(len(data),n_states_bic,log)
print ("Model baked..")
t = model.to_json()
import json
with open(str(save_path+'data.json'), 'w', encoding='utf-8') as f:
json.dump(t, f)
# use custom fitted model is gen 2
return model,bic,log
def get_model_BIC(df,distributions):
print ("Generating model...")
df= df[df.steplength > 0.01]
data = df['steplength'].tolist()
data=np.asarray(data)
data = data.reshape(1, -1)
data_to_fit = []
group_all = df.groupby('particle')
for name, group in group_all:
data_to_fit.append(np.asarray(group.steplength.tolist()))
# learn from data
model = HiddenMarkovModel.from_samples(GammaDistribution, n_components=int(distributions), X=data_to_fit)
model.fit(data_to_fit)
model.bake()
print ("Model baked..")
bic_long = model.log_probability(data)
return bic_long,model
def load_model(path):
import json
with open(str(path), 'r', encoding='utf-8') as f:
t = json.load(f)
model = HiddenMarkovModel.from_json(t)
return model
def find_d_single_from_df(r):
r = np.asarray(r)
def f1(r,D):
if D> 0:
return (r/(2.*D*0.030))*np.exp(-((r**2)/(4.*D*0.03)))
else:
return 0
compdf1 = probfit.functor.AddPdfNorm(f1)
ulh1 = UnbinnedLH(compdf1, r, extended=False)
import iminuit
m1 = iminuit.Minuit(ulh1, D=0.1, limit_D = (0,2),pedantic= False,print_level = 0)
m1.migrad(ncall=30000)
return m1.values['D']
def run_hmm_treat(df_raw,model,save_path):
print ("Running dataframe and fitting traces to hmm model...")
sub_path = str(save_path+'_traces_hmm/')
if not os.path.exists(sub_path): # creates a folder for saving the stuff in if it does not exist
os.makedirs(sub_path)
run = 0
df_raw = df_raw.sort_values(['particle','time'], ascending=True)
#df_raw = df_raw[df_raw.steplength >0.01]
df_new = pd.DataFrame()
df_new_full = pd.DataFrame()
group_all = df_raw.groupby('particle')
for name, group in tqdm(group_all):
tmp_trace = group.FRET_E.tolist()
tmp_trace = (np.asarray(tmp_trace))
tmp_trace_re = tmp_trace.reshape(-1, 1)
data_len = len(tmp_trace)
time = np.linspace(1, data_len, data_len)
d_full_trace = find_d_single_from_df(tmp_trace)
state_seq = model.predict(tmp_trace_re)
#if sum(np.diff(abs(np.asarray(state_seq[1:])))) ==0:
# fig,ax = plt.subplots(figsize=(6, 3))
# ax.plot(tmp_trace, "gray", linewidth = 3,alpha = 0.8)
# ax.set_ylabel("FRET")
# ax.set_xlabel("t")
# ax.set_ylim(0,1.5)
# ax.tick_params(axis = 'both', which = 'major', labelsize = 14)
# ax.tick_params(axis = 'both', which = 'minor', labelsize = 14)
# ax.spines['right'].set_visible(False)
# ax.spines['top'].set_visible(False)
# ax.grid(False)
# fig.tight_layout()
# fig.savefig(str(sub_path+str('__')+str(run)+'.pdf') )
# plt.clf()
# plt.close("all")
#
# run +=1
# continue
df = pd.DataFrame({"time": time, "step": tmp_trace, "state": state_seq})
df['track_id'] = str(name)
df["unique_state_ID"] = df["state"].transform(lambda group: (group.diff() != 0).cumsum())
df["idealized"] = df.groupby(["state"], as_index = False)["step"].transform("mean") # but does this make sense, better fit and fit a d either by fitting a straight line to msd or by fitting the very few data pointds tp a PDF
df["after"] = np.roll(df["idealized"], -1)
#
# if run %1 ==0:
# #print (str(("Plotting trace with hmm " + str(run))))
# fig,ax = plt.subplots(figsize=(6, 3))
#
# ax.plot(df['step'].values, "gray", linewidth = 1,alpha = 0.8)
# ax.plot(df['idealized'].values, "firebrick",linewidth = 1,alpha = 0.8)
#
# ax.set_ylabel("FRET")
# ax.set_xlabel("t")
# ax.set_ylim(0,1.5)
# ax.tick_params(axis = 'both', which = 'major', labelsize = 14)
# ax.tick_params(axis = 'both', which = 'minor', labelsize = 14)
# ax.spines['right'].set_visible(False)
# ax.spines['top'].set_visible(False)
# ax.grid(False)
# fig.tight_layout()
# fig.savefig(str(sub_path+'__'+str(run)+'__.pdf') )
# plt.clf()
# plt.close("all")
df['d'] = df.groupby('state')['step'].transform(find_d_single_from_df) # UBLH
df["d_after"] = np.roll(df["d"], -1)
df["state_jump"] = df["idealized"].transform(lambda group: (abs(group.diff()) != 0).cumsum())
df_tmp_full = df.copy()
df = df.drop_duplicates(subset = "state_jump", keep = "last")
df['single_d'] = d_full_trace
timedif = np.diff(df["time"])
timedif = np.append(np.nan, timedif)
df["lifetime"] = timedif
df['track'] = name
df = df[1:]
df_new= df_new.append(df, ignore_index = True)
df_new_full = df_new_full.append(df_tmp_full, ignore_index = True)
run +=1
return df_new ,df_new_full
#tester_df = pd.read_csv('/Volumes/Soeren/Lipase/treat_2/Amalie_L3/L3_product_toSoren/all_tracked_p2.csv', low_memory=False, sep = ',')
#fig,ax =plt.subplots(2,1)
#a=ax[0].hist2d(tester_df['x'],tester_df['y'],10,weights = tester_df['steplength'])
#b=ax[1].hist2d(tester_df['x'],tester_df['y'],10)
def create_grid_like_data_labels(df,max_val,grid_size):
"""
Put spt data into grid
max_val is location in pixel or micron, depending on data type
"""
max_val = 81.2
grid_size = 10
sections = np.linspace(0,max_val,int(grid_size))
grid_id = np.arange(0,len(sections),1)
x_vals = np.asarray(df['x'].tolist())
y_vals = np.asarray(df['y'].tolist())
grid_id_list = []
#for x,y in zip(sections):
def countour_2d(xdata, ydata, n_colors = 2, kernel = "gaussian", extend_grid = 1, bandwidth = 0.1, shade_lowest = False, gridsize = 100, bins = "auto"):
"""
Valid kernels for sklearn are
['gaussian' | 'tophat' | 'epanechnikov' | 'exponential' | 'linear' | 'cosine']
Example
-------
X, Y, Z, lev = countour_2d(x, y, shade_lowest = False)
fig, ax = plt.subplots()
c = ax.contourf(X,Y,Z, levels=lev, cmap = "inferno")
fig.colorbar(c)
Alternatively, unpack like
contour = countour_2d(x, y, shade_lowest = False)
c = ax.contourf(*contour)
"""
if kernel == "epa":
kernel = "epanechnikov"
# Stretch the min/max values to make sure that the KDE goes beyond the outermost points
meanx = np.mean(xdata)*extend_grid
meany = np.mean(ydata)*extend_grid
# Create a grid for KDE
X, Y = np.mgrid[min(xdata)-meanx:max(xdata)+meanx:complex(gridsize),min(ydata)-meany:max(ydata)+meany:complex(gridsize)]
positions = np.vstack([X.ravel(), Y.ravel()])
values = np.vstack([xdata, ydata])
# Define KDE with specified bandwidth
kernel_sk = neighbors.KernelDensity(kernel = kernel, bandwidth = bandwidth).fit(list(zip(*values)))
Z = np.exp(kernel_sk.score_samples(list(zip(*positions))))
Z = np.reshape(Z.T, X.shape)
if not shade_lowest:
n_colors += 1
locator = ticker.MaxNLocator(n_colors, min_n_ticks = n_colors)
if len(bins) > 1:
levels = bins
elif bins is "auto":
levels = locator.tick_values(Z.min(), Z.max())
else:
raise ValueError("Levels must be either a list of bins (e.g. np.arange) or 'auto'")
if not shade_lowest:
levels = levels[1:]
return X, Y, Z, levels
def error_ellipse(xdata, ydata, n_std, ax = None, return_ax = False, **kwargs):
"""
Parameters
----------
xdata : array-like
ydata : array-like
n_std : scalar
Number of sigmas (e.g. 2 for 95% confidence interval)
ax : ax to plot on
return_ax : bool
Returns axis for plot
return_inside : bool
Returns a list of True/False for inside/outside ellipse
**kwargs
Passed to matplotlib.patches.Ellipse. Color, alpha, etc..
Returns
-------
Ellipse with the correct orientation, given the data
Example
-------
x = np.random.randn(100)
y = 0.1 * x + np.random.randn(100)
fig, ax = plt.subplots()
ax, in_out = _define_eclipse(x, y, n_std = 2, ax = ax, alpha = 0.5, return_ax = True)
ax.scatter(x, y, c = in_out)
plt.show()
"""
def _eigsorted(cov):
vals, vecs = np.linalg.eigh(cov)
order = vals.argsort()[::-1]
return vals[order], vecs[:, order]
points = np.stack([xdata, ydata], axis = 1) # Combine points to 2-column matrix
center = points.mean(axis = 0) # Calculate mean for every column (x,y)
# Calculate covariance matrix for coordinates (how correlated they are)
cov = np.cov(points, rowvar = False) # rowvar = False because there are 2 variables, not nrows variables
vals, vecs = _eigsorted(cov)
angle = np.degrees(np.arctan2(*vecs[:, 0][::-1]))
width, height = 2 * n_std * np.sqrt(vals)
in_out = is_in_ellipse(xdata = xdata, ydata = ydata, center = center, width = width, height = height, angle = angle)
in_out = np.array(in_out)
if return_ax:
ellip = patches.Ellipse(xy = center, width = width, height = height, angle = angle, **kwargs)
if ax is None:
ax = plt.gca()
ax.add_artist(ellip)
# return ax, in_out
# else:
return in_out
def is_in_ellipse(xdata, ydata, center, width, height, angle):
"""
Determines whether points are in ellipse, given the parameters of the ellipse
Parameters
----------
xdata : array-like
ydata : array-lie
center : array-like, tuple
center of the ellipse as (x,y)
width : scalar
height : scalar
angle : scalar
angle in degrees
Returns
-------
List of True/False, depending on points being inside/outside of the ellipse
"""
cos_angle = np.cos(np.radians(180 - angle))
sin_angle = np.sin(np.radians(180 - angle))
xc = xdata - center[0]
yc = ydata - center[1]
xct = xc * cos_angle - yc * sin_angle
yct = xc * sin_angle + yc * cos_angle
rad_cc = (xct ** 2 / (width / 2) ** 2) + (yct ** 2 / (height / 2) ** 2)
in_ellipse = []
for r in rad_cc:
in_ellipse.append(True) if r <= 1. else in_ellipse.append(False)
return in_ellipse
def create_tdp_basic(df,save_path):
"""
Used to initial inspection of data
"""
blanchard_cols = ["#FDF9E9", "#FDF9E9", "#FFFFFF", "#BACAE9", "#88AAD8", "#527FC0", "#2E5992", "#00AAA4", "#3AB64A", "#CADB2A", "#FFF203", "#FFD26F", "#FAA841", "#F5834F", "#ED1D25"]
ccmap_lines = ["lightgrey", "#FFFFFF", "#BACAE9", "#88AAD8", "#527FC0", "#2E5992", "#00AAA4", "#3AB64A", "#CADB2A", "#FFF203", "#FFD26F", "#FAA841", "#F5834F", "#ED1D25"]
import uncertainties as un
import uncertainties.umath as umath
from uncertainties import unumpy as unp
import matplotlib
import matplotlib.colors as mcolors
from matplotlib.colors import LinearSegmentedColormap
import seaborn as sns
blanchard_cmap = LinearSegmentedColormap.from_list(name = "", colors = blanchard_cols)
import matplotlib.colors as mcolors
std_cols = sns.color_palette("Set2", 8)
from sklearn import mixture, decomposition, cluster
from tqdm import tqdm
df = df[ abs(df.after-df.idealized)>0.007]
fig,ax = plt.subplots(figsize = (3,3))
ax.hist(df['idealized'],50, color = "gray",density = True, range = (0,1.1),alpha =0.7)
ax = fix_ax_probs(ax,'Idealized steps','Density')
fig.tight_layout()
fig.savefig(str(save_path+'idealized_steplength_hist.pdf'))
plt.close('all')
cbins = np.arange(0, 7, 0.5)
cont = countour_2d(xdata = df["lifetime"]/1000,
ydata = df["life_after"]/1000,
kernel = "linear",
bandwidth = 0.1,
shade_lowest = True,
gridsize = 80,
n_colors = len(blanchard_cols),
bins = cbins)
fig, ax = plt.subplots(figsize=(3, 3))
c = ax.contourf(*cont, cmap = blanchard_cmap, extend = "both")
ax.set_ylim(0,1)
ax.set_xlim(0,1)
ax = fix_ax_probs(ax,'Idealized','Idealized after')
fig.colorbar(c, ax = ax, extendrect = True)
fig.tight_layout()
fig.savefig(str(save_path+'_TDP_non_sorted_steps.pdf'))
fig.savefig(str(save+'newtdp_from_life.pdf'))
plt.close()
def histbins(binmin, binmax, binwidth = 0.03):
return np.arange(binmin, binmax, binwidth)
def flatten_list(input_list, as_array = False):
"""
:param input_list: a list of lists
:return a single list of all the merged lists
"""
flat_list = list(itertools.chain.from_iterable(input_list))
if as_array:
return np.array(flat_list)
else:
return flat_list
def lh_fit(data, f, binned_likelihood, **kwargs):
import iminuit
"""
Parameters
----------
data: array
unbinned data to fit
f: function
function to fit which returns the likelihood
binned_likelihood: bool
binned or unbinned likelihood
kwargs:
write parameters to fit like a (scalar), a_limit (range), fix_a (bool)
Returns
-------
params: array
array of estimated fit parameters
errs: array
array of estimated fit parameter errors
loglh: scalar
the minimized log likelihood
"""
# Create an unbinned likelihood object with function and data.
if binned_likelihood:
minimize = probfit.BinnedLH(f, data)
else:
minimize = probfit.UnbinnedLH(f, data)
# Minimizes the unbinned likelihood for the given function
m = iminuit.Minuit(minimize,
**kwargs,
print_level = 0,
pedantic = False)
m.migrad()
params = np.array([val for val in m.values.values()])
errs = np.array([val for val in m.errors.values()])
log_lh = np.sum(np.log(f(data, *params)))
return params, errs, log_lh
### true lifetime and tdp
def create_tdf_file(df2,name,save_path,clusters):
df = df2
blanchard_cols = ["#FDF9E9", "#FDF9E9", "#FFFFFF", "#BACAE9", "#88AAD8", "#527FC0", "#2E5992", "#00AAA4", "#3AB64A", "#CADB2A", "#FFF203", "#FFD26F", "#FAA841", "#F5834F", "#ED1D25"]
ccmap_lines = ["lightgrey", "#FFFFFF", "#BACAE9", "#88AAD8", "#527FC0", "#2E5992", "#00AAA4", "#3AB64A", "#CADB2A", "#FFF203", "#FFD26F", "#FAA841", "#F5834F", "#ED1D25"]
import uncertainties as un
import uncertainties.umath as umath
from uncertainties import unumpy as unp
import matplotlib
import matplotlib.colors as mcolors
from matplotlib.colors import LinearSegmentedColormap
import seaborn as sns
blanchard_cmap = LinearSegmentedColormap.from_list(name = "", colors = blanchard_cols)
import matplotlib.colors as mcolors
std_cols = sns.color_palette("Set2", 14)
std_cols=(sns.color_palette("cubehelix", 12))
experiment_type = name
from sklearn import mixture, decomposition, cluster
from tqdm import tqdm
df = df[ abs(df.after-df.idealized)>0.007]
cbins = np.arange(0, 7, 0.5)
cont = countour_2d(xdata = df["idealized"],
ydata = df["after"],
kernel = "linear",
bandwidth = 0.2,
shade_lowest = True,
gridsize = 80,
n_colors = len(blanchard_cols),
bins = cbins)
uppr_diag = df2[df2["idealized"] < df2["after"]] # 0
lwer_diag = df2[df2["idealized"] > df2["after"]] # 1
halves = [uppr_diag, lwer_diag]
newdiags = []
for n, diag in enumerate(halves):
#diag['d']=np.log(diag['d'])
#diag['d_after']=np.log(diag['d_after'])
#diag_vals = diag.drop(['lifetime','time','step','state','unique_state_ID','idealized','single_d','after','state_jump','track','track_id','experiment_type'], axis = 1).as_matrix()
#diag_vals = diag.drop(['lifetime','time','step','state','unique_state_ID','d','single_d','track','d_after','state_jump','track_id','experiment_type'], axis = 1).as_matrix()
# for all hmm
diag_vals = diag.drop(['lifetime','time','step','state','unique_state_ID','d','d_after','state_jump','track_id','track'], axis = 1).as_matrix()
#diag_vals = diag.drop(['lifetime','time','step','state','unique_state_ID','idealized','after','state_jump','track_id','experiment_type','track'], axis = 1).as_matrix()
list(list(diag_vals))
diag["half"] = n
# ['Native','Native_product','L2','L3','Inactive']
if n ==1:
params = [[(0.26),(0.01)],
[(0.75),(0.01)],
[(0.99),(0.01)],
[(0.75),(0.26)],
[(0.99),(0.26)],
[(0.99),(0.75)]]
else:
params = [[(0.01),(0.26)],
[(0.01),(0.75)],
[(0.01),(0.75)],
[(0.26),(0.75)],
[(0.26),(0.99)],
[(0.75),(0.99)]]
# if name == 'Native_product':
# if n ==1:
# params = [[(0.4),(0.15)],[(0.13),(0.05)]]
#
# else:
# params = [[(0.13),(0.4)],[(0.05),(0.13)]]
#else:
# if n ==1:
# params = [[(0.8),(0.2)],[(0.25),(0.05)]]
#
# weights_init = [[(0.4),(0.2)],[(0.2),(0.2)]]
#
# else:
# params = [[(0.05),(0.2)],[(0.25),(0.8)]]
# weights_init = [[(0.2),(0.4)],[(0.1),(0.1)]]
#params2 = [[(1),(1)],[(0.11),(0.1)],[(0.11),(0.1)]]
#m = cluster.KMeans(n_clusters = clusters,n_init = 30,tol=1e-8).fit(diag_vals)
#m = mixture.GaussianMixture(n_components=clusters,warm_start = False, covariance_type='full').fit(diag_vals)
#m = mixture.GaussianMixture(n_components=clusters, means_init = params,warm_start = False, covariance_type='tied').fit(diag_vals)
m = mixture.GaussianMixture(n_components=clusters,warm_start = False, covariance_type='diag').fit(diag_vals)
diag["label"] = m.predict(diag_vals)
#diag["label"] = m.labels_
#centers = m.cluster_centers_
if n == 1:
diag["label"] += 2
newdiags.append(diag)
df2 = pd.concat(newdiags)
df2["d_pos"] = df2.groupby("label")["idealized"].transform(np.mean)
df2["d_pos_after"] = df2.groupby("idealized")["after"].transform(np.mean)
df2 = df2.sort_values(["half", "d_pos"])
#fig, ax = plt.subplots(figsize=(8, 8))
#ax = sns.scatterplot(x="d", y="d_after", hue="label",data=df_tmp)
newdiags = []
for i, diag in df2.groupby("half"):
if i == 0:
diag["label"] = diag["d_pos"].transform(lambda group: (group.diff() != 0).cumsum()) - 1
diag["label"] = 2 * diag["label"]
else:
diag["label"] = diag["d_pos"].transform(lambda group: (group.diff() != 0).cumsum()) - 1
diag["label"] = 2 * diag["label"] + 1
newdiags.append(diag)
df2 = pd.concat(newdiags)
df2 = df2.sort_values(["label"]).reset_index()
df2["state_grp"] = df2["label"] - df2["half"]
def fast_concat(temp_list):
"""
A faster way to make a dataframe, assuming that it's a shallow copy of ONE original dataframe.
Note that this function loses the original indices.
:param temp: a temporary list of sub-dataframes
:return: tdp_df: a concatenated Pandas dataframe, but faster than pd.concat()
"""
COLUMN_NAMES = temp_list[0].columns
df_dict = dict.fromkeys(COLUMN_NAMES, [])
for col in COLUMN_NAMES:
# Use a generator to save memory
extracted = (temp[col] for temp in temp_list)
# Flatten and save to df_dict
df_dict[col] = flatten_list(extracted)
df = pd.DataFrame.from_dict(df_dict)[COLUMN_NAMES]
del temp_list
return df
label_edits = []
print (set(df2['label']))
for i, grp in df2.groupby("label"):
print (i)
grp["in_out"] = error_ellipse(xdata = grp["idealized"].values, ydata = grp["after"].values, n_std = 5., return_ax = False, color = std_cols[i], alpha = 0.2)
grp["label"][grp["in_out"] == False] = -1
label_edits.append(grp)
df2 = fast_concat(label_edits)
fig,ax = plt.subplots(figsize = (5,5))
for i, grp in df2.groupby("label"):
e_bf, e_af = grp["idealized"], grp["after"]
ax.scatter(e_bf, e_af, zorder = 10, s = 12, color = "black" if i == -1 else std_cols[i])
ax = fix_ax_probs(ax,'D','D after')
fig.tight_layout()
fig.savefig(str(save_path+'_TDP_points_sorted_png_.png'))
fig.savefig(str(save_path+'_TDP_points_sorted.pdf'))
plt.clf()
plt.close('all')
df2 = df2[df2.in_out == True] # removing points we dont want
cbins = np.arange(0, 7, 0.5)
cont = countour_2d(xdata = df2["idealized"],
ydata = df2["after"],
kernel = "linear",
bandwidth = 0.2,
shade_lowest = True,
gridsize = 80,
n_colors = len(blanchard_cols),
bins = cbins)
fig, ax = plt.subplots(figsize=(4, 3))
c = ax.contourf(*cont, cmap = blanchard_cmap, extend = "both")
ax.set_ylim(-0.1,1.7)
ax.set_xlim(-0.1,1.7)
ax = fix_ax_probs(ax,'D','D after')
fig.tight_layout()
fig.colorbar(c, ax = ax, extendrect = True)
fig.savefig(str(save_path+'_D_tdp_true_cols_sort.pdf'), bbox_inches = "tight")
plt.close()
df2.to_csv(str(save_path+'__TDP_labels__.csv'), header=True, index=None, sep=',', mode='w')
bins = histbins(2, 30, 1)
plot_pts = np.linspace(2, 30, 300)
n_total = len(df2)
res = []
n = 0
import uncertainties as un
import uncertainties.umath as umath
def single_exp_fit(x, scale):
from scipy import signal, stats
return stats.expon.pdf(x, loc = 0, scale = scale)
def fit_func(x,start_val,rate): # function to fit
return start_val*np.exp(-rate*x)
fig, axes = plt.subplots(nrows = int(clusters), ncols = 2, figsize = (12, 12))
ax = axes.ravel()
fig2, axes2 = plt.subplots(nrows = int(clusters), ncols = 2, figsize = (12, 12))
ax2 = axes2.ravel()
#df2 = df2[df2.lifetime<25]
fig_iden,ax_iden = plt.subplots(figsize = (3,3))
for i, grp in tqdm(df2.groupby("label")):
if i == -1: # skip outlier labels
continue
# Convert to values for probfit
lifetime = grp["lifetime"].values
# if i ==0:
# d_mask = grp["idealized"].values
# d_mask = d_mask<0.03
# lifetime = lifetime[d_mask]
#lifetime_mask = lifetime>2
#lifetime_mask = lifetime<31
#lifetime = lifetime[lifetime_mask]
# Calculate where transitions are
E_bf = np.mean(grp["idealized"])
E_bf_std = np.std(grp["idealized"])
E_af = np.mean(grp["after"])
E_af_std = np.std(grp["after"])
ax_iden.annotate(str([i]), (E_bf,E_af), horizontalalignment='right', color = 'blue')
r_bf = (un.ufloat(E_bf, E_bf_std))
r_af = (un.ufloat(E_af, E_af_std))
E_bf_label = "{:.2f} $\pm$ {:.2f}".format(E_bf, E_bf_std)
E_af_label = "{:.2f} $\pm$ {:.2f}".format(E_af, E_af_std)
r_bf_label = "{:.2f} $\pm$ {:.2f}".format(r_bf.n, r_bf.s)
r_af_label = "{:.2f} $\pm$ {:.2f}".format(r_af.n, r_af.s)
success = 0
while success != 1: # keep removing datapoints until it works
scale, err, *_ = lh_fit(data = lifetime,
f = single_exp_fit,
binned_likelihood = True,
scale = 2.,
limit_scale = (0.1, 50.))
tau = un.ufloat(scale[0], err[0]) /(1/sec_per_frame)
rate = 1/tau
if tau.s > 0.8 * tau.n:
lifetime_cutoff -= 1
if lifetime_cutoff < 10:
success += 1
grp = grp[grp["lifetime"] <= lifetime_cutoff]
lifetime = grp["lifetime"].values
else:
success += 1
n_datapoints = len(lifetime)
n_percent = n_datapoints / n_total * 100
hist_label = r"$\tau$ (s) = {:.2f} $\pm$ {:.2f}".format(tau.n, tau.s) + \
"\n" + \
r"k = {:.2f} $\pm$ {:.2f}".format(rate.n, rate.s) + \
"\n" + \
"{} entries ({:.0f} %)".format(n_datapoints, n_percent)