forked from dladd/CardiacCalcium_TestCaCLEAN
/
SimulateMicroscopy.py
executable file
·359 lines (324 loc) · 14.8 KB
/
SimulateMicroscopy.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
#!/usr/bin/env python
'''
Author: David Ladd
Brief: Convert finite element FCa field results to simulated confocal
microscopy data to be processed by CaCLEAN.
Copyright 2019 David Ladd, University of Melbourne
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import inputs.utilities as util
import numpy as np
import math
import pandas as pd
import naturalneighbor
import skimage.io
import trimesh
import scipy
import scipy.io
from scipy import signal
import os
#import matplotlib.pyplot as plt
#=================================================================
# C l a s s e s
#=================================================================
class fieldInfo(object):
'base class for info about fields'
def __init__(self):
self.region = ''
self.group = ''
self.numberOfFields = 0
self.fieldNames = []
self.numberOfFieldComponents = []
# =====================================
# C o n t r o l P a n e l
# =====================================
inputsDir = "./inputs/"
outputsDir = "./simulatedMicroscopy_outputs/"
testCaCLEANOutputsDir = "./TestCaCLEAN_outputs/"
FE_modelDir = '../cardiaccalcium_finiteelement/'
# -------------------------------------
# Input nodal FE data info
# -------------------------------------
stopTime = 30. # finish time for the FEM simulation (ms)
startTime = 0.0 # start time for the FEM simulation (ms)
timeIncrement = 0.1 # timestep increment (ms)
numberOfProcessors = 8 # number of processors if run as an MPI job
species = [3] # Ca(1), F(2), FCa(3), CaM(4), CaMCa(5), ATP(6), ATPCa(7)
speciesLabel = ['FCa']
dependentFieldNumber = 2 # The dependent field of interest
outputFrequency = 50 # the output frequency of the FEM solver (or desired frequency to read the node data files at)
regSpace = 0.05375 #1075 #0.0215 0.05375 # regular grid spacing to interpolate to (in um)
outputSpacingStep = 4
psfFile = 'psf_50x50x140_53nmPx_fwhm_410xy_1800z.tif'
roundTo = regSpace
initFCa = 2.08
padding = 0
SNR = 100.0
# -------------------------------------
# Identify FEM I/O files
# -------------------------------------
meshDir = FE_modelDir + 'input/'
nodeFile = 'Combined_8Sarc_1319kNodes_node.h5' #'Combined_8Sarc_1436kNodes_node.h5'
FE_resultsDir = FE_modelDir + "output/"
surfaceMaskFile = "Combined_8Sarc_503kNodes_surfaceFixed.stl"
boundaryTol = 2.1*regSpace
# -------------------------------------
# Identify RyR I/O files
# -------------------------------------
spacingType = "1umSpacing"
mitoModel = 'NoMito'
numSarc = 8
numRyrPerSarc = 51 #123
maxClustersPerSlice = 400
numberOfKNodes = 1319 #1436 #1319
ryrClusterCentersDir = inputsDir + 'ryr_locations/N' + str(numRyrPerSarc) + '/'
detectRyrTol = 0.2
detectRyrTolInc = 0.01
detectRyrTolMax = 1.5000001
# -------------------------------------
# Read in the node and element maps generated by tetgen
print('Checking for node file...')
if not os.path.exists(meshDir + nodeFile):
print('Downloading node file to directory: ' + meshDir)
util.download_file(nodeFile, meshDir)
store = pd.HDFStore(meshDir + nodeFile)
df = store['Node_Coordinates']
totalNumberOfNodes = df.shape[0]
nodeX = np.ascontiguousarray(df.iloc[:, 0].values)
nodeY = np.ascontiguousarray(df.iloc[:, 1].values)
nodeZ = np.ascontiguousarray(df.iloc[:, 2].values)
nodeGeom = np.asarray(df)
store.close()
# -------------------------------------
# Output regular data info
# -------------------------------------
xGridMax = (math.ceil(np.max(nodeX)/(roundTo*outputSpacingStep)) + padding)*(roundTo*outputSpacingStep)
xGridMin = (math.floor(np.min(nodeX)/(roundTo*outputSpacingStep)) - padding)*(roundTo*outputSpacingStep)
yGridMax = (math.ceil(np.max(nodeY)/(roundTo*outputSpacingStep)) + padding)*(roundTo*outputSpacingStep)
yGridMin = (math.floor(np.min(nodeY)/(roundTo*outputSpacingStep)) - padding)*(roundTo*outputSpacingStep)
zGridMax = (math.ceil(np.max(nodeZ)/(roundTo*outputSpacingStep)) + padding)*(roundTo*outputSpacingStep)
zGridMin = (math.floor(np.min(nodeZ)/(roundTo*outputSpacingStep)) - padding)*(roundTo*outputSpacingStep)
gridDimensions = [(int((xGridMax - xGridMin)/regSpace + roundTo/100.0)+1),
(int((yGridMax - yGridMin)/regSpace + roundTo/100.0)+1),
(int((zGridMax - zGridMin)/regSpace + roundTo/100.0)+1)]
xGrid = [xGridMin, xGridMax, gridDimensions[0]*1j]
yGrid = [yGridMin, yGridMax, gridDimensions[1]*1j]
zGrid = [zGridMin, zGridMax, gridDimensions[2]*1j]
grid_ranges = [xGrid, yGrid, zGrid]
x = np.linspace(xGrid[0], xGrid[1], gridDimensions[0])[0:gridDimensions[0]:outputSpacingStep]
y = np.linspace(yGrid[0], yGrid[1], gridDimensions[1])[0:gridDimensions[1]:outputSpacingStep]
z = np.linspace(zGrid[0], zGrid[1], gridDimensions[2])[0:gridDimensions[2]:outputSpacingStep]
print(x)
print(y)
print(z)
xLen = len(x)
yLen = len(y)
zLen = len(z)
totalNumberOfGridPoints = xLen*yLen*zLen
# Create a list of points from the regular grid
grid = np.zeros((totalNumberOfGridPoints, 3))
c = 0
for i in range(xLen):
for j in range(yLen):
for k in range(zLen):
grid[c] = [x[i], y[j], z[k]]
c += 1
# -------------------------------------
# Read in FEM nodal data
# -------------------------------------
# Get number of timesteps
totalSimTime = stopTime - startTime
numberOfTimesteps = 1
if totalSimTime > timeIncrement:
numberOfTimesteps += int((totalSimTime/timeIncrement)/outputFrequency)
print('Number of timsteps: ' + str(numberOfTimesteps))
nn_interp = np.zeros((numberOfTimesteps, gridDimensions[0], gridDimensions[1], gridDimensions[2]))
interpDataFile = outputsDir + 'FCa_' + spacingType + '_' + mitoModel + '_interp' + str(int(regSpace*1000)) + '_' + str(numberOfTimesteps) + 'timesteps.npz'
try:
os.makedirs(outputsDir)
except OSError as e:
if e.errno != 17:
raise
# Check whether we have already read and stored the interpolated data
if os.path.isfile(interpDataFile):
with open(interpDataFile):
print('Reading interpolated data from: ' + interpDataFile)
loaded = np.load(interpDataFile)
nn_interp = loaded['nn_interp']
else:
specData = np.zeros((numberOfTimesteps, totalNumberOfNodes))
specGeomDataFile = outputsDir + 'FCa_' + spacingType + '_' + mitoModel + '_NodalData_' + str(numberOfTimesteps) + 'timesteps.npz'
# Check whether we have already read and stored the nodal data
if os.path.isfile(specGeomDataFile):
with open(specGeomDataFile):
print('Reading FEM data from: ' + specGeomDataFile)
loaded = np.load(specGeomDataFile)
specData = loaded['spec']
nodeGeom = loaded['geom']
else:
# Collect geometry and species data from OpenCMISS .exnode files
fields = fieldInfo()
for timestep in range(numberOfTimesteps):
nodeData = np.zeros((totalNumberOfNodes,4))
outputStep = timestep * outputFrequency
s = 0
for speciesNumber in species:
filenameRoot = FE_resultsDir + 'TIME_STEP_SPEC_'+ str(speciesNumber) + '.part'
for proc in range(numberOfProcessors):
filename = filenameRoot + str(proc).zfill(2) + '.' + str(outputStep).zfill(3) + '.exnode'
#filename += str(proc).zfill(2) + '.300.exnode'
importNodeData = np.zeros((totalNumberOfNodes,4))
print('Reading: ' + filename)
util.readExnode(filename,fields,importNodeData,totalNumberOfNodes,dependentFieldNumber)
nodeData += importNodeData
specData[timestep] = nodeData[:,3]
s+=1
print('Saving nodal data to: ' + specGeomDataFile)
# Save nodal data
np.savez_compressed(specGeomDataFile, spec=specData, geom=nodeGeom)
for timestep in range(numberOfTimesteps):
print(' Performing discrete Sibson interpolation, Time (ms): ' + str(timestep*timeIncrement*outputFrequency))
specData[timestep, specData[timestep] < 0.01] = initFCa
nn_interp[timestep] = naturalneighbor.griddata(nodeGeom, specData[timestep], grid_ranges)
# Save interpolated data
np.savez_compressed(interpDataFile, nn_interp=nn_interp)
print('Saving interpolated data to: ' + interpDataFile)
# -------------------------------------
# Convolve image against selected PSF
# -------------------------------------
convolve = True
if convolve:
# download the psf file if needed
print('Checking for PSF file...')
if not os.path.exists(inputsDir + psfFile):
print('Downloading PSF file to directory: ' + inputsDir)
util.download_file(psfFile, inputsDir)
convolved = np.zeros_like(nn_interp)
psfOrig = skimage.io.imread(inputsDir + psfFile)
# in our case, the y-axis is the z depth for the simulated microscopy
psf = np.moveaxis(psfOrig, 2, 1)
magPsf = sum(sum(sum(psf)))
for timestep in range(numberOfTimesteps):
print('Convolving interpolated image with PSF, timestep: ' + str(timestep))
convolved[timestep] = signal.convolve(nn_interp[timestep], psf, mode='same') # / magPsf
#convolved[timestep] = ndimage.convolve(nn_interp[timestep], psf, mode='constant') / magPsf
# -------------------------------------
# Select 2D slice and export
# CaCLEAN fields to a MatLab .mat file
# -------------------------------------
ryrCentersOrig = np.zeros((numRyrPerSarc*numSarc, 3))
zOffset = 1.0
for s in range(numSarc):
sarcRyr = np.loadtxt(ryrClusterCentersDir+'simPP'+str(s+1)+'.txt')
sarcRyr[:, 2] += zOffset
ryrCentersOrig[s*numRyrPerSarc:(s+1)*numRyrPerSarc, :] = sarcRyr
zOffset += 2.0
# x/y seems to be flipped in the ryrCenters file?
ryrCenters = np.zeros_like(ryrCentersOrig)
ryrCenters[:, 0] = ryrCentersOrig[:, 1]
ryrCenters[:, 1] = ryrCentersOrig[:, 0]
ryrCenters[:, 2] = ryrCentersOrig[:, 2]
print(ryrCenters)
# tolerances to check for clusters
tolerances = np.arange(detectRyrTolInc, detectRyrTolMax, detectRyrTolInc)
numTol = len(tolerances)
# Choose slices
multiSliceData = []
multiBgrData = []
multiMask = []
sliceList = list(np.arange(5, yLen-4, 2, dtype="int"))
numSlices = len(sliceList)
print('Checking for surface mask file...')
if not os.path.exists(inputsDir + surfaceMaskFile):
print('Downloading surface mask file to directory: ' + inputsDir)
util.download_file(surfaceMaskFile, inputsDir)
# Load outer surface mask
print('surface mask used: ' + inputsDir + surfaceMaskFile)
mesh = trimesh.load(inputsDir + surfaceMaskFile)
# For each slice, construct a list of RyRs with centers within
# a range of distance tolerances (admissible windows) and a
# mask file to indicate which pixels represent the intracellular space.
# Downsample the convolved data to match typical microscopy resolution
# (215 nm xy, 5 ms in time by default). Also create a background image
# set to the initial FCa conditions. Add light noise (SNR=100) to the
# simulated microscopy data and the background image.
multiRyrClusterCenters = np.full((numSlices, numTol, maxClustersPerSlice, 2), np.nan)
for s in range(numSlices):
ySlice = sliceList[s]
yLocation = y[ySlice]
numDetect = 0
ryrSliceCenters = []
for tol in range(numTol):
detectRyrTol = tolerances[tol]
centersTemp = ryrCenters[np.where(np.isclose(ryrCenters[:, 1], yLocation, atol=detectRyrTol))]
numDetect = len(centersTemp)
scaled = (np.delete(centersTemp, 1, axis = 1) / (regSpace*outputSpacingStep)
+ padding*outputSpacingStep + 1.) # pixel space conversions
multiRyrClusterCenters[s, tol,:numDetect] = scaled
# mask out the points outside of the mesh
print('checking if pixels in mesh...')
ySliceGrid = grid[np.where(np.isclose(grid[:, 1], yLocation, atol=detectRyrTolInc))]
mask = mesh.contains(ySliceGrid)
print('Calculating distance from triangulated surfaces')
(closest_points, distances, triangle_id) = mesh.nearest.on_surface(ySliceGrid)
maskOut = np.full((xLen, zLen), True, dtype=bool)
c = 0
for i in range(xLen):
for k in range(zLen):
if not mask[c]:
maskOut[i, k] = False
if distances[c] < boundaryTol:
maskOut[i, k] = False
c += 1
mask_out_slice = maskOut
# Downsample the convolved data in x, y, and t
convolvedReduced = convolved[:, 0:gridDimensions[0]:outputSpacingStep,
0:gridDimensions[1]:outputSpacingStep,
0:gridDimensions[2]:outputSpacingStep]
sliceData = np.moveaxis(np.squeeze(convolvedReduced[:, :, ySlice, :]), 0, 2)
# Add light noise to the slice data and a background image
noisySliceData = np.zeros_like(sliceData)
bgr = np.zeros_like(sliceData)
stdDev = np.mean(sliceData[:, :, 0]) / SNR
for timestep in range(numberOfTimesteps):
noise1 = np.random.normal(0, stdDev, [xLen, zLen])
noise2 = np.random.normal(0, stdDev, [xLen, zLen])
noisySliceData[:, :, timestep] = sliceData[:, :, timestep] + noise1
bgr[:, :, timestep] = sliceData[:, :, 0] + noise2
multiSliceData.append(noisySliceData)
multiBgrData.append(bgr)
multiMask.append(mask_out_slice)
xyt = [x[1]-x[0], z[1]-z[0], timeIncrement*outputFrequency]
outString = outputsDir + "simulatedMicroscopyResults_interp" + str(int(regSpace*1000)) + "_SNR" + str(int(SNR)) + '_' + spacingType + '_' + mitoModel + '_' + str(xLen) + 'x' + str(zLen) + 'x' + str(numberOfTimesteps)
outputFile = outString + '.mat'
print('Writing MatLab file: ' + outputFile)
scipy.io.savemat(outputFile, mdict={'MultiMask': multiMask,
'MultiRyrClusterCenters': multiRyrClusterCenters,
'RyrTolerances': tolerances,
'MultiBgr': multiBgrData,
'MultiIdenoised': multiSliceData,
'xyt_dim': xyt})
# Make outputs dir for TestCaCLEAN results (easier to do here than in Matlab)
try:
os.makedirs(testCaCLEANOutputsDir)
except OSError as e:
if e.errno != 17:
raise
# # timestep = 4
# # temp_nn_interp= naturalneighbor.griddata(nodeGeom, specData[timestep], grid_ranges)
# fig = plt.figure()
# ax = fig.add_subplot(111)
# #im = ax.imshow(temp_nn_interp[:,50,:])
# #im = ax.imshow(nn_interp[4,:,50,:])
# im = ax.imshow(multiSliceData[5][:,:,4])
# plt.colorbar(im)
# plt.show()
# plt.close(fig)