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/

test_deformation.py 63.7 KB
Newer Older
1
2
3
4
5
6
# -*- coding: utf-8 -*-
from __future__ import print_function

import unittest
import numpy
import os
7
8
9
import scipy.ndimage
import tifffile
import subprocess
10

11
12
13
import spam.helpers
import spam.kalisphera
import spam.datasets
14
import spam.mesh
15
import spam.label
16
17
18
import spam.DIC
import spam.deformation

19
testFolder = './'
20
21
22
23

class testAll(unittest.TestCase):

    def tearDown(self):
24
25
26
27
        try:
            os.remove(testFolder+'Step0.tif')
            os.remove(testFolder+'Lab0.tif')
            os.remove(testFolder+'Step1.tif')
28
            os.remove(testFolder+'Step2.tif')
29
            os.remove(testFolder+'Step0-Step1-bin2-registration.tsv')
30
            os.remove(testFolder+'Step1-Step2-bin2-registration.tsv')
31
            os.remove(testFolder+'Step0-Step1.tsv')
32
            os.remove(testFolder+'Step1-Step2.tsv')
33
34
35
            os.remove(testFolder+'Step0-Step1-discreteDVC.tsv')
            os.remove(testFolder+'Step0-Step1-discreteDVC.vtk')
            os.remove(testFolder+'merged.tsv')
36
            os.remove(testFolder+'TSV_getDisplacementFromNeighbours.tsv')
37
38
            os.remove(testFolder+'TSV_mergeRegistrationAndDiscreteFields.tsv')
            
39
40
41
42

        except OSError:
            pass

43
44

    def test_computePhi(self):
45
46
47
48
49
        # U MUST be symmetric, make sure this is checked and sets off an assertion
        badU = numpy.eye(3)
        badU[2,1] = 5
        self.assertRaises(AssertionError, spam.deformation.computePhi, {'U': badU})

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
        trans1 = {'t': [0.0, 3.0, 3.0]}
        trans2 = {'r': [-5.0, 0.0, 0.0]}
        trans3 = {'z': [2, 2, 2]}
        trans4 = {'s': [0.9, 0.8, 0.7]}
        Phi1 = spam.deformation.computePhi(trans1)
        self.assertEqual(numpy.sum([Phi1[0, -1], Phi1[1, -1], Phi1[2, -1]]), 6)
        Phi2 = spam.deformation.computePhi(trans2)
        self.assertEqual(numpy.sum([Phi2[0, -1], Phi2[1, -1], Phi2[2, -1]]), 0)
        Phi3 = spam.deformation.computePhi(trans2, PhiCentre=[50.0, 50.0, 50.0], PhiPoint=[50.0, 16.0, 84.0])
        self.assertAlmostEqual(numpy.sum([Phi3[0, -1], Phi3[1, -1], Phi3[2, -1]]), 5.926, places=2)
        Phi4 = spam.deformation.computePhi(trans3)
        self.assertEqual([Phi4[0, 0], Phi4[1, 1], Phi4[2, 2]], [2., 2., 2.])
        Phi5 = spam.deformation.computePhi(trans4)
        self.assertEqual(Phi5[0, 1], Phi5[1, 0], 0.9)
        self.assertEqual(Phi5[0, 2], Phi5[2, 0], 0.8)
        self.assertEqual(Phi5[1, 3], Phi5[3, 1], 0.7)
Edward Andò's avatar
Edward Andò committed
66
67
68
69
70
71
        Phi6 = spam.deformation.computePhi({'U':numpy.eye(3)})
        self.assertEqual(Phi6.tolist(), numpy.eye(4).tolist())
        U = numpy.eye(3)
        U[0,0] = 0.8
        Phi7 = spam.deformation.computePhi({'U':U})
        self.assertEqual(Phi7[0,0], 0.8)
72
73
74
75


    def test_decomposePhi(self):
        # CASE 1: singular Phi
Edward Andò's avatar
Edward Andò committed
76
        Phi = numpy.zeros((4,4))
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
        self.assertEqual(numpy.isnan(spam.deformation.decomposePhi(Phi)["t"]).sum(), 3)
        self.assertEqual(numpy.isnan(spam.deformation.decomposePhi(Phi)["r"]).sum(), 3)

        # CASE 2: Phi contains nans
        Phin = numpy.eye(4)
        Phin[0, 3] = numpy.nan
        self.assertEqual(numpy.isnan(spam.deformation.decomposePhi(Phin)["t"]).sum(), 3)
        self.assertEqual(numpy.isnan(spam.deformation.decomposePhi(Phin)["r"]).sum(), 3)

        # CASE 3: Phi contains inf
        Phii = numpy.eye(4)
        Phii[0, 3] = numpy.inf
        self.assertEqual(numpy.isnan(spam.deformation.decomposePhi(Phii)["t"]).sum(), 3)
        self.assertEqual(numpy.isnan(spam.deformation.decomposePhi(Phii)["r"]).sum(), 3)

        # CASE 4: negative eigenvalues in transpose(Phi).Phi
        Phib = numpy.array([[0.25383295079467, -0.028793281703941, 0.05805266499330, 10.722113444672508],
                            [-0.03543852689277, 0.004282141971071, -0.008072359472034, 18.14869851125678],
                            [0.041196242920521, -0.004961945218488, 0.009385858417623, 17.144152186875889],
                            [0, 0, 0, 1]])
        self.assertAlmostEqual(spam.deformation.decomposePhi(Phib)["t"].tolist(), Phib[0:3, -1].tolist(), places=5)

        # CASE 5: error in inverting U to create the rotation matrix
        # it doesn't seem to pass the test on gricad...
        # Phib = numpy.array([[0.000000001, 0.000000001, 0.000000001, 1],
        # [0.000000001, 0.000000001, 0.000000001, 1],
        # [0.000000001, 0.0, 0.000000001, 1],
        # [0, 0, 0, 1]])
        # self.assertEqual(spam.deformation.decomposePhi(Phib)["t"], [0,0,0])

        # CASE 6: back calculation of transformation
        transIn = {'t': [4.6, 11.2, 0.3],
                   'r': [-5.0, 2.0, 8.0]}
        a = numpy.random.uniform(1, 100, 3)
        b = numpy.random.uniform(1, 100, 3)
        Phi = spam.deformation.computePhi(transIn, PhiCentre=a, PhiPoint=b)
        transBack = spam.deformation.decomposePhi(Phi, PhiCentre=b, PhiPoint=a)
        self.assertTrue(numpy.linalg.norm(numpy.subtract(transBack["t"], transIn["t"])) < 1e-5)
        self.assertTrue(numpy.linalg.norm(numpy.subtract(transBack["r"], transIn["r"])) < 1e-5)


    def test_Q8(self):
Olga Stamati's avatar
Q8 test  
Olga Stamati committed
119
        # case 0: 2D field with nans under large strains
120
121
122
123
124
125
126
127
        dispField0 = numpy.zeros((4, 3))
        dispField0[:, 1] = [20, 20, -20, numpy.nan]  # dipsY
        dispField0[:, 2] = [20, -20, 20, numpy.nan]  # dipsX

        F0 = spam.deformation.FfieldRegularQ8(dispField0.reshape(1, 2, 2, 3), nodeSpacing=[0, 100, 100])
        decomposedF = spam.deformation.decomposeF(F0)
        self.assertTrue(numpy.isnan((decomposedF['U']).sum()))  # return nan

Olga Stamati's avatar
Q8 test  
Olga Stamati committed
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
        ## case 0b: 2D field with nans under small strains
        self.assertTrue(numpy.isnan((decomposedF['e']).sum()))  # return nan

        # case 1: 2D field of 1 square with isotropic compression under large strains
        dispField1 = numpy.zeros((4, 3))
        dispField1[:, 1] = [20, 20, -20, -20]  # dipsY
        dispField1[:, 2] = [20, -20, 20, -20]  # dipsX

        Vo1 = 100 * 100  # initial volume
        Vf1 = 60 * 60  # final volume

        F1 = spam.deformation.FfieldRegularQ8(dispField1.reshape(1, 2, 2, 3), nodeSpacing=[0, 100, 100])
        decomposedF1 = spam.deformation.decomposeF(F1[0, 0, 0], twoD = True)

        self.assertAlmostEqual(decomposedF1["vol"], (Vf1 - Vo1) / float(Vo1), places=3)  # volStrain should be the volume change
        self.assertAlmostEqual(decomposedF1["dev"], 0, places=6)  # devStrain must be 0

        # case 1b: 2D field of 1 rectangle with isotropic compression under small strains
        dispField1b = numpy.zeros((4, 3))
        dispField1b[:, 1] = [1, 1, -1, -1]  # dipsY
        dispField1b[:, 2] = [1, -1, 1, -1]  # dipsX

        Vo1b = 100 * 100  # initial volume
        Vf1b = 98 * 98  # final volume

        F1b = spam.deformation.FfieldRegularQ8(dispField1b.reshape(1, 2, 2, 3), nodeSpacing=[0, 100, 100])
        decomposedF1b = spam.deformation.decomposeF(F1b[0, 0, 0], twoD = True)

        self.assertAlmostEqual(decomposedF1b["volss"], (Vf1b - Vo1b) / float(Vo1b), places=3)  # volStrain should be the volume change
        self.assertEqual(decomposedF1b["devss"], 0)  # devStrain must be 0

        # case 2: 3D field of 1 cell (2x2x2nodes) with isotropic compression under large strains
        dispField2 = numpy.zeros((8, 3))
        dispField2[:, 0] = [20, 20, 20, 20, -20, -20, -20, -20]  # dipsZ
        dispField2[:, 1] = [20, 20, -20, -20, 20, 20, -20, -20]  # dipsY
        dispField2[:, 2] = [20, -20, 20, -20, 20, -20, 20, -20]  # dipsX

        Vo2 = 100 * 100 * 100  # initial volume
        Vf2 = 60 * 60 * 60  # final volume

        F2 = spam.deformation.FfieldRegularQ8(dispField2.reshape(2, 2, 2, 3), nodeSpacing=[100, 100, 100])
        decomposedF2 = spam.deformation.decomposeF(F2[0, 0, 0])
        self.assertAlmostEqual(decomposedF2["vol"], (Vf2 - Vo2) / float(Vo2), places=3)  # volStrain should be the volume change
        self.assertAlmostEqual(decomposedF2["dev"], 0, places=6)  # devStrain must be 0

        # case 2b: 3D field of 1 cell (2x2x2nodes) with isotropic compression under small strains
        dispField2b = numpy.zeros((8, 3))
        dispField2b[:, 0] = [1, 1, 1, 1, -1, -1, -1, -1]  # dipsZ
        dispField2b[:, 1] = [1, 1, -1, -1, 1, 1, -1, -1]  # dipsY
        dispField2b[:, 2] = [1, -1, 1, -1, 1, -1, 1, -1]  # dipsX

        Vo2b = 100 * 100 * 100  # initial volume
        Vf2b = 98 * 98 * 98  # final volume

        F2b = spam.deformation.FfieldRegularQ8(dispField2b.reshape(2, 2, 2, 3), nodeSpacing=[100, 100, 100])
        decomposedF2b = spam.deformation.decomposeF(F2b[0, 0, 0])
        self.assertAlmostEqual(decomposedF2b["volss"], (Vf2b - Vo2b) / float(Vo2b), places=2)
        self.assertEqual(decomposedF2b["devss"], 0)

        # case 3: 2D field of 1 rectangle with shear under large strains
        dispField3 = numpy.zeros((4, 3))
        dispField3[:, 2] = [0, 0, 20, 20]  # dipsX

        F3 = spam.deformation.FfieldRegularQ8(dispField3.reshape(1, 2, 2, 3), nodeSpacing=[0, 100, 100])
        decomposedF3 = spam.deformation.decomposeF(F3[0, 0, 0], twoD = True)
        self.assertEqual(decomposedF3["vol"], 0)  # volStrain must be 0
        self.assertAlmostEqual(decomposedF3["U"][1, 2], decomposedF3["U"][2, 1], places=4)  # diag strain matrix
        self.assertAlmostEqual(abs(decomposedF3["U"][1, 2] - ((20 / 100.0) * 0.5)), 0, places=3)

        # case 3b: 2D field of 1 rectangle with shear under small strains
        dispField3b = numpy.zeros((4, 3))
        dispField3b[:, 2] = [0, 0, 2, 2]  # dipsX

        F3b = spam.deformation.FfieldRegularQ8(dispField3b.reshape(1, 2, 2, 3), nodeSpacing=[0, 100, 100])
        decomposedF3b = spam.deformation.decomposeF(F3b[0, 0, 0], twoD = True)
        self.assertEqual(decomposedF3b["volss"], 0)  # volStrain must be 0
        self.assertEqual(decomposedF3b["e"][1, 2], decomposedF3b["e"][2, 1])  # diag strain matrix
        self.assertEqual(decomposedF3b["e"][1, 2], (2 / 100.0) * 0.5)

        # case 4: 3D field with shear under large strains
        dispField4 = numpy.zeros((8, 3))
        dispField4[:, 2] = [0, 0, 20, 20, 0, 0, 20, 20]  # dipsX

        F4 = spam.deformation.FfieldRegularQ8(dispField4.reshape(2, 2, 2, 3), nodeSpacing=[100, 100, 100])
        decomposedF4 = spam.deformation.decomposeF(F4[0, 0, 0])
        self.assertEqual(decomposedF4["vol"], 0)  # volStrain must be 0
        self.assertAlmostEqual(decomposedF4["U"][1, 2], decomposedF4["U"][2, 1], places=4)  # diag strain matrix
        self.assertAlmostEqual(abs(decomposedF4["U"][1, 2] - (20 / 100.0) * 0.5), 0, places=3)

        # case 4b: 3D field with shear under small strains
        dispField4b = numpy.zeros((8, 3))
        dispField4b[:, 2] = [0, 0, 2, 2, 0, 0, 2, 2]  # dipsX

        F4b = spam.deformation.FfieldRegularQ8(dispField4b.reshape(2, 2, 2, 3), nodeSpacing=[100, 100, 100])
        decomposedF4b = spam.deformation.decomposeF(F4b[0, 0, 0])
        self.assertEqual(decomposedF4b["volss"], 0)  # volStrain must be 0
        self.assertEqual(decomposedF4b["e"][1, 2], decomposedF4b["e"][2, 1])  # diag strain matrix
        self.assertEqual(decomposedF4b["e"][1, 2], (2 / 100.0) * 0.5)

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
        #nodeSpacing = [150,150,150]
        nodeSpacing = [200,200,200]
        imSize = [2000,1000,1000]
        # Random points
        pointsRef, dims = spam.DIC.grid.makeGrid(imSize, nodeSpacing=nodeSpacing)

        #######################################################
        # Dilation of points for grain strain calc
        #######################################################
        # Test with 1% dilation
        dilation = 1.01

        # make sure average volumetric strain is the same as the projected one
        pointsDef = pointsRef * dilation
        displacements = (pointsDef - pointsRef).reshape(dims[0], dims[1], dims[2], 3)
        Ffield = spam.deformation.FfieldRegularQ8(displacements, nodeSpacing)

        ev = spam.deformation.decomposeFfield(Ffield, ["vol"])["vol"]
        # print("\tU trace mean new:",numpy.array(U)[:,[0,1,2],[0,1,2]].mean())
        # print("\tev",numpy.array(ev))
        # print("\tev",numpy.array(ev).mean())

        self.assertAlmostEqual(ev.mean(), 3. * (dilation - 1), places=3)
        #self.assertAlmostEqual(ev.mean(), 3. * (dilation - 1), places=3)


        ########################################################
        ## Z-stretch of points for strain calc
        ########################################################
        zStretch = 1.02
        print("\n\nSpreading points in Z by by 1.2")
        # Deform the points by spreading them apart -- this is dilating so positive volumetric strain
        displacements = (pointsRef * [zStretch, 1.0, 1.0] - pointsRef).reshape(dims[0], dims[1], dims[2], 3)
        Ffield = spam.deformation.FfieldRegularQ8(displacements, nodeSpacing)
        # only compute on internal nodes, we know there's a problem at the edges
        self.assertAlmostEqual(Ffield[1:-1,1:-1,1:-1,0,0].mean(), zStretch, places=3)
        self.assertAlmostEqual(Ffield[1:-1,1:-1,1:-1,1,1].mean(), 1.0, places=3)
        self.assertAlmostEqual(Ffield[1:-1,1:-1,1:-1,2,2].mean(), 1.0, places=3)


        ########################################################
        ## Y-stretch of points for strain calc
        ########################################################
        yStretch = 1.02
        print("\n\nSpreading points in Y by by 1.2")
        # Deform the points by spreading them apart -- this is dilating so positive volumetric strain
        displacements = (pointsRef * [1.0, yStretch, 1.0] - pointsRef).reshape(dims[0], dims[1], dims[2], 3)
        Ffield = spam.deformation.FfieldRegularQ8(displacements, nodeSpacing)
        # only compute on internal nodes, we know there's a problem at the edges
        self.assertAlmostEqual(Ffield[1:-1,1:-1,1:-1,0,0].mean(), 1.0, places=3)
        self.assertAlmostEqual(Ffield[1:-1,1:-1,1:-1,1,1].mean(), yStretch, places=3)
        self.assertAlmostEqual(Ffield[1:-1,1:-1,1:-1,2,2].mean(), 1.0, places=3)



        #######################################################
        # Rotation of points for grain strain calc
        #######################################################
        pointsRotated = pointsRef.copy()
        rotAngle = 3.0
        for n, point in enumerate(pointsRef):
            Phi = spam.deformation.computePhi({'r': [rotAngle, 0.0, 0.0]},
                                              PhiCentre = numpy.array(((numpy.array(imSize)-1)/2)-1),
                                              PhiPoint  = point)
            pointsRotated[n] += Phi[0:3, -1]
            # print( point, pointsRotated[n], '\n\n' )

        displacements = (pointsRotated - pointsRef).reshape(dims[0], dims[1], dims[2], 3)
        Ffield = spam.deformation.FfieldRegularQ8(displacements, nodeSpacing)

        # Compute strains
        decomposedF = spam.deformation.decomposeFfield(Ffield, ["r", "vol", "dev"])

        self.assertAlmostEqual(decomposedF['r'][1:-1,1:-1,1:-1, 0].mean(), rotAngle, places=3)
        self.assertAlmostEqual(decomposedF['r'][1:-1,1:-1,1:-1, 1].mean(), 0.0, places=3)
        self.assertAlmostEqual(decomposedF['r'][1:-1,1:-1,1:-1, 2].mean(), 0.0, places=3)
        self.assertAlmostEqual(decomposedF['vol'][1:-1,1:-1,1:-1].mean(), 0, places=3)
        self.assertAlmostEqual(decomposedF['dev'][1:-1,1:-1,1:-1].mean(), 0, places=3)



        #######################################################
        # Shear of points for grain strain calc:
        #   N.B.: this is a shear which results in a SYMMETRIC F
        #######################################################
        pointsRotated = pointsRef.copy()
        shearVal = 0.1
        for n, point in enumerate(pointsRef):
            Phi = spam.deformation.computePhi({'s': [shearVal, 0.0, 0.0]},
                                              PhiCentre = numpy.array(((numpy.array(imSize)-1)/2)-1),
                                              PhiPoint  = point)
            pointsRotated[n] += Phi[0:3, -1]
            # print( point, pointsRotated[n], '\n\n' )

        displacements = (pointsRotated - pointsRef).reshape(dims[0], dims[1], dims[2], 3)
        Ffield = spam.deformation.FfieldRegularQ8(displacements, nodeSpacing)

        # Compute strains
        decomposedF = spam.deformation.decomposeFfield(Ffield, ["U"])


        UmeanWithoutBoundaries = numpy.mean(decomposedF['U'][1:-1,1:-1,1:-1], axis=(0, 1, 2))
        for i in range(3):
            for j in range(i,3):
                self.assertAlmostEqual(UmeanWithoutBoundaries[i,j], UmeanWithoutBoundaries[j,i], places=3)


        #######################################################
        # Homogeneous shrinking together
        #######################################################
        shrink = 0.99
        # Deform the points by pushing them closer together -- this is compressing so  negative volumetric strain
        displacements = (pointsRef * shrink - pointsRef).reshape(dims[0], dims[1], dims[2], 3)
        Ffield        = spam.deformation.FfieldRegularQ8(displacements, nodeSpacing)
        decomposedF   = spam.deformation.decomposeFfield(Ffield, ["vol"])
        self.assertAlmostEqual(decomposedF['vol'][1:-1,1:-1,1:-1].mean(), 3. * (shrink - 1.), places=3)

        ### while we're at it, the brute force distance too, why not here
        Ffield       = spam.deformation.FfieldRegularQ8(displacements, nodeSpacing)
        decomposedF  = spam.deformation.decomposeFfield(Ffield, ["vol"])
        self.assertAlmostEqual(decomposedF['vol'][1:-1,1:-1,1:-1].mean(), 3. * (shrink - 1.), places=3)


Edward Andò's avatar
Edward Andò committed
350
    def test_geers(self):
351
352
353
354
355
356
        nodeSpacing = [200, 200, 200]
        imSize      = [2000, 1000, 1000]
        # 2D
        nodeSpacing2D = [1, 100, 100]
        imSize2D      = [1, 1000, 1000]

Edward Andò's avatar
Edward Andò committed
357
        # Random points
358
359
        pointsRef, dims     = spam.DIC.makeGrid(imSize, nodeSpacing=nodeSpacing)
        pointsRef2D, dims2D = spam.DIC.makeGrid(imSize2D, nodeSpacing=nodeSpacing2D)
Edward Andò's avatar
Edward Andò committed
360

361
        ########################################################
Edward Andò's avatar
Edward Andò committed
362
363
364
365
366
367
        # Dilation of points for grain strain calc
        #######################################################
        # Test with 1% dilation
        dilation = 1.01

        # make sure average volumetric strain is the same as the projected one
368
369
370
371
372
        pointsDef   = pointsRef * dilation
        pointsDef2D = pointsRef2D * dilation
        displacements     = (pointsDef - pointsRef).reshape(dims[0], dims[1], dims[2], 3)
        displacements2D   = (pointsDef2D - pointsRef2D).reshape(dims2D[0], dims2D[1], dims2D[2], 3)

Edward Andò's avatar
Edward Andò committed
373
        Ffield = spam.deformation.FfieldRegularGeers(displacements, nodeSpacing)
374
        Ffield2D = spam.deformation.FfieldRegularGeers(displacements2D, nodeSpacing2D)
Edward Andò's avatar
Edward Andò committed
375

376
377
        ev   = spam.deformation.decomposeFfield(Ffield, ["vol"])["vol"]
        ev2D = spam.deformation.decomposeFfield(Ffield2D, ["vol"])["vol"]
Edward Andò's avatar
Edward Andò committed
378
379

        self.assertAlmostEqual(ev.mean(), 3. * (dilation - 1), places=3)
380
        self.assertAlmostEqual(ev2D.mean(), 2. * (dilation - 1), places=3)
Edward Andò's avatar
Edward Andò committed
381

382
383
384
        #########################################################
        ### Z-stretch of points for strain calc
        #########################################################
Edward Andò's avatar
Edward Andò committed
385
        zStretch = 1.02
386

Edward Andò's avatar
Edward Andò committed
387
        # Deform the points by spreading them apart -- this is dilating so positive volumetric strain
388
389
390
        displacements   = (pointsRef * [zStretch, 1.0, 1.0] - pointsRef).reshape(dims[0], dims[1], dims[2], 3)
        Ffield   = spam.deformation.FfieldRegularGeers(displacements, nodeSpacing)

Edward Andò's avatar
Edward Andò committed
391
392
        # only compute on internal nodes, we know there's a problem at the edges
        self.assertAlmostEqual(Ffield[1:-1,1:-1,1:-1,0,0].mean(), zStretch, places=3)
393
394
395
396
397
398
399
        self.assertAlmostEqual(Ffield[1:-1,1:-1,1:-1,1,1].mean(), 1.0, places=3)
        self.assertAlmostEqual(Ffield[1:-1,1:-1,1:-1,2,2].mean(), 1.0, places=3)

        ########################################################
        ## Y-stretch of points for strain calc
        ########################################################
        yStretch = 1.02
400

401
402
        # Deform the points by spreading them apart -- this is dilating so positive volumetric strain
        displacements = (pointsRef * [1.0, yStretch, 1.0] - pointsRef).reshape(dims[0], dims[1], dims[2], 3)
403
404
405
406
        displacements2D = (pointsRef2D * [1.0, yStretch, 1.0] - pointsRef2D).reshape(dims2D[0], dims2D[1], dims2D[2], 3)
        Ffield   = spam.deformation.FfieldRegularGeers(displacements, nodeSpacing)
        Ffield2D = spam.deformation.FfieldRegularGeers(displacements2D, nodeSpacing2D)

407
408
409
410
        # only compute on internal nodes, we know there's a problem at the edges
        self.assertAlmostEqual(Ffield[1:-1,1:-1,1:-1,0,0].mean(), 1.0, places=3)
        self.assertAlmostEqual(Ffield[1:-1,1:-1,1:-1,1,1].mean(), yStretch, places=3)
        self.assertAlmostEqual(Ffield[1:-1,1:-1,1:-1,2,2].mean(), 1.0, places=3)
411
412
        self.assertAlmostEqual(Ffield2D[:,1:-1,1:-1,1,1].mean(), yStretch, places=3)
        self.assertAlmostEqual(Ffield2D[:,1:-1,1:-1,2,2].mean(), 1.0, places=3)
Edward Andò's avatar
Edward Andò committed
413

414
415
416
417
418
        ########################################################
        ## Rotation of points for grain strain calc
        ########################################################
        pointsRotated   = pointsRef.copy()
        pointsRotated2D = pointsRef2D.copy()
Edward Andò's avatar
Edward Andò committed
419
420
421
        rotAngle = 3.0
        for n, point in enumerate(pointsRef):
            Phi = spam.deformation.computePhi({'r': [rotAngle, 0.0, 0.0]},
422
423
                                              PhiCentre = numpy.array(((numpy.array(imSize)-1)/2)-1),
                                              PhiPoint  = point)
Edward Andò's avatar
Edward Andò committed
424
425
426
            pointsRotated[n] += Phi[0:3, -1]
            # print( point, pointsRotated[n], '\n\n' )

427
428
429
430
431
432
433
434
435
436
437
        for n, point in enumerate(pointsRef2D):
            Phi = spam.deformation.computePhi({'r': [rotAngle, 0.0, 0.0]},
                                              PhiCentre = numpy.array(((numpy.array(imSize2D)-1)/2)-1),
                                              PhiPoint  = point)
            pointsRotated2D[n] += Phi[0:3, -1]
            # print( point, pointsRotated[n], '\n\n' )

        displacements   = (pointsRotated - pointsRef).reshape(dims[0], dims[1], dims[2], 3)
        displacements2D = (pointsRotated2D - pointsRef2D).reshape(dims2D[0], dims2D[1], dims2D[2], 3)
        Ffield   = spam.deformation.FfieldRegularGeers(displacements, nodeSpacing)
        Ffield2D = spam.deformation.FfieldRegularGeers(displacements2D, nodeSpacing2D)
Edward Andò's avatar
Edward Andò committed
438
439

        # Compute strains
440
441
        decomposedF   = spam.deformation.decomposeFfield(Ffield, ["r", "vol", "dev"])
        decomposedF2D = spam.deformation.decomposeFfield(Ffield2D, ["r", "vol", "dev"])
Edward Andò's avatar
Edward Andò committed
442

443
        self.assertAlmostEqual(decomposedF['r'][1:-1,1:-1,1:-1, 0].mean(), rotAngle, places=3)
Edward Andò's avatar
Edward Andò committed
444
445
446
447
        self.assertAlmostEqual(decomposedF['r'][1:-1,1:-1,1:-1, 1].mean(), 0.0, places=3)
        self.assertAlmostEqual(decomposedF['r'][1:-1,1:-1,1:-1, 2].mean(), 0.0, places=3)
        self.assertAlmostEqual(decomposedF['vol'][1:-1,1:-1,1:-1].mean(), 0, places=3)
        self.assertAlmostEqual(decomposedF['dev'][1:-1,1:-1,1:-1].mean(), 0, places=3)
448
449
450
451
452
        self.assertAlmostEqual(decomposedF2D['r'][:,1:-1,1:-1, 0].mean(), rotAngle, places=3)
        self.assertAlmostEqual(decomposedF2D['r'][:,1:-1,1:-1, 1].mean(), 0.0, places=3)
        self.assertAlmostEqual(decomposedF2D['r'][:,1:-1,1:-1, 2].mean(), 0.0, places=3)
        self.assertAlmostEqual(decomposedF2D['vol'][:,1:-1,1:-1].mean(), 0, places=3)
        self.assertAlmostEqual(decomposedF2D['dev'][:,1:-1,1:-1].mean(), 0, places=3)
Edward Andò's avatar
Edward Andò committed
453

454
455
456
457
458
        ########################################################
        ## Shear of points for grain strain calc:
        ##   N.B.: this is a shear which results in a SYMMETRIC F
        ########################################################
        pointsSheared = pointsRef.copy()
459
460
461
462
463
        shearVal = 0.1
        for n, point in enumerate(pointsRef):
            Phi = spam.deformation.computePhi({'s': [shearVal, 0.0, 0.0]},
                                              PhiCentre = numpy.array(((numpy.array(imSize)-1)/2)-1),
                                              PhiPoint  = point)
464
            pointsSheared[n] += Phi[0:3, -1]
465

466
467
468
469
470
471
472
473
474
475
476
477
        pointsSheared2D = pointsRef2D.copy()
        for n, point in enumerate(pointsRef2D):
            Phi = spam.deformation.computePhi({'s': [0.0, 0.0, shearVal]},
                                              PhiCentre = numpy.array(((numpy.array(imSize2D)-1)/2)-1),
                                              PhiPoint  = point)
            pointsSheared2D[n] += Phi[0:3, -1]

        displacements   = (pointsSheared - pointsRef).reshape(dims[0], dims[1], dims[2], 3)
        displacements2D = (pointsSheared2D - pointsRef2D).reshape(dims2D[0], dims2D[1], dims2D[2], 3)

        Ffield   = spam.deformation.FfieldRegularGeers(displacements, nodeSpacing)
        Ffield2D = spam.deformation.FfieldRegularGeers(displacements2D, nodeSpacing2D)
478
479

        # Compute strains
480
481
        decomposedF   = spam.deformation.decomposeFfield(Ffield, ["U"])
        decomposedF2D = spam.deformation.decomposeFfield(Ffield2D, ["U"])
482

483
484
        UmeanWithoutBoundaries   = numpy.mean(decomposedF['U'][1:-1,1:-1,1:-1], axis=(0, 1, 2))
        UmeanWithoutBoundaries2D = numpy.mean(decomposedF2D['U'][0,1:-1,1:-1], axis=(0, 1))
485
486
487
488

        for i in range(3):
            for j in range(i,3):
                self.assertAlmostEqual(UmeanWithoutBoundaries[i,j], UmeanWithoutBoundaries[j,i], places=3)
489
        self.assertAlmostEqual(UmeanWithoutBoundaries[0,1], shearVal, places=3)
490

491
492
493
494
        for i in range(3):
            for j in range(i,3):
                self.assertAlmostEqual(UmeanWithoutBoundaries2D[i,j], UmeanWithoutBoundaries2D[j,i], places=3)
        self.assertAlmostEqual(UmeanWithoutBoundaries2D[2,1], shearVal, places=3)
495

496
497
498
        ########################################################
        ## Homogeneous shrinking together
        ########################################################
Edward Andò's avatar
Edward Andò committed
499
500
501
        shrink = 0.99
        # Deform the points by pushing them closer together -- this is compressing so  negative volumetric strain
        displacements = (pointsRef * shrink - pointsRef).reshape(dims[0], dims[1], dims[2], 3)
502
503
        Ffield        = spam.deformation.FfieldRegularGeers(displacements, nodeSpacing)
        decomposedF   = spam.deformation.decomposeFfield(Ffield, ["vol"])
Edward Andò's avatar
Edward Andò committed
504
505
506
        self.assertAlmostEqual(decomposedF['vol'][1:-1,1:-1,1:-1].mean(), 3. * (shrink - 1.), places=3)

        ### while we're at it, the brute force distance too, why not here
507
508
        Ffield       = spam.deformation.FfieldRegularGeers(displacements, nodeSpacing, bruteForceDistance=True)
        decomposedF  = spam.deformation.decomposeFfield(Ffield, ["vol"])
Edward Andò's avatar
Edward Andò committed
509
510
        self.assertAlmostEqual(decomposedF['vol'][1:-1,1:-1,1:-1].mean(), 3. * (shrink - 1.), places=3)

511
512
513
        ########################################################
        ## Increasing neighbourhood radius should decrease noise
        ########################################################
Edward Andò's avatar
Edward Andò committed
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
        #Add noise to displacements
        displacementAmplitude = displacements.max()-displacements.min()
        displacements += numpy.random.random(displacements.shape)*0.1*displacementAmplitude
        FfieldR1 = spam.deformation.FfieldRegularGeers(displacements, nodeSpacing, neighbourRadius=1)
        decomposedFR1 = spam.deformation.decomposeFfield(FfieldR1, ["vol"])

        FfieldR1p5 = spam.deformation.FfieldRegularGeers(displacements, nodeSpacing, neighbourRadius=1.5)
        decomposedFR1p5 = spam.deformation.decomposeFfield(FfieldR1p5, ["vol"])

        FfieldR2 = spam.deformation.FfieldRegularGeers(displacements, nodeSpacing, neighbourRadius=2)
        decomposedFR2 = spam.deformation.decomposeFfield(FfieldR2, ["vol"])

        #FfieldR3 = spam.deformation.FfieldRegularGeers(displacements, nodeSpacing, neighbourRadius=3)
        #decomposedFR3 = spam.deformation.decomposeFfield(FfieldR3, ["vol"])
        std1   = decomposedFR1[  'vol'][1:-1,1:-1,1:-1].std()
        std1p5 = decomposedFR1p5['vol'][1:-1,1:-1,1:-1].std()
        std2   = decomposedFR2[  'vol'][1:-1,1:-1,1:-1].std()
        #compute stdev of vol strain (most sensitive!!) and try for three different neighbourhoodRadii
        self.assertEqual(std1 > std1p5, True)
        self.assertEqual(std1p5 > std2, True)

535
536
537
538
        ########################################################
        ## Application of mask
        ########################################################
        xStretch = 1.02
Edward Andò's avatar
Edward Andò committed
539
        # Deform the points by spreading them apart -- this is dilating so positive volumetric strain
540
541
        displacements   = (pointsRef * [1.0, 1.0, xStretch] - pointsRef).reshape(dims[0], dims[1], dims[2], 3)
        displacements2D = (pointsRef2D * [1.0, 1.0, xStretch] - pointsRef2D).reshape(dims2D[0], dims2D[1], dims2D[2], 3)
Edward Andò's avatar
Edward Andò committed
542
543
544

        # manually add a NaN in the middle of the displacement field
        displacements[dims[0]//2, dims[1]//2, dims[2]//2] = [numpy.nan, numpy.nan, numpy.nan]
545
        displacements2D[0, dims2D[1]//2, dims2D[2]//2] = [numpy.nan, numpy.nan, numpy.nan]
Edward Andò's avatar
Edward Andò committed
546

547
548
        Ffield   = spam.deformation.FfieldRegularGeers(displacements, nodeSpacing)
        Ffield2D = spam.deformation.FfieldRegularGeers(displacements2D, nodeSpacing2D)
Edward Andò's avatar
Edward Andò committed
549
        # only compute on internal nodes, we know there's a problem at the edges
550
551
        self.assertEqual(numpy.isnan(Ffield[:,:,:,2,2]).sum(), 1)
        self.assertEqual(numpy.isnan(Ffield2D[:,:,:,2,2]).sum(), 1)
Edward Andò's avatar
Edward Andò committed
552

553
554
555
556
        Ffield   = spam.deformation.FfieldRegularGeers(displacements, nodeSpacing, mask=True)
        Ffield2D = spam.deformation.FfieldRegularGeers(displacements2D, nodeSpacing2D, mask=True)
        self.assertEqual(numpy.isnan(Ffield[:,:,:,2,2]).sum(), 1)
        self.assertEqual(numpy.isnan(Ffield2D[:,:,:,2,2]).sum(), 1)
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
    def test_bagiStrain(self):
        #######################################################
        # Check triangulation and strains
        #######################################################
        # New example with larger distance
        # pointsRef = numpy.array([[  0,   0,   0],
        # [100,   0,   0],
        # [  0, 100,   0],
        # [100, 100,   0],
        # [  0,   0, 100],
        # [100,   0, 100],
        # [  0, 100, 100],
        # [100, 100, 100]], dtype='<f4')

        #######################################################
        # Check connectivityFromVoronoi
        #######################################################
        ## Check alpha functionality
        numpy.random.seed(1)
        pointsRef = numpy.random.randint(-20, 20, (20, 3)).astype('<f4')
        connectivity = spam.mesh.triangulate(pointsRef,alpha=-1)

        self.assertTrue(connectivity.shape[0] == 19)
        self.assertEqual(connectivity.shape[1], 4)

        # Random points
        pointsRef = numpy.random.randint(-20, 20, (20, 3)).astype('<f4')

        # Our C++ CGAL function without weights
        connectivity = spam.mesh.triangulate(pointsRef)

        # Make sure it's broken with weights of different sizes
        with self.assertRaises(Exception) as context:
            spam.mesh.triangulate(pointsRef, weights=numpy.array([2,2]))
        self.assertTrue("weights array dim1 != points array dim1" in str(context.exception))

        # Check size of connectivity
        self.assertTrue(connectivity.shape[0] >= 6)
        self.assertEqual(connectivity.shape[1], 4)


        #######################################################
        # Dilation of points for grain strain calc
        #######################################################
        # Test with 1% dilation
        dilation = 1.01

        # make sure average volumetric strain is the same as the projected one
        pointsDef = pointsRef * dilation
        tetVolumesRef = spam.mesh.tetVolumes(pointsRef, connectivity)
        tetVolumesDef = spam.mesh.tetVolumes(pointsDef, connectivity)
        # print("volStrains@tet:", (tetVolumesDef-tetVolumesRef)/tetVolumesRef)
        self.assertAlmostEqual(numpy.mean((tetVolumesDef - tetVolumesRef) / tetVolumesRef), 3. * (dilation - 1), places=3)
        ####
        # Check spam.deformation.FfieldBagi
        ###
        # Deform the points by spreading them apart -- this is dilating so positive volumetric strain
        # U, ev, ed = spam.deformation.FfieldBagi(points, connectivity, points - points)
        Ffield = spam.deformation.FfieldBagi(pointsRef, connectivity, pointsDef - pointsRef)
Edward Andò's avatar
Edward Andò committed
617
618

        ev = spam.deformation.decomposeFfield(Ffield, ["vol"])["vol"]
619
620
621
622
623
        # print("\tU trace mean new:",numpy.array(U)[:,[0,1,2],[0,1,2]].mean())
        # print("\tev",numpy.array(ev))
        # print("\tev",numpy.array(ev).mean())

        self.assertAlmostEqual(ev.mean(), 3. * (dilation - 1), places=3)
Edward Andò's avatar
Edward Andò committed
624
        #print(spam.deformation.decomposeFfield(Ffield, ['vol']))
625
626
627
628
629
630
        #self.assertAlmostEqual(ev.mean(), 3. * (dilation - 1), places=3)


        ########################################################
        ## Z-stretch of points for grain strain calc
        ########################################################
Edward Andò's avatar
Edward Andò committed
631
632
633
634
635
        zStretch = 1.02
        print("\n\nSpreading points in Z by by 1.2")
        # Deform the points by spreading them apart -- this is dilating so positive volumetric strain
        Ffield = spam.deformation.FfieldBagi(pointsRef, connectivity, pointsRef * [zStretch, 1.0, 1.0] - pointsRef)
        self.assertAlmostEqual(Ffield[:,0,0].mean(), zStretch, places=3)
636

Edward Andò's avatar
Edward Andò committed
637
638
639
640
641
        # Make sure that a single NaN does not pollute strains and is safely ignored
        pointsRefOneBadPoint = pointsRef.copy()
        badPointCoord = pointsRef.shape[0]//2
        pointsRefOneBadPoint[badPointCoord] = numpy.nan
        Ffield = spam.deformation.FfieldBagi(pointsRefOneBadPoint, connectivity, pointsRef * [zStretch, 1.0, 1.0] - pointsRef)
Edward Andò's avatar
Edward Andò committed
642
        # make sure that the nans in the strain are where there is our bad particle
Edward Andò's avatar
Edward Andò committed
643
        self.assertEqual(list(numpy.isnan(Ffield[:,0,0])), list(numpy.sum(connectivity==badPointCoord, axis=1)>0))
Edward Andò's avatar
Edward Andò committed
644
        # check the mean strain without the bad ones
Edward Andò's avatar
Edward Andò committed
645
        self.assertAlmostEqual(numpy.nanmean(Ffield[:,0,0]), zStretch, places=3)
646

Edward Andò's avatar
Edward Andò committed
647
648
649
        # Same as above with all strain components (F and R) to pass them to grain projector
        Ffield = spam.deformation.FfieldBagi(pointsRef, connectivity, pointsRef * [zStretch, 1.0, 1.0] - pointsRef)
        self.assertAlmostEqual(Ffield[:,0,0].mean(), zStretch, places=3)
650

Edward Andò's avatar
Edward Andò committed
651
652
653
654
655
        # Project F back to grains
        grainF = spam.mesh.projectTetFieldToGrains(pointsRef * [zStretch, 1.0, 1.0], connectivity, Ffield)
        self.assertAlmostEqual(numpy.mean(grainF[:,0,0]), zStretch, places=3)
        self.assertAlmostEqual(numpy.mean(grainF[:,1,1]), 1.00, places=3)
        self.assertAlmostEqual(numpy.mean(grainF[:,2,2]), 1.00, places=3)
656
657
658



Edward Andò's avatar
Edward Andò committed
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
        #######################################################
        # Rotation of points for grain strain calc
        #######################################################
        pointsRotated = pointsRef.copy()
        rotAngle = 3.0
        for n, point in enumerate(pointsRef):
            pointPad = numpy.ones(4)
            pointPad[0:3] = point
            # pointsRotated[n] = point + spam.DIC.computeTransformationOperator(  {'r': [10.0,0.0,0.0]},
            Phi = spam.deformation.computePhi({'r': [rotAngle, 0.0, 0.0]},
                                              PhiCentre=[0.0, 50.0, 50.0],
                                              PhiPoint=point)
            # pointsRotated[n] = numpy.dot(F,pointPad)[0:3]
            pointsRotated[n] += Phi[0:3, -1]
            # print( point, pointsRotated[n], '\n\n' )

        # Compute strains
        Ffield      = spam.deformation.FfieldBagi(pointsRef, connectivity, pointsRotated - pointsRef)
        decomposedF = spam.deformation.decomposeFfield(Ffield, ["r", "vol", "dev"])

        self.assertAlmostEqual(decomposedF['r'][:, 0].mean(), rotAngle, places=3)
        self.assertAlmostEqual(decomposedF['r'][:, 1].mean(), 0.0, places=3)
        self.assertAlmostEqual(decomposedF['r'][:, 2].mean(), 0.0, places=3)
        self.assertAlmostEqual(decomposedF['vol'].mean(), 0, places=3)
        self.assertAlmostEqual(decomposedF['dev'].mean(), 0, places=3)

        # Project to grains
        grain_r = spam.mesh.projectTetFieldToGrains(pointsRotated, connectivity, decomposedF['r'])
        self.assertAlmostEqual(numpy.mean(grain_r[:,0]), rotAngle, places=3)
        self.assertAlmostEqual(numpy.mean(grain_r[:,1]), 0.00, places=3)
        self.assertAlmostEqual(numpy.mean(grain_r[:,2]), 0.00, places=3)
690
691
692



Edward Andò's avatar
Edward Andò committed
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
        #######################################################
        # Homogeneous shrinking together
        #######################################################
        shrink = 0.99
        # Deform the points by pushing them closer together -- this is compressing so  negative volumetric strain
        Ffield = spam.deformation.FfieldBagi(pointsRef, connectivity, pointsRef * shrink - pointsRef)
        decomposedF = spam.deformation.decomposeFfield(Ffield, ["vol"])
        self.assertAlmostEqual(decomposedF['vol'].mean(), 3. * (shrink - 1.), places=3)

        Ffield = spam.deformation.FfieldBagi(pointsRef, connectivity, pointsRef * shrink - pointsRef)
        # Project F back to grains
        grainF = spam.mesh.projectTetFieldToGrains(pointsRef * shrink, connectivity, Ffield)
        self.assertAlmostEqual(numpy.mean(grainF[:,0,0]), shrink, places=3)
        self.assertAlmostEqual(numpy.mean(grainF[:,1,1]), shrink, places=3)
        self.assertAlmostEqual(numpy.mean(grainF[:,2,2]), shrink, places=3)

        ### Attempt a grid projection
        #grid_bounds, num_in_grid, gridStrain = spam.mesh.projectBagiStrainToGrid(pointsRef * shrink, connectivity, F, nx=3, ny=3, nz=3)
        #print(grid_bounds)
        #print(num_in_grid)
        #print(gridStrain)
714

Edward Andò's avatar
Edward Andò committed
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737

        #######################################################
        # Move one point and see if the right elements strain
        #######################################################
        # make sure that the connectivity is well respected in the output  --  move only one point,
        #   and make sure only the elements concerned are moved.
        # Move point two:
        pointToMove = 2
        newPoints = pointsRef.copy()
        # newPoints[pointToMove] += numpy.random.randint( -10, 10, (3))
        newPoints[pointToMove] += [10, 10, 10]

        # list of numbers
        tetsWithPointToMove = numpy.where(connectivity == pointToMove)[0]
        Ffield = spam.deformation.FfieldBagi(pointsRef, connectivity, newPoints - pointsRef)
        decomposedF = spam.deformation.decomposeFfield(Ffield, ["dev"])

        # full length indexing bool array
        otherTets = numpy.ones(connectivity.shape[0], dtype=bool)
        otherTets[tetsWithPointToMove] = 0

        self.assertEqual(decomposedF['dev'][otherTets].tolist(), numpy.zeros(otherTets.sum()).tolist())
        self.assertTrue(numpy.sum(decomposedF['dev'][tetsWithPointToMove] != 0) == len(tetsWithPointToMove))
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
    def test_merge(self):
        #######################################################
        ### 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))

        #test of rigid translation and rotation
        #Create Phi and Apply (25 px displacement on Y-axis, and 5 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'))


        #######################################################
        ### Now use the ddic and ldic 
        #######################################################
        exitCode = subprocess.call(["spam-ldic",
                                    "-glt", "0.5",
                                    "-hws", "10",
                                    "-ns", "10",
808
                                    "-reg", "-regbb", "2", "-regbe", "2",
809
810
811
812
813
814
815
816
817
818
819
820
821
822
                                    "-tsv", 
                                    "-gpi", "5",
                                    "Step0.tif", "Step1.tif",
                                    "-od", testFolder+""])
        self.assertEqual(exitCode, 0)

        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)


823
        # With lists
824
825
826
827
828
829
        spam.deformation.mergeRegularGridAndDiscrete(regularGrid=spam.helpers.readCorrelationTSV(testFolder+'Step0-Step1.tsv'),
                                                              discrete=[spam.helpers.readCorrelationTSV(testFolder+'Step0-Step1-discreteDVC.tsv')],
                                                              labelledImage=[tifffile.imread(testFolder+'Lab0.tif')],
                                                              alwaysLabel=False,
                                                              fileName=testFolder+'merged.tsv')

830
831
        # Non-working options, either one list and not the other, or different sizes, catch None returns
        r = spam.deformation.mergeRegularGridAndDiscrete(regularGrid=spam.helpers.readCorrelationTSV(testFolder+'Step0-Step1.tsv'),
832
                                                              discrete=[spam.helpers.readCorrelationTSV(testFolder+'Step0-Step1-discreteDVC.tsv')],
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
                                                              labelledImage=[tifffile.imread(testFolder+'Lab0.tif'), None],
                                                              alwaysLabel=False,
                                                              fileName=testFolder+'merged.tsv')
        self.assertEqual(r is None, True)

        r = spam.deformation.mergeRegularGridAndDiscrete(regularGrid=spam.helpers.readCorrelationTSV(testFolder+'Step0-Step1.tsv'),
                                                              discrete=[spam.helpers.readCorrelationTSV(testFolder+'Step0-Step1-discreteDVC.tsv')],
                                                              labelledImage=tifffile.imread(testFolder+'Lab0.tif'),
                                                              alwaysLabel=False,
                                                              fileName=testFolder+'merged.tsv')
        self.assertEqual(r is None, True)

        r = spam.deformation.mergeRegularGridAndDiscrete(regularGrid=spam.helpers.readCorrelationTSV(testFolder+'Step0-Step1.tsv'),
                                                              discrete=[spam.helpers.readCorrelationTSV(testFolder+'Step0-Step1-discreteDVC.tsv')],
                                                              labelledImage=None,
                                                              alwaysLabel=False,
                                                              fileName=testFolder+'merged.tsv')
        self.assertEqual(r is None, True)

        # This works again, no lists
        output = spam.deformation.mergeRegularGridAndDiscrete(regularGrid=spam.helpers.readCorrelationTSV(testFolder+'Step0-Step1.tsv'),
                                                              discrete=spam.helpers.readCorrelationTSV(testFolder+'Step0-Step1-discreteDVC.tsv'),
                                                              labelledImage=tifffile.imread(testFolder+'Lab0.tif'))
856
857
858
859
860
861
862
863
864
865
866
867
868

        for i in range(3):
            self.assertAlmostEqual(numpy.mean(output['PhiField'][:,i,-1][output['returnStatus']==2]) - translationStep1[i], 0, places=1)

        # Check that there are more RS==2 points in the merged than in the ldic
        rsTwoLdic = numpy.sum(spam.helpers.readCorrelationTSV(testFolder+'Step0-Step1.tsv')['returnStatus']==2)
        self.assertEqual(numpy.sum(output['returnStatus']==2) > rsTwoLdic, True)

        # Check that there some mergeSource = 1
        mergeSource = numpy.unique(numpy.genfromtxt(testFolder+'merged.tsv', names=True)['mergeSource'])
        self.assertEqual(mergeSource[0], 0)
        self.assertEqual(mergeSource[1], 1)

869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892

    def test_interpolatePhiField(self):
        # Fake Phi field -- this will be defined at 0,0,0 and +100 in all directions
        # z =   0 --> transformation below:
        transformation = {'t': [5., 0., 0.],
                          'r': [0., 0., 0.]}
        # z = 100 --> nothing

        fieldCoords = numpy.array([[  0,  0,  0],
                                   [  0,  0,100],
                                   [  0,100,  0],
                                   [  0,100,100],
                                   [100,  0, 0],
                                   [100,  0,100],
                                   [100,100,  0],
                                   [100,100,100]])

        fieldValues = numpy.zeros([8,4,4])
        fieldValues[0:4] = spam.deformation.computePhi(transformation)
        fieldValues[4:8] = numpy.eye(4)

        interpCoods = numpy.array([[50.,50.,50.]])

        interpolatedPhi = spam.deformation.interpolatePhiField(fieldCoords, fieldValues, interpCoods)
893

894
895
896
897
898
899
        decomposedInterpolatedPhi = spam.deformation.decomposePhi(interpolatedPhi[0])

        for key in transformation.keys():
            for i in range(3):
                self.assertAlmostEqual(decomposedInterpolatedPhi[key][i],
                                       transformation[key][i]/2.0 ,places=3)
900

901

902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
    def test_computeRigidPhi(self):
        transformation = {'t': [5., 0., 0.],
                          'r': [3., 0., 0.]}
        PhiR1 = spam.deformation.computePhi(transformation)
        PhiR2 = spam.deformation.computeRigidPhi(PhiR1)
        for i in range(4):
            for j in range(4):
                self.assertAlmostEqual(PhiR1[i,j], PhiR2[i,j], places=2)

        transformation = {'t': [5., 0., 0.],
                          'r': [3., 0., 0.],
                          'z': [1.01, 1.01, 1.01]}
        PhiR1 = spam.deformation.computePhi(transformation)
        PhiR2 = spam.deformation.computeRigidPhi(PhiR1)
        for i in range(4):
            for j in range(4):
918
                if i==j and i < 3:
919
920
921
                    self.assertEqual(PhiR1[i,j] > PhiR2[i,j], True)
                else:
                    self.assertAlmostEqual(PhiR1[i,j], PhiR2[i,j], places=2)
922
923


Gustavo Pinzon's avatar
Gustavo Pinzon committed
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
    def test_decomposeF(self):
        #Test that it runs without problems
        F = numpy.array(([5, 2, 3],[2,5,1],[3, 1, 5]))
        res = spam.deformation.deformationFunction.decomposeF(F)
        self.assertIsNotNone(res)
        #Test for singular F
        F = numpy.array(([1, 2, 3],[2, 4, 6],[3, 6, 9]))
        res = spam.deformation.deformationFunction.decomposeF(F)
        self.assertTrue(numpy.isnan(res['r'][0]))
        #Test for nan
        F = numpy.array(([1, 2, 3],[2, 4, 6],[3, numpy.nan, 9]))
        res = spam.deformation.deformationFunction.decomposeF(F)
        self.assertTrue(numpy.isnan(res['r'][0]))
        #Test for inf
        F = numpy.array(([1, 2, 3],[2, 4, 6],[3, numpy.inf, 9]))
        res = spam.deformation.deformationFunction.decomposeF(F)
        self.assertTrue(numpy.isnan(res['r'][0]))
941

942
943
944
945
946
947
948
949
950
951
952
953
954
955
    def test_decomposePhiField(self):
        PhiField = numpy.array([numpy.eye(4) for point in range(3)])

        decomposedPhiField = spam.deformation.decomposePhiField(PhiField, ["vol", "dev", "volss", "devss", "t", "r", "z", "U", "e"])

        for point in range(PhiField.shape[0]):
            self.assertTrue(numpy.allclose(decomposedPhiField["t"][point], numpy.zeros(3)))
            self.assertTrue(numpy.allclose(decomposedPhiField["r"][point], numpy.zeros(3)))
            self.assertTrue(numpy.allclose(decomposedPhiField["U"][point], numpy.eye(3)))
            self.assertTrue(numpy.allclose(decomposedPhiField["vol"][point], 0.0))
            self.assertTrue(numpy.allclose(decomposedPhiField["dev"][point], 0.0))
            self.assertTrue(numpy.allclose(decomposedPhiField["e"][point], numpy.zeros((3,3))))
            self.assertTrue(numpy.allclose(decomposedPhiField["volss"][point], 0.0))
            self.assertTrue(numpy.allclose(decomposedPhiField["devss"][point], 0.0))
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
            
    def test_getDisplacementFromNeighbours(self):

        # Create a TSV and Lab file just as in test_merge

        #######################################################
        ### 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))

        #test of rigid translation and rotation
998
        #Create Phi and Apply (25 px displacement on Y-axis, and 0 degree rotation along Z axis)
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
        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'))


        #######################################################
        ### Now use the ddic and ldic 
        #######################################################
        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)

        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)
        
        
        # Read lab file and TSV from previous code
        imLab = tifffile.imread('Lab0.tif')
        TSV  = spam.helpers.readCorrelationTSV('Step0-Step1-discreteDVC.tsv', 
                                               readConvergence=True, 
                                               readError=True, 
                                               readLabelDilate=True, 
                                               readPSCC=True)
        # Manually change the RS of one grain
        TSV['returnStatus'][10] = -1
        
        # Case 1: Run the function normally and check the displacement and F
        exitCode = spam.deformation.deformationField.getDisplacementFromNeighbours(imLab, TSV, './TSV_getDisplacementFromNeighbours.tsv')
        # Read the resulting TSV
        tsvRes  = spam.helpers.readCorrelationTSV('TSV_getDisplacementFromNeighbours.tsv', 
                                                  readConvergence=True, 
                                                  readError=True, 
                                                  readLabelDilate=True, 
                                                  readPSCC=True)
        # Get the mean translation
        meanT = spam.deformation.deformationFunction.decomposePhi(tsvRes['PhiField'][10])['t']
        # Check the values (The values are linked to the displacement imposed at the beginning of the code on test_merge)
        self.assertAlmostEqual(meanT[0], 5, places=2)
        self.assertAlmostEqual(meanT[1], 2, places=2)
        self.assertAlmostEqual(meanT[2], 0, places=2)
        # Check that the F matrix is equal to numpy.eye(3)
        self.assertTrue((tsvRes['PhiField'][10][:-1, :-1] == numpy.eye(3)).all())
        
        # Case 2: Run the function using the same TSV as the previous step to preserve F
        spam.deformation.deformationField.getDisplacementFromNeighbours(imLab, TSV, './TSV_getDisplacementFromNeighbours.tsv', previousDVC = TSV)
        # Read the resulting TSV
        tsvRes  = spam.helpers.readCorrelationTSV('TSV_getDisplacementFromNeighbours.tsv', 
                                                  readConvergence=True, 
                                                  readError=True, 
                                                  readLabelDilate=True, 
                                                  readPSCC=True)
        # Get the mean translation
        meanT = spam.deformation.deformationFunction.decomposePhi(tsvRes['PhiField'][10])['t']
        # Check the values (The values are linked to the displacement imposed at the beginning of the code on test_merge)
        self.assertAlmostEqual(meanT[0], 5, places=2)
        self.assertAlmostEqual(meanT[1], 2, places=2)
        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())
1086
        
Gustavo Pinzon's avatar
Gustavo Pinzon committed
1087
1088
1089
1090
1091
1092
1093
1094
1095
        # Case 3: Run the function with an incomplete TSV file
        TSV  = spam.helpers.readCorrelationTSV('Step0-Step1-discreteDVC.tsv', 
                                               readConvergence=False, 
                                               readError=False, 
                                               readLabelDilate=False, 
                                               readPSCC=False)
        res = spam.deformation.deformationField.getDisplacementFromNeighbours(imLab, TSV, './TSV_getDisplacementFromNeighbours.tsv', previousDVC = TSV)
        self.assertIsNone(res)
        
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
    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)
1237

1238
1239
if __name__ == '__main__':
    unittest.main()