Vous avez reçu un message "Your GitLab account has been locked ..." ? Pas d'inquiétude : lisez cet article https://docs.gricad-pages.univ-grenoble-alpes.fr/help/unlock/

Commit 859e725e authored by Gustavo Pinzon's avatar Gustavo Pinzon
Browse files

New function spam.deformation.deformationField.mergeRegistrationAndDiscreteFields() with test

parent e9238d3e
Pipeline #52845 passed with stages
in 13 minutes and 28 seconds
......@@ -1031,7 +1031,7 @@ def getDisplacementFromNeighbours(labIm, DVC, fileName, method = 'getLabel', cen
Labelled volume, with lab.max() labels
DVC : dictionary
Dictionary with deformation field, obtained from `spam-ddic` script, and read using `spam.helpers.tsvio.readCorrelationTSV()`
Dictionary with deformation field, obtained from `spam-ddic` script, and read using `spam.helpers.tsvio.readCorrelationTSV()` with `readConvergence=True, readPSCC=True, readLabelDilate=True`
fileName : string
FileName including full path and .tsv at the end to write
......@@ -1051,15 +1051,11 @@ def getDisplacementFromNeighbours(labIm, DVC, fileName, method = 'getLabel', cen
This allows the to compute only the displacement increment from the neighbours, while using the F tensor from a previous (converged) step.
If `previousDVS = None`, then the resulting Phi would be composed only by the displacement of the neighbours.
Default = None
fileName : string
Output filename, if None return dictionary as from spam.helpers.readCorrelationTSV()
Default = None
Returns
--------
Dictionary
Output dictionary with the same columns as the input
TSV file with the same columns as the input
"""
# Compute centreOfMass if needed
......@@ -1140,22 +1136,81 @@ def getDisplacementFromNeighbours(labIm, DVC, fileName, method = 'getLabel', cen
PhiField[:, 2, 0], PhiField[:, 2, 1], PhiField[:, 2, 2],
PSCC, error, iterations, returnStatus, deltaPhiNorm, labelDilateList]).T
numpy.savetxt(fileName,
outMatrix,
fmt='%.7f',
delimiter='\t',
newline='\n',
comments='',
header="Label\tZpos\tYpos\tXpos\t" +
"Zdisp\tYdisp\tXdisp\t" +
"Fzz\tFzy\tFzx\t" +
"Fyz\tFyy\tFyx\t" +
"Fxz\tFxy\tFxx\t" +
"PSCC\terror\titerations\treturnStatus\tdeltaPhiNorm\tLabelDilate")
outMatrix,
fmt='%.7f',
delimiter='\t',
newline='\n',
comments='',
header="Label\tZpos\tYpos\tXpos\t" +
"Zdisp\tYdisp\tXdisp\t" +
"Fzz\tFzy\tFzx\t" +
"Fyz\tFyy\tFyx\t" +
"Fxz\tFxy\tFxx\t" +
"PSCC\terror\titerations\treturnStatus\tdeltaPhiNorm\tLabelDilate")
except:
print('spam.deformation.deformationField.getDisplacementFromNeighbours(): Missing information in the input TSV. Make sure you are reading iterations, returnStatus, deltaPhiNorm, PSCC, LabelDilate, and error.')
print('spam.deformation.deformationField.getDisplacementFromNeighbours(): Aborting')
def mergeRegistrationAndDiscreteFields(regTSV, discreteTSV, fileName):
"""
This function merges a registration TSV with a discrete TSV.
Can be used to create the first guess for `spam-ddic`, using the registration over the whole file, and a previous result from `spam-ddic`.
Parameters
-----------
regTSV : dictionary
Dictionary with deformation field, obtained from a registrion, usually from the whole sample, and read using `spam.helpers.tsvio.readCorrelationTSV()`
discreteTSV : dictionary
Dictionary with deformation field, obtained from `spam-ddic` script, and read using `spam.helpers.tsvio.readCorrelationTSV()`
fileName : string
FileName including full path and .tsv at the end to write
Returns
--------
Dictionary
TSV file with the same columns as the input
"""
# Create a first guess
phiGuess = discreteTSV['PhiField'].copy()
# Main loop
for lab in range(discreteTSV['numberOfLabels']):
# Initial position of a grain
iniPos = discreteTSV['fieldCoords'][lab]
# Position of the label at T+1
deformPos = iniPos + discreteTSV['PhiField'][lab][:-1,-1]
# Compute the extra displacement and rotation
extraDisp = spam.deformation.decomposePhi(regTSV['PhiField'][0],
PhiCentre = regTSV['fieldCoords'][0],
PhiPoint = deformPos)['t']
# Add the extra disp to the phi guess
phiGuess[lab][:-1,-1] += extraDisp
# Save
outMatrix = numpy.array([numpy.array(range(discreteTSV['numberOfLabels'])),
discreteTSV['fieldCoords'][:, 0],
discreteTSV['fieldCoords'][:, 1],
discreteTSV['fieldCoords'][:, 2],
phiGuess[:, 0, 3], phiGuess[:, 1, 3], phiGuess[:, 2, 3],
phiGuess[:, 0, 0], phiGuess[:, 0, 1], phiGuess[:, 0, 2],
phiGuess[:, 1, 0], phiGuess[:, 1, 1], phiGuess[:, 1, 2],
phiGuess[:, 2, 0], phiGuess[:, 2, 1], phiGuess[:, 2, 2],
numpy.zeros(((discreteTSV['numberOfLabels'])), dtype='<f4'),
discreteTSV['iterations'],
discreteTSV['returnStatus'],
discreteTSV['deltaPhiNorm']]).T
numpy.savetxt(fileName,
outMatrix,
fmt='%.7f',
delimiter='\t',
newline='\n',
comments='',
header="Label\tZpos\tYpos\tXpos\t" +
"Zdisp\tYdisp\tXdisp\t" +
"Fzz\tFzy\tFzx\t" +
"Fyz\tFyy\tFyx\t" +
"Fxz\tFxy\tFxx\t" + "PSCC\titerations\treturnStatus\tdeltaPhiNorm")
......@@ -25,12 +25,17 @@ class testAll(unittest.TestCase):
os.remove(testFolder+'Step0.tif')
os.remove(testFolder+'Lab0.tif')
os.remove(testFolder+'Step1.tif')
os.remove(testFolder+'Step2.tif')
os.remove(testFolder+'Step0-Step1-bin2-registration.tsv')
os.remove(testFolder+'Step1-Step2-bin2-registration.tsv')
os.remove(testFolder+'Step0-Step1.tsv')
os.remove(testFolder+'Step1-Step2.tsv')
os.remove(testFolder+'Step0-Step1-discreteDVC.tsv')
os.remove(testFolder+'Step0-Step1-discreteDVC.vtk')
os.remove(testFolder+'merged.tsv')
os.remove(testFolder+'TSV_getDisplacementFromNeighbours.tsv')
os.remove(testFolder+'TSV_mergeRegistrationAndDiscreteFields.tsv')
except OSError:
pass
......@@ -952,7 +957,7 @@ class testAll(unittest.TestCase):
tifffile.imsave(testFolder + "Lab0.tif", labIm0.astype(spam.label.labelType))
#test of rigid translation and rotation
#Create Phi and Apply (25 px displacement on Y-axis, and 5 degree rotation along Z axis)
#Create Phi and Apply (25 px displacement on Y-axis, and 0 degree rotation along Z axis)
translationStep1 = [5, 2, 0]
rotationStep1 = [0, 0, 0]
transformation = {'t': translationStep1,
......@@ -1040,6 +1045,148 @@ class testAll(unittest.TestCase):
self.assertAlmostEqual(meanT[2], 0, places=2)
# Check that the F matrix is equal to the initial
self.assertTrue((tsvRes['PhiField'][10][:-1, :-1] == TSV['PhiField'][10][:-1, :-1]).all())
def test_mergeRegistrationAndDiscreteFields(self):
#Create an initial Lab
#######################################################
### We're using the DDIC test from scripts here, lightly modified
#######################################################
#First we need to create some data using DEM dataset
pixelSize = 0.0001
blurSTD = 0.8
noiseSTD = 0.01
boxSizeDEM, centres, radii = spam.datasets.loadUniformDEMboxsizeCentreRadius()
# put 0 in the middle
centres -= numpy.mean(centres, axis=0)
rMax = numpy.amax(radii)
# pad box size
boxSizeDEM = boxSizeDEM + 5 * rMax
# add half box size to centres
centres += numpy.array(boxSizeDEM)/2.0
boxSizePx = (boxSizeDEM / pixelSize).astype(int)
centresPx = centres / pixelSize
radiiPx = radii / pixelSize
box = numpy.zeros(boxSizePx, dtype="<f8")
spam.kalisphera.makeSphere(box, centresPx, radiiPx)
box[numpy.where(box > 1.0)] = 1.0
box[numpy.where(box < 0.0)] = 0.0
box = box * 0.5
box = box + 0.25
box = scipy.ndimage.filters.gaussian_filter(box, sigma=blurSTD)
box = numpy.random.normal(box, scale=noiseSTD)
binIm0 = box >= 0.5
#Run watershed
labIm0 = spam.label.ITKwatershed.watershed(binIm0)
#Save images
tifffile.imsave(testFolder + "Step0.tif", box.astype('<f4'))
tifffile.imsave(testFolder + "Lab0.tif", labIm0.astype(spam.label.labelType))
# Create the first step
#Create Phi and Apply (25 px displacement on Y-axis, and 0 degree rotation along Z axis)
translationStep1 = [5, 2, 0]
rotationStep1 = [0, 0, 0]
transformation = {'t': translationStep1,
'r': rotationStep1}
Phi = spam.deformation.computePhi(transformation)
# transform centres around the centres of the box
centresPxDeformed = numpy.zeros_like(centresPx)
for i, centrePx in enumerate(centresPx):
centresPxDeformed[i] = centrePx + spam.deformation.decomposePhi(Phi, PhiPoint=centrePx, PhiCentre=numpy.array(boxSizePx)/2.0)['t']
boxDeformed = numpy.zeros(boxSizePx, dtype="<f8")
spam.kalisphera.makeSphere(boxDeformed, centresPxDeformed, radiiPx)
boxDeformed[numpy.where(boxDeformed > 1.0)] = 1.0
boxDeformed[numpy.where(boxDeformed < 0.0)] = 0.0
boxDeformed = boxDeformed * 0.5
boxDeformed = boxDeformed + 0.25
boxDeformed = scipy.ndimage.filters.gaussian_filter(boxDeformed, sigma=blurSTD)
boxDeformed = numpy.random.normal(boxDeformed, scale=noiseSTD)
#Save images
tifffile.imsave(testFolder + "Step1.tif", boxDeformed.astype('<f4'))
# Create the second step
#Create Phi and Apply (25 px displacement on Y-axis, and 5 degree rotation along Z axis)
translationStep2 = [10, 4, 0]
rotationStep2 = [0, 0, 0]
transformation = {'t': translationStep2,
'r': rotationStep2}
Phi = spam.deformation.computePhi(transformation)
# transform centres around the centres of the box
centresPxDeformed = numpy.zeros_like(centresPx)
for i, centrePx in enumerate(centresPx):
centresPxDeformed[i] = centrePx + spam.deformation.decomposePhi(Phi, PhiPoint=centrePx, PhiCentre=numpy.array(boxSizePx)/2.0)['t']
boxDeformed = numpy.zeros(boxSizePx, dtype="<f8")
spam.kalisphera.makeSphere(boxDeformed, centresPxDeformed, radiiPx)
boxDeformed[numpy.where(boxDeformed > 1.0)] = 1.0
boxDeformed[numpy.where(boxDeformed < 0.0)] = 0.0
boxDeformed = boxDeformed * 0.5
boxDeformed = boxDeformed + 0.25
boxDeformed = scipy.ndimage.filters.gaussian_filter(boxDeformed, sigma=blurSTD)
boxDeformed = numpy.random.normal(boxDeformed, scale=noiseSTD)
#Save images
tifffile.imsave(testFolder + "Step2.tif", boxDeformed.astype('<f4'))
# Create the TSV from macro reg between 0 and 1
exitCode = subprocess.call(["spam-ldic",
"-glt", "0.5",
"-hws", "10",
"-ns", "10",
"-reg", "-regbb", "2", "-regbe", "2",
"-tsv",
"-gpi", "5",
"Step0.tif", "Step1.tif",
"-od", testFolder+""])
self.assertEqual(exitCode, 0)
# Create the TSV from ddic between 0 and 1
#exitCode = subprocess.call(["spam-ddic",
#"-pf", "Step0-Step1-bin2-registration.tsv", "-pfb", "2",
#"-ld", "2",
#"Step0.tif", "Lab0.tif", "Step1.tif",
#"-od", testFolder+""])
#self.assertEqual(exitCode, 0)
# Create the TSV from macro reg between 1 and 2
exitCode = subprocess.call(["spam-ldic",
"-glt", "0.5",
"-hws", "10",
"-ns", "10",
"-reg", "-regbb", "2", "-regbe", "2",
"-tsv",
"-gpi", "5",
"Step1.tif", "Step2.tif",
"-od", testFolder+""])
self.assertEqual(exitCode, 0)
# Read ddic TSV
discreteTSV = spam.helpers.readCorrelationTSV('Step0-Step1-discreteDVC.tsv',
readConvergence=True,
readError=True,
readLabelDilate=True,
readPSCC=True)
# Read macro TSV
macroTSV = spam.helpers.readCorrelationTSV('Step1-Step2-bin2-registration.tsv',
fieldBinRatio=2)
# Run function
spam.deformation.deformationField.mergeRegistrationAndDiscreteFields(macroTSV, discreteTSV, 'TSV_mergeRegistrationAndDiscreteFields.tsv')
# Read the resulting TSV
tsvRes = spam.helpers.readCorrelationTSV('TSV_mergeRegistrationAndDiscreteFields.tsv')
# Check the results
for i in range(tsvRes['numberOfLabels']):
desp = spam.deformation.deformationFunction.decomposePhi(tsvRes['PhiField'][i])['t']
self.assertAlmostEqual(numpy.abs(desp[0] - 10), 0, places = 0)
self.assertAlmostEqual(numpy.abs(desp[1] - 4), 0, places = 0)
self.assertAlmostEqual(numpy.abs(desp[2]), 0, places = 0)
if __name__ == '__main__':
unittest.main()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment