Validation_stability.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # ### Link to the file with meta information on recordings
  4. # In[14]:
  5. #import matplotlib.pyplot as plt
  6. #plt.rcParams["figure.figsize"] = (20,3)
  7. database_path = '/media/andrey/My Passport/GIN/backup_Anesthesia_CA1/meta_data/meta_recordings_sleep.xlsx'
  8. # ### Select the range of recordings for the analysis (see "Number" row in the meta data file)
  9. # In[4]:
  10. rec = [x for x in range(0,74+1)]
  11. #rec = [1,2]
  12. # In[1]:
  13. import numpy as np
  14. import numpy.ma as ma
  15. import matplotlib.pyplot as plt
  16. import matplotlib.ticker as ticker
  17. import pandas as pd
  18. import seaborn as sns
  19. import pickle
  20. import os
  21. sns.set()
  22. sns.set_style("whitegrid")
  23. from scipy.signal import medfilt
  24. from scipy.stats import skew, kurtosis, zscore
  25. from scipy import signal
  26. from sklearn.linear_model import LinearRegression, TheilSenRegressor
  27. plt.rcParams['figure.figsize'] = [16, 8]
  28. color_awake = (0,191/255,255/255)
  29. color_mmf = (245/255,143/255,32/255)
  30. color_keta = (181./255,34./255,48./255)
  31. color_iso = (143./255,39./255,143./255)
  32. custom_palette ={'keta':color_keta, 'iso':color_iso,'fenta':color_mmf,'awa':color_awake}
  33. # In[2]:
  34. from capipeline import *
  35. # ### Run the analysis
  36. # /media/andrey/My Passport/GIN/Anesthesia_CA1/validation/calcium_imaging
  37. # It creates a data frame *df_estimators* that contains basic information regarding stability of the recordings, such as
  38. #
  39. # - total number of identified neurons,
  40. # - traces and neuropils median inntensities for each ROI
  41. # - their standard deviation
  42. # - skewness of the signal
  43. # - estamation of their baseline (defined as a bottom quartile of signal intensities)
  44. # - their temporal stability (defined as the ratio between median signals of all ROIs in the first and the second parts of the recording)
  45. # In[5]:
  46. '''
  47. df_estimators = pd.DataFrame()
  48. for r in rec:
  49. Traces, Npils, n_accepted_and_rejected = traces_and_npils(r, database_path, concatenation=False)
  50. print("Shape:" + str(Traces.shape[0]) + "N_accept_reject" + str(n_accepted_and_rejected))
  51. animal = get_animal_from_recording(r, database_path)
  52. #condition = get_condition(r, database_path)
  53. #print("#" + str(r) + " " + str(animal) + " " + str(condition) + " ")
  54. Traces_median = ma.median(Traces, axis=1)
  55. Npils_median = ma.median(Npils, axis=1)
  56. Traces_std = ma.std(Npils, axis=1)
  57. Npils_std = ma.std(Npils, axis=1)
  58. Traces_skewness = skew(Traces,axis=1)
  59. Npils_skewness = skew(Npils,axis=1)
  60. baseline = np.quantile(Traces,0.25,axis=1)
  61. num_cells = np.shape(Traces)[0]
  62. decay_isol = np.zeros((num_cells))
  63. fs = 30
  64. for neuron in np.arange(num_cells):
  65. if np.all(np.isnan(Traces[neuron])):
  66. decay_isol[neuron] = np.nan
  67. else:
  68. _, _, _, decay_neuron_isolated10, _ = deconvolve(np.double(Traces[neuron, ] + 100000),
  69. penalty = 0, optimize_g = 10)
  70. decay_isol[neuron] = - 1 / (fs * np.log(decay_neuron_isolated10))
  71. recording_length = int(Traces.shape[1])
  72. half = int(recording_length/2)
  73. print(recording_length)
  74. m1 = ma.median(Traces[:,:half])
  75. m2 = ma.median(Traces[:,half:])
  76. print("Stability:",m2/m1*100)
  77. norm_9000 = 9000/recording_length # normalize to 9000 frames (5 min recording)
  78. traces_median_half_vs_half = norm_9000*(m2-m1)*100/m1 + 100
  79. print("Stability (9000 frames normalization)",traces_median_half_vs_half)
  80. df_e = pd.DataFrame({ "animal":animal,
  81. "recording":r,
  82. #"condition":condition,
  83. "number.neurons":Traces.shape[0],
  84. "traces.median":Traces_median,
  85. "npils.median":Npils_median,
  86. "traces.std":Traces_std,
  87. "npils.std":Npils_std,
  88. "traces.skewness":Traces_skewness,
  89. "npils.skewness":Npils_skewness,
  90. "baseline.quantile.25":baseline,
  91. "decay":decay_isol,
  92. "median.stability":traces_median_half_vs_half # in percent
  93. })
  94. df_estimators = pd.concat([df_estimators,df_e])
  95. print("*****")
  96. # ### Save the result of the analysis
  97. # In[7]:
  98. df_estimators.to_pickle("./sleep_data_calcium_imaging_stability_validation.pkl")
  99. '''
  100. # ### Load the result of the analysis
  101. # In[8]:
  102. df_estimators = pd.read_pickle("./sleep_data_calcium_imaging_stability_validation.pkl")
  103. df_estimators['neuronID'] = df_estimators.index
  104. df_estimators["animal_cat"] = df_estimators["animal"].astype("category")
  105. # ### Plot
  106. # In[9]:
  107. parameters = ["animal",'number.neurons','traces.median','traces.skewness','decay','median.stability']
  108. labels = ["Animal \n ID",'Extracted \n ROIs','Median, \n A.U.','Skewness','Decay time, \n s','1st/2nd \n ratio, %']
  109. number_subplots = len(parameters)
  110. recordings_ranges = [[0,74]]
  111. for rmin,rmax in recordings_ranges:
  112. f, axes = plt.subplots(number_subplots, 1, figsize=(8, 4.5)) # sharex=Truerex=True
  113. #plt.subplots_adjust(left=None, bottom=0.1, right=None, top=0.9, wspace=None, hspace=0.2)
  114. #f.tight_layout()
  115. sns.despine(left=True)
  116. for i, param in enumerate(parameters):
  117. lw = 0.8
  118. #else:
  119. sns.boxplot(x='recording', y=param, data=df_estimators[(df_estimators.recording>=rmin)&(df_estimators.recording<=rmax)], width=0.9, dodge=False, showfliers = False,ax=axes[i],linewidth=lw)
  120. if (i == 0):
  121. param = "animal_cat"
  122. print(np.unique(df_estimators[param]))
  123. axes[i].set_yticks(np.unique(df_estimators[param]))
  124. sns.swarmplot(x='recording', y=param, data=df_estimators[(df_estimators.recording>=rmin)&(df_estimators.recording<=rmax)&(df_estimators['neuronID'] == 0)],dodge=False, s=1, edgecolor='black', linewidth=1, ax=axes[i])
  125. #ax.set(ylabel="")
  126. if i > 1:
  127. axes[i].set_ylim([0.0,2000.0])
  128. if i > 2:
  129. axes[i].set_ylim([0.0,10.0])
  130. if i > 3:
  131. axes[i].set_ylim([0.0,1.0])
  132. if i > 4:
  133. axes[i].set_ylim([80,120])
  134. axes[i].get_xaxis().set_visible(True)
  135. else:
  136. axes[i].get_xaxis().set_visible(False)
  137. if i < number_subplots-1:
  138. axes[i].xaxis.label.set_visible(False)
  139. if i==0:
  140. axes[i].set_title("Validation: stability check (recordings #%d-#%d)" % (rmin,rmax), fontsize=9, pad=30) #45
  141. axes[i].set_ylabel(labels[i], fontsize=8,labelpad=5) #40
  142. axes[i].set_xlabel("Recording", fontsize=8,labelpad=5) #40
  143. #axes[i].axis('off')
  144. axes[i].xaxis.set_tick_params(labelsize=6) #35
  145. axes[i].yaxis.set_tick_params(labelsize=6) #30
  146. #axes[i].get_legend().remove()
  147. axes[i].xaxis.set_major_locator(ticker.MultipleLocator(10))
  148. axes[i].xaxis.set_major_formatter(ticker.ScalarFormatter())
  149. #plt.legend(loc='upper right',fontsize=35)
  150. #plt.legend(bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.,fontsize=25)
  151. plt.savefig("Validation_stability_check_rec_#%d-#%d).png" % (rmin,rmax),dpi=400)
  152. plt.savefig("Validation_stability_check_rec_#%d-#%d).svg" % (rmin,rmax))
  153. #plt.show()
  154. # In[13]:
  155. sns.displot(data=df_estimators, x="median.stability", kind="kde", hue = "animal")
  156. plt.xlim([80,120])
  157. plt.xlabel("Stability, %", fontsize = 15)
  158. plt.title("Validation: summary on stability (recordings #%d-#%d)" % (min(rec),max(rec)), fontsize = 20, pad=20)
  159. plt.grid(False)
  160. plt.savefig("Validation_summary_stability_recordings_#%d-#%d)" % (min(rec),max(rec)))
  161. #plt.show()