ROI_adjustment_check.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # ### Define paths and animals for the analysis
  4. # In[1]:
  5. path = '/media/andrey/My Passport/GIN/backup_Anesthesia_CA1/meta_data/meta_recordings - anesthesia.xlsx'
  6. path4results = '/media/andrey/My Passport/GIN/Anesthesia_CA1/validation/calcium_imaging/' #To store transformation matrix
  7. save_plots_path = '/media/andrey/My Passport/GIN/Anesthesia_CA1/validation/calcium_imaging/'
  8. log_file_path = save_plots_path + 'registration_logs.txt'
  9. animals_for_analysis = [37527]
  10. # ### Align FOV's for all recordings
  11. # In[2]:
  12. repeat_calc = 1
  13. silent_mode = False
  14. #######################
  15. import pandas as pd
  16. import numpy as np
  17. import os
  18. import matplotlib.pyplot as plt
  19. import sys
  20. np.set_printoptions(threshold=sys.maxsize)
  21. from pystackreg import StackReg
  22. # Sobel filter (not used)
  23. #from scipy import ndimage #https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.sobel.html
  24. meta_data = pd.read_excel(path, engine='openpyxl')
  25. #%% compute transformations matrices between recordings
  26. recordings = meta_data['Number']
  27. animals = animals_for_analysis
  28. #print("Recordings: ", recordings)
  29. #ALIGNMENT ALGORITHM
  30. sr = StackReg(StackReg.AFFINE)
  31. # ROI adjustment check for all recordings
  32. from matplotlib import colors
  33. Amap = colors.ListedColormap(['white','tab:blue', 'tab:red','purple'])
  34. '''
  35. if not os.path.exists(save_plots_path + 'ROIAdjustmentCheck/'):
  36. os.makedirs(save_plots_path + 'ROIAdjustmentCheck/')
  37. for animal in animals:
  38. if not os.path.exists(save_plots_path + 'ROIAdjustmentCheck/' + str(animal) + "/"):
  39. os.makedirs(save_plots_path + 'ROIAdjustmentCheck/' + str(animal) + "/")
  40. tmats_loaded = np.load(path4results + 'StackReg/' + str(animal) + "_best_tmats" + '.npy')
  41. meta_animal = meta_data[meta_data['Mouse'] == animal]
  42. recordings = meta_animal['Number'] #,'blue', 'green','cyan'])
  43. print(recordings)
  44. images = np.zeros((512, 512, np.shape(meta_animal)[0]))
  45. for idx, recording in enumerate(recordings):
  46. stats = np.load(meta_data['Folder'][recording] +
  47. str(meta_data['Subfolder'][recording]) +
  48. str(int(meta_data['Recording idx'][recording])) +
  49. '/suite2p/plane0/stat.npy',
  50. allow_pickle=True)
  51. iscell = np.load(meta_data['Folder'][recording] +
  52. str(meta_data['Subfolder'][recording]) +
  53. str(int(meta_data['Recording idx'][recording])) +
  54. '/suite2p/plane0/iscell.npy',
  55. allow_pickle=True)
  56. #stats = stats[iscell[:, 0].astype(bool)]
  57. for stats_neuron in stats:
  58. images[stats_neuron['ypix'], stats_neuron['xpix'], idx] += 1
  59. images[:,:,idx][images[:,:,idx]>1] = 1
  60. roi_corresp = np.zeros((512, 512))
  61. #for idx0 in range(np.shape(images)[2]):
  62. #for idx1 in range(idx0, np.shape(images)[2]):
  63. for idx0, recording0 in enumerate(recordings):
  64. for idx1, recording1 in enumerate(recordings):
  65. # roi_corresp = images[:,:,idx0] + 2*images[:,:,idx1]
  66. roi_corresp = images[:,:,idx0] + 2*sr.transform(images[:, :, idx1], tmats_loaded[idx0, idx1, :, :])
  67. file_title = str(idx0) + "_" + str(idx1) + "_" + meta_data['Condition'][recording0] + "_" + meta_data['Condition'][recording1]
  68. print(file_title)
  69. plt.imshow(roi_corresp[:,:],cmap=Amap) #'tab10'
  70. #plt.annotate('blue - reference / green - corrected / cyan - intersection', xy=(0, 0), xytext=(.8, 0), fontsize=12)
  71. plt.savefig(save_plots_path + "ROIAdjustmentCheck/" + str(animal) + '/' + file_title + "_ROI_correspondence.svg")
  72. #plt.show()
  73. '''
  74. if not os.path.exists(save_plots_path + 'ROIs/'):
  75. os.makedirs(save_plots_path + 'ROIs/')
  76. for animal in animals:
  77. if not os.path.exists(save_plots_path + 'ROIs/' + str(animal) + "/"):
  78. os.makedirs(save_plots_path + 'ROIs/' + str(animal) + "/")
  79. tmats_loaded = np.load(path4results + 'StackReg/' + str(animal) + "_best_tmats" + '.npy')
  80. meta_animal = meta_data[meta_data['Mouse'] == animal]
  81. recordings = meta_animal['Number'] #,'blue', 'green','cyan'])
  82. print(recordings)
  83. images = np.zeros((512, 512, np.shape(meta_animal)[0]))
  84. for idx, recording in enumerate(recordings):
  85. stats = np.load(meta_data['Folder'][recording] +
  86. str(meta_data['Subfolder'][recording]) +
  87. str(int(meta_data['Recording idx'][recording])) +
  88. '/suite2p/plane0/stat.npy',
  89. allow_pickle=True)
  90. iscell = np.load(meta_data['Folder'][recording] +
  91. str(meta_data['Subfolder'][recording]) +
  92. str(int(meta_data['Recording idx'][recording])) +
  93. '/suite2p/plane0/iscell.npy',
  94. allow_pickle=True)
  95. #stats = stats[iscell[:, 0].astype(bool)]
  96. print(iscell[:, 0].astype(bool).shape, ' vs ', iscell[:, 0].sum())
  97. print(stats.shape)
  98. for stats_neuron in stats:
  99. images[stats_neuron['ypix'], stats_neuron['xpix'], idx] += 1
  100. images[:,:,idx][images[:,:,idx]>1] = 1
  101. roi_corresp = np.zeros((512, 512))
  102. for idx0, recording0 in enumerate(recordings):
  103. #roi_corresp = sr.transform(images[:, :, idx0], tmats_loaded[0, idx0, :, :])
  104. roi_corresp = images[:, :, idx0]
  105. #roi_corresp [roi_corresp > 0.5] = 1
  106. file_title = str(idx0) + "_" + meta_data['Condition'][recording0]
  107. print(file_title)
  108. plt.imshow(roi_corresp[:,:],cmap='binary') #'tab10'
  109. plt.savefig(save_plots_path + "ROIs/" + str(animal) + '/' + file_title + "_ROIs.svg")