Debian Codegraph @

skfmm/__init__.py

raw symbols SCIP
1 # -*- mode: doctest -*-
2 """scikit-fmm is a Python extension module which implements the fast
3 marching method.
4
5 https://github.com/scikit-fmm/scikit-fmm
6
7 The fast marching method is used to model the evolution of boundaries
8 and interfaces in a variety of application areas. More specifically,
9 the fast marching method is a numerical technique for finding
10 approximate solutions to boundary value problems of the Eikonal
11 equation:
12
13 F(x) | grad T(x) | = 1.
14
15 Typically, such a problem describes the evolution of a closed curve as
16 a function of time T with speed F(x)>0 in the normal direction at a
17 point x on the curve. The speed function is specified, and the time at
18 which the contour crosses a point x is obtained by solving the
19 equation.
20
21 skfmm.distance(phi, dx=1.0, self_test=False, order=2, narrow=0.0,
22 periodic=False)
23
24 Return the signed distance from the zero contour of the array phi.
25
26 skfmm.travel_time(phi, speed, dx=1.0, self_test=False, order=2,
27 narrow=0.0, periodic=False)
28
29 Return the travel from the zero contour of the array phi given the
30 scalar velocity field speed.
31
32 skfmm.extension_velocities(phi, speed, dx=1.0, self_test=False,
33 order=2, ext_mask=None, narrow=0.0, periodic=False)
34
35 Extend the velocities defined at the zero contour of phi, in the
36 normal direction, to the rest of the domain. Extend the velocities
37 such that grad f_ext dot grad d = 0 where where f_ext is the
38 extension velocity and d is the signed distance function.
39
40
41 :Copyright: Copyright 2025 The scikit-fmm team.
42 :License: BSD-style license. See LICENSE.txt in the source directory.
43
44 """
45
46 from __future__ import print_function
47
48 __version__ = "2025.06.23"
49 __docformat__ = 'restructuredtext'
50
51 from .pfmm import distance, travel_time, extension_velocities
52 from .heap import heap
53
54 def testing():
55 r"""
56
57 These tests are gathered from FiPy_, PyLSMLIB_ and original
58 Scikit-fmm_ tests.
59
60 .. _FiPy: http://www.ctcms.nist.gov/fipy/
61 .. _PyLSMLIB: https://github.com/ktchu/LSMLIB/tree/master/pylsmlib
62 .. _Scikit-fmm: http://packages.python.org/scikit-fmm/
63 .. _LSMLIB: http://ktchu.serendipityresearch.org/software/lsmlib/index.html
64
65 **1D Test**
66
67 >>> import numpy as np
68
69 >>> print(np.allclose(distance((-1., -1., -1., -1., 1., 1., 1., 1.), dx=.5),
70 ... (-1.75, -1.25, -.75, -0.25, 0.25, 0.75, 1.25, 1.75)))
71 True
72
73 Small dimensions.
74
75 >>> dx = 1e-10
76 >>> print(np.allclose(distance((-1., -1., -1., -1., 1., 1., 1., 1.), dx=dx),
77 ... np.arange(8) * dx - 3.5 * dx))
78 True
79
80 **Bug Fix**
81
82 Test case for a bug in the upwind finite difference scheme for
83 negative phi. When computing finite differences we want to
84 preferentially use information from the frozen neighbors that
85 are closest to the zero contour in each dimension. This means
86 that we must compare absolute distances when checking neighbors
87 in the negative phi direction.
88
89 The error can result in incorrect values of the updated signed
90 distance function for regions close to the minimum contour of
91 the level set function, i.e. in the middle of holes.
92
93 To test we use a square matrix for the initial phi field that is
94 equal to -1 on the main diagonal and on the three diagonals above
95 and below this. The matrix is set to 1 everywhere else. The bug
96 results in errors in positions (1,1), (2,2), (3,3), (6,6), (7,7)
97 and (8,8) along the main diagonal.
98
99 This error occurs for first- and second-order updates. For
100 simplicity, we choose to only test the first-order update.
101
102 >>> phi = np.ones((10, 10))
103 >>> i,j = np.indices(phi.shape)
104 >>> phi[i==j-3] = -1
105 >>> phi[i==j-2] = -1
106 >>> phi[i==j-1] = -1
107 >>> phi[i==j] = -1
108 >>> phi[i==j+1] = -1
109 >>> phi[i==j+2] = -1
110 >>> phi[i==j+3] = -1
111 >>> phi = distance(phi, order=1)
112 >>> print(np.allclose(phi[1, 1], -2.70464, atol=1e-4))
113 True
114 >>> print(np.allclose(phi[2, 2], -2.50873, atol=1e-4))
115 True
116 >>> print(np.allclose(phi[3, 3], -2.47487, atol=1e-4))
117 True
118 >>> print(np.allclose(phi[6, 6], -2.47487, atol=1e-4))
119 True
120 >>> print(np.allclose(phi[7, 7], -2.50873, atol=1e-4))
121 True
122 >>> print(np.allclose(phi[8, 8], -2.70464, atol=1e-4))
123 True
124
125 **Bug Fix**
126
127 A 2D test case to test trial values for a pathological case.
128
129 >>> dx = 1.
130 >>> dy = 2.
131 >>> vbl = -dx * dy / np.sqrt(dx**2 + dy**2) / 2.
132 >>> vbr = dx / 2
133 >>> vml = dy / 2.
134 >>> crossProd = dx * dy
135 >>> dsq = dx**2 + dy**2
136 >>> top = vbr * dx**2 + vml * dy**2
137 >>> sqrt = crossProd**2 *(dsq - (vbr - vml)**2)
138 >>> sqrt = np.sqrt(max(sqrt, 0))
139 >>> vmr = (top + sqrt) / dsq
140 >>> print(np.allclose(distance(((-1., 1., -1.), (1., 1., 1.)), dx=(dx, dy), order=1),
141 ... ((vbl, vml, vbl), (vbr, vmr, vbr))))
142 True
143
144 **Test Extension Field Calculation**
145
146 >>> tmp = 1 / np.sqrt(2)
147 >>> phi = np.array([[-1., 1.], [1., 1.]])
148 >>> phi, ext = extension_velocities(phi,
149 ... [[-1, .5], [2., -1.]],
150 ... ext_mask=phi < 0,
151 ... dx=1., order=1)
152 >>> print(np.allclose(phi, ((-tmp / 2, 0.5), (0.5, 0.5 + tmp))))
153 True
154 >>> print(np.allclose(ext, [[1.25, .5], [2., 1.25]]))
155 True
156
157 >>> phi = np.array(((-1., 1., 1.), (1., 1., 1.), (1., 1., 1.)))
158 >>> phi, ext = extension_velocities(phi,
159 ... ((-1., 2., -1.),
160 ... (.5, -1., -1.),
161 ... (-1., -1., -1.)),
162 ... ext_mask=phi < 0,
163 ... order=1)
164 >>> v1 = 0.5 + tmp
165 >>> v2 = 1.5
166 >>> tmp1 = (v1 + v2) / 2 + np.sqrt(2. - (v1 - v2)**2) / 2
167 >>> tmp2 = tmp1 + 1 / np.sqrt(2)
168 >>> print(np.allclose(phi, ((-tmp / 2, 0.5, 1.5),
169 ... (0.5, 0.5 + tmp, tmp1),
170 ... (1.5, tmp1, tmp2))))
171 True
172 >>> print(np.allclose(ext, ((1.25, 2., 2.),
173 ... (.5, 1.25, 1.5456),
174 ... (.5, 0.9544, 1.25)),
175 ... rtol = 1e-4))
176 True
177
178 **Bug Fix**
179
180 Test case for a bug that occurs when initializing the distance
181 variable at the interface. Currently it is assumed that adjacent
182 cells that are opposite sign neighbors have perpendicular normal
183 vectors. In fact the two closest cells could have opposite
184 normals.
185
186 >>> print(np.allclose(distance((-1., 1., -1.)), (-0.5, 0.5, -0.5)))
187 True
188
189 Testing second order. This example failed with Scikit-fmm_.
190
191 >>> phi = ((-1., -1., 1., 1.),
192 ... (-1., -1., 1., 1.),
193 ... (1., 1., 1., 1.),
194 ... (1., 1., 1., 1.))
195 >>> answer = ((-1.30473785, -0.5, 0.5, 1.49923009),
196 ... (-0.5, -0.35355339, 0.5, 1.45118446),
197 ... (0.5, 0.5, 0.97140452, 1.76215286),
198 ... (1.49923009, 1.45118446, 1.76215286, 2.33721352))
199 >>> print(np.allclose(distance(phi),
200 ... answer,
201 ... rtol=1e-9))
202 True
203
204 **A test for a bug in both LSMLIB and Scikit-fmm**
205
206 The following test gives different results depending on whether
207 LSMLIB_ or Scikit-fmm_ is used. This issue occurs when calculating
208 second order accurate distance functions. When a value becomes
209 "known" after previously being a "trial" value it updates its
210 neighbors' values. In a second order scheme the neighbors one step
211 away also need to be updated (if the cell between the new "known"
212 cell and the cell required for second order accuracy also happens
213 to be "known"), but are not updated in either package. By luck
214 (due to trial values having the same value), the values calculated
215 in Scikit-fmm_ for the following example are correct although an
216 example that didn't work for Scikit-fmm_ could also be
217 constructed.
218
219 >>> phi = distance([[-1, -1, -1, -1],
220 ... [ 1, 1, -1, -1],
221 ... [ 1, 1, -1, -1],
222 ... [ 1, 1, -1, -1]], order=2)
223 >>> phi = distance(phi, order=2)
224
225 The following values come form Scikit-fmm_.
226
227 >>> answer = [[-0.5, -0.58578644, -1.08578644, -1.85136395],
228 ... [ 0.5, 0.29289322, -0.58578644, -1.54389939],
229 ... [ 1.30473785, 0.5, -0.5, -1.5 ],
230 ... [ 1.49547948, 0.5, -0.5, -1.5 ]]
231
232 The 3rd and 7th element are different for LSMLIB_. This is because
233 the 15th element is not "known" when the "trial" value for the 7th
234 element is calculated. Scikit-fmm_ calculates the values in a
235 slightly different order so gets a seemingly better answer, but
236 this is just chance.
237
238 >>> print(np.allclose(phi, answer, rtol=1e-9))
239 True
240
241 The following tests for the same issue but is a better test case
242 guaranteed to fail.
243
244 >>> phi = np.array([[-1, 1, 1, 1, 1, -1],
245 ... [-1, -1, -1, -1, -1, -1],
246 ... [-1, -1, -1, -1, -1, -1]])
247
248 >>> phi = distance(phi)
249 >>> print(phi[2, 2] == phi[2, 3])
250 True
251
252 >>> phi = distance(phi)
253 >>> print(phi[2, 2] == phi[2, 3])
254 True
255
256 **Circle Example**
257
258 Solve the level set equation in two dimensions for a circle.
259
260 The 2D level set equation can be written,
261
262 .. math::
263
264 |\nabla \phi| = 1
265
266 and the boundary condition for a circle is given by, :math:`\phi = 0` at
267 :math:`(x - L / 2)^2 + (y - L / 2)^2 = (L / 4)^2`.
268
269 The solution to this problem will be demonstrated in the following
270 script. Firstly, setup the parameters.
271
272 >>> def mesh(nx=1, ny=1, dx=1., dy=1.):
273 ... y, x = np.mgrid[0:nx,0:ny]
274 ... x = x * dx + dx / 2
275 ... y = y * dy + dy / 2
276 ... return x, y
277
278 >>> dx = 1.
279 >>> N = 11
280 >>> L = N * dx
281 >>> x, y = mesh(nx=N, ny=N, dx=dx, dy=dx)
282 >>> phi = -np.ones(N * N, 'd')
283 >>> phi[(x.flatten() - L / 2.)**2 + (y.flatten() - L / 2.)**2 < (L / 4.)**2] = 1.
284 >>> phi = np.reshape(phi, (N, N))
285 >>> phi = distance(phi, dx=dx, order=1).flatten()
286
287 >>> dX = dx / 2.
288 >>> m1 = dX * dX / np.sqrt(dX**2 + dX**2)
289 >>> def evalCell(phix, phiy, dx):
290 ... aa = dx**2 + dx**2
291 ... bb = -2 * ( phix * dx**2 + phiy * dx**2)
292 ... cc = dx**2 * phix**2 + dx**2 * phiy**2 - dx**2 * dx**2
293 ... sqr = np.sqrt(bb**2 - 4. * aa * cc)
294 ... return ((-bb - sqr) / 2. / aa, (-bb + sqr) / 2. / aa)
295 >>> v1 = evalCell(-dX, -m1, dx)[0]
296 >>> v2 = evalCell(-m1, -dX, dx)[0]
297 >>> v3 = evalCell(m1, m1, dx)[1]
298 >>> v4 = evalCell(v3, dX, dx)[1]
299 >>> v5 = evalCell(dX, v3, dx)[1]
300 >>> MASK = -1000.
301 >>> trialValues = np.array((
302 ... MASK, MASK, MASK, MASK, MASK, MASK, MASK, MASK, MASK, MASK, MASK,
303 ... MASK, MASK, MASK, MASK,-3*dX,-3*dX,-3*dX, MASK, MASK, MASK, MASK,
304 ... MASK, MASK, MASK, v1, -dX, -dX, -dX, v1, MASK, MASK, MASK,
305 ... MASK, MASK, v2, -m1, m1, dX, m1, -m1, v2, MASK, MASK,
306 ... MASK, -dX*3, -dX, m1, v3, v4, v3, m1, -dX,-dX*3, MASK,
307 ... MASK, -dX*3, -dX, dX, v5, MASK, v5, dX, -dX,-dX*3, MASK,
308 ... MASK, -dX*3, -dX, m1, v3, v4, v3, m1, -dX,-dX*3, MASK,
309 ... MASK, MASK, v2, -m1, m1, dX, m1, -m1, v2, MASK, MASK,
310 ... MASK, MASK, MASK, v1, -dX, -dX, -dX, v1, MASK, MASK, MASK,
311 ... MASK, MASK, MASK, MASK,-3*dX,-3*dX,-3*dX, MASK, MASK, MASK, MASK,
312 ... MASK, MASK, MASK, MASK, MASK, MASK, MASK, MASK, MASK, MASK, MASK), 'd')
313
314 >>> phi[trialValues == MASK] = MASK
315 >>> print(np.allclose(phi, trialValues))
316 True
317
318 **Square Example**
319
320 Here we solve the level set equation in two dimensions for a square. The equation is
321 given by:
322
323 .. math::
324
325 |\nabla \phi| &= 1 \\
326 \phi &= 0 \qquad \text{at} \qquad \begin{cases}
327 x = \left( L / 3, 2 L / 3 \right)
328 & \text{for $L / 3 \le y \le 2 L / 3$} \\
329 y = \left( L / 3, 2 L / 3 \right)
330 & \text{for $L / 3 \le x \le 2 L / 3$}
331 \end{cases}
332
333 >>> dx = 0.5
334 >>> dy = 2.
335 >>> nx = 5
336 >>> ny = 5
337 >>> Lx = nx * dx
338 >>> Ly = ny * dy
339
340 >>> x, y = mesh(nx=nx, ny=ny, dx=dx, dy=dy)
341 >>> x = x.flatten()
342 >>> y = y.flatten()
343 >>> phi = -np.ones(nx * ny, 'd')
344 >>> phi[((Lx / 3. < x) & (x < 2. * Lx / 3.)) & ((Ly / 3. < y) & (y < 2. * Ly / 3))] = 1.
345 >>> phi = np.reshape(phi, (nx, ny))
346 >>> phi = distance(phi, dx=(dy, dx), order=1).flatten()
347
348 >>> def evalCell(phix, phiy, dx, dy):
349 ... aa = dy**2 + dx**2
350 ... bb = -2 * ( phix * dy**2 + phiy * dx**2)
351 ... cc = dy**2 * phix**2 + dx**2 * phiy**2 - dx**2 * dy**2
352 ... sqr = np.sqrt(bb**2 - 4. * aa * cc)
353 ... return ((-bb - sqr) / 2. / aa, (-bb + sqr) / 2. / aa)
354 >>> val = evalCell(-dy / 2., -dx / 2., dx, dy)[0]
355 >>> v1 = evalCell(val, -3. * dx / 2., dx, dy)[0]
356 >>> v2 = evalCell(-3. * dy / 2., val, dx, dy)[0]
357 >>> v3 = evalCell(v2, v1, dx, dy)[0]
358 >>> v4 = dx * dy / np.sqrt(dx**2 + dy**2) / 2
359 >>> arr = np.array((
360 ... v3 , v2 , -3. * dy / 2. , v2 , v3,
361 ... v1 , val , -dy / 2. , val , v1 ,
362 ... -3. * dx / 2., -dx / 2., v4 , -dx / 2., -3. * dx / 2.,
363 ... v1 , val , -dy / 2. , val , v1 ,
364 ... v3 , v2 , -3. * dy / 2. , v2 , v3 ))
365 >>> print(np.allclose(arr, phi))
366 True
367
368 **Assertion Errors**
369
370 >>> distance([[-1, 1],[1, 1]], dx=(1, 2, 3))
371 Traceback (most recent call last):
372 ...
373 ValueError: dx must be of length len(phi.shape)
374 >>> extension_velocities([[-1, 1],[1, 1]], speed=[1, 1])
375 Traceback (most recent call last):
376 ...
377 ValueError: phi and speed must have the same shape
378
379 **Test for 1D equality between `distance` and `travel_time`**
380
381 >>> phi = np.arange(-5, 5) + 0.499
382 >>> d = distance(phi)
383 >>> t = travel_time(phi, speed=np.ones_like(phi))
384 >>> np.testing.assert_allclose(t, np.abs(d))
385
386 **Tests taken from FiPy**
387
388 >>> phi = np.array(((-1, -1, 1, 1),
389 ... (-1, -1, 1, 1),
390 ... (1, 1, 1, 1),
391 ... (1, 1, 1, 1)))
392 >>> o1 = distance(phi, order=1, self_test=True)
393 >>> dw_o1 = [[-1.20710678, -0.5, 0.5, 1.5],
394 ... [-0.5, -0.35355339, 0.5, 1.5],
395 ... [ 0.5, 0.5, 1.20710678, 2.04532893],
396 ... [ 1.5, 1.5, 2.04532893, 2.75243571]]
397 >>> np.testing.assert_allclose(o1, dw_o1)
398
399 >>> phi = np.array(((-1, -1, 1, 1),
400 ... (-1, -1, 1, 1),
401 ... (1, 1, 1, 1),
402 ... (1, 1, 1, 1)))
403 >>> o1 = travel_time(phi, np.ones_like(phi), order=1, self_test=True)
404 >>> dw_o1 = [[-1.20710678, -0.5, 0.5, 1.5],
405 ... [-0.5, -0.35355339, 0.5, 1.5],
406 ... [ 0.5, 0.5, 1.20710678, 2.04532893],
407 ... [ 1.5, 1.5, 2.04532893, 2.75243571]]
408 >>> np.testing.assert_allclose(o1, np.abs(dw_o1))
409
410 >>> phi = np.array(((-1, -1, 1, 1),
411 ... (-1, -1, 1, 1),
412 ... (1, 1, 1, 1),
413 ... (1, 1, 1, 1)))
414 >>> o2 = distance(phi, self_test=True)
415 >>> dw_o2 = [[-1.30473785, -0.5, 0.5, 1.49923009],
416 ... [-0.5, -0.35355339, 0.5, 1.45118446],
417 ... [ 0.5, 0.5, 0.97140452, 1.76215286],
418 ... [ 1.49923009, 1.45118446, 1.76215286, 2.33721352]]
419
420 >>> np.testing.assert_allclose(o2, dw_o2)
421 >>> phi = np.array(((-1, -1, 1, 1),
422 ... (-1, -1, 1, 1),
423 ... (1, 1, 1, 1),
424 ... (1, 1, 1, 1)))
425 >>> o2 = travel_time(phi, np.ones_like(phi), self_test=True)
426 >>> dw_o2 = [[-1.30473785, -0.5, 0.5, 1.49923009],
427 ... [-0.5, -0.35355339, 0.5, 1.45118446],
428 ... [ 0.5, 0.5, 0.97140452, 1.76215286],
429 ... [ 1.49923009, 1.45118446, 1.76215286, 2.33721352]]
430 >>> np.testing.assert_allclose(o2, np.abs(dw_o2))
431
432 >>> distance([-1,1], order=0)
433 Traceback (most recent call last):
434 ...
435 ValueError: order must be 1 or 2
436
437 >>> distance([-1,1], order=3)
438 Traceback (most recent call last):
439 ...
440 ValueError: order must be 1 or 2
441
442 **Extension velocity tests**
443
444 Test 1d extension constant.
445
446 >>> phi = [-1,-1,-1,1,1,1]
447 >>> speed = [1,1,1,1,1,1]
448 >>> d, f_ext = extension_velocities(phi, speed, self_test=True)
449 >>> np.testing.assert_allclose(speed, f_ext)
450
451 Test the 1D extension block.
452
453 >>> phi = np.ones(10)
454 >>> phi[0] =- 1
455 >>> speed = np.ones(10)
456 >>> speed[0:3] = 5
457 >>> d, f_ext = extension_velocities(phi, speed, self_test=True)
458 >>> np.testing.assert_allclose(f_ext, 5)
459
460 Test that a uniform speed value is preserved.
461
462 >>> N = 50
463 >>> X, Y = np.meshgrid(np.linspace(-1, 1, N), np.linspace(-1, 1, N))
464 >>> r = 0.25
465 >>> dx = 2.0 / (N - 1)
466 >>> phi = (X) ** 2 + (Y) ** 2 - r ** 2
467 >>> speed = np.ones_like(phi)
468 >>> d, f_ext = extension_velocities(phi, speed, dx, self_test=True)
469 >>> np.testing.assert_allclose(f_ext, 1.0)
470
471 Constant value march-out test
472
473 >>> speed[abs(Y)<0.3] = 10.0
474 >>> d, f_ext = extension_velocities(phi, speed, dx, self_test=True)
475 >>> np.testing.assert_allclose(f_ext, 10.0)
476
477 Test distance from extension
478
479 >>> speed = np.ones_like(phi)
480 >>> d, f_ext = extension_velocities(phi, speed, dx, self_test=True)
481 >>> d2 = distance(phi, dx, self_test=True)
482 >>> np.testing.assert_allclose(d, d2)
483
484 Test for extension velocity bug
485
486 >>> N = 150
487 >>> X, Y = np.meshgrid(np.linspace(-1, 1, N), np.linspace(-1, 1, N))
488 >>> r = 0.5
489 >>> dx = 2.0 / (N - 1)
490 >>> phi = (X) ** 2 + (Y) ** 2 - r ** 2
491 >>> speed = np.ones_like(phi)
492 >>> speed[X>0.25] = 3.0
493 >>> d2, f_ext = extension_velocities(phi, speed, dx)
494
495 >>> assert (f_ext <= 3.0000001).all()
496 >>> assert (f_ext >= 1).all()
497
498 >>> np.testing.assert_almost_equal(f_ext[137, 95], 1, 3)
499 >>> np.testing.assert_almost_equal(f_ext[103, 78], 1, 2)
500 >>> np.testing.assert_almost_equal(f_ext[72, 100], 3, 3)
501 >>> np.testing.assert_almost_equal(f_ext[72, 86], 3, 3)
502 >>> np.testing.assert_almost_equal(f_ext[110, 121], 3, 3)
503
504 Simple two point tests
505
506 >>> np.testing.assert_array_equal(distance([-1, 1]),
507 ... [-0.5, 0.5])
508 >>> np.testing.assert_allclose(distance([-1, -1, -1, 1, 1, 1]),
509 ... [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5])
510 >>> np.testing.assert_allclose(distance([1, 1, 1, -1, -1, -1]),
511 ... [2.5, 1.5, 0.5, -0.5, -1.5, -2.5])
512
513 Three point test case
514
515 >>> np.testing.assert_array_equal(distance([-1, 0, 1]), [-1, 0, 1])
516 >>> np.testing.assert_array_equal(distance([-1, 0, 1], dx=[2]), [-2, 0, 2])
517 >>> np.testing.assert_array_equal(distance([-1, 0, 1], dx=2), [-2, 0, 2])
518 >>> np.testing.assert_array_equal(distance([-1, 0, 1], dx=2.0), [-2, 0, 2])
519 >>> np.testing.assert_array_equal(travel_time([1, 0, -1], [1, 1, 1]),
520 ... [1, 0, 1])
521 >>> np.testing.assert_array_equal(travel_time([-1, 0, 1], [1, 1, 1]),
522 ... [1, 0, 1])
523 >>> np.testing.assert_array_equal(travel_time([1, 0, -1], [1, 1, 1], dx=2),
524 ... [2, 0, 2])
525 >>> np.testing.assert_array_equal(travel_time([1, 0, -1], [1, 1, 1], dx=[2]),
526 ... [2, 0, 2])
527 >>> np.testing.assert_array_equal(travel_time([1, 0, -1], [1, 1, 1], dx=2.0),
528 ... [2, 0, 2])
529
530 Travel time tests 1
531
532 >>> np.testing.assert_allclose(travel_time([0, 1, 1, 1, 1], [2, 2, 2, 2, 2]),
533 ... [0, 0.5, 1.0, 1.5, 2.0])
534 >>> np.testing.assert_array_equal(travel_time([1, 0, -1], [2, 2, 2]),
535 ... [0.5, 0, 0.5])
536
537 Travel time tests 2
538
539 >>> phi = [1, 1, 1, -1, -1, -1]
540 >>> t = travel_time(phi, np.ones_like(phi))
541 >>> exact = [2.5, 1.5, 0.5, 0.5, 1.5, 2.5]
542 >>> np.testing.assert_allclose(t, exact)
543
544 Travel time tests 3
545
546 >>> phi = [-1, -1, -1, 1, 1, 1]
547 >>> t = travel_time(phi, np.ones_like(phi))
548 >>> exact = [2.5, 1.5, 0.5, 0.5, 1.5, 2.5]
549 >>> np.testing.assert_allclose(t, exact)
550
551 Corner case
552
553 >>> np.testing.assert_array_equal(distance([0, 0]), [0, 0])
554 >>> np.testing.assert_array_equal(travel_time([0, 0], [1, 1]), [0, 0])
555
556 Test zero
557
558 >>> distance([1, 0, 1, 1], 0)
559 Traceback (most recent call last):
560 ...
561 ValueError: dx must be greater than zero
562
563 Test dx shape
564
565 >>> distance([0, 0, 1, 0, 0], [0, 0, 1, 0, 0])
566 Traceback (most recent call last):
567 ...
568 ValueError: dx must be of length len(phi.shape)
569
570 Test for small speeds
571
572 Test catching speeds which are too small. Speeds less than the
573 machine epsilon are masked off to avoid an overflow.
574
575 >>> t = travel_time([-1, -1, 0, 1, 1], [1, 1, 1, 1, 0])
576 >>> assert isinstance(t, np.ma.MaskedArray)
577 >>> np.testing.assert_array_equal(t.data[:-1], [2, 1, 0, 1])
578 >>> np.testing.assert_array_equal(t.mask, [False, False, False, False, True])
579
580 >>> t2 = travel_time([-1, -1, 0, 1, 1], [1, 1, 1, 1, 1e-300])
581 >>> np.testing.assert_array_equal(t, t2)
582
583 Mask test
584
585 Test that when the mask cuts off the solution, the cut off points
586 are also masked.
587
588 >>> ma = np.ma.MaskedArray([1, 1, 1, 0], [False, True, False, False])
589 >>> d = distance(ma)
590 >>> exact = np.ma.MaskedArray([0, 0, 1, 0], [True, True, False, False])
591 >>> np.testing.assert_array_equal(d.mask, exact.mask)
592 >>> np.testing.assert_array_equal(d, exact)
593
594 Circular level set
595
596 >>> N = 50
597 >>> X, Y = np.meshgrid(np.linspace(-1, 1, N), np.linspace(-1, 1, N))
598 >>> r = 0.5
599 >>> dx = 2.0 / (N - 1)
600 >>> phi = (X) ** 2 + (Y) ** 2 - r ** 2
601 >>> d = distance(phi, dx, self_test=True)
602 >>> exact = np.sqrt(X ** 2 + Y ** 2) - r
603 >>> np.testing.assert_allclose(d, exact, atol=dx)
604
605 Planar level set
606
607 >>> N = 50
608 >>> X, Y = np.meshgrid(np.linspace(-1, 1, N), np.linspace(-1, 1, N))
609 >>> dx = 2.0 / (N - 1)
610 >>> phi = np.ones_like(X)
611 >>> phi[0, :] = -1
612 >>> d = distance(phi, dx, self_test=True)
613 >>> exact = Y + 1 - dx / 2.0
614 >>> np.testing.assert_allclose(d, exact)
615
616 Masked input
617
618 >>> N = 50
619 >>> X, Y = np.meshgrid(np.linspace(-1, 1, N), np.linspace(-1, 1, N))
620 >>> dx = 2.0 / (N - 1)
621 >>> phi = np.ones_like(X)
622 >>> phi[0, 0] = -1
623 >>> mask = np.logical_and(abs(X) < 0.25, abs(Y) < 0.25)
624 >>> mphi = np.ma.MaskedArray(phi.copy(), mask)
625 >>> d0 = distance(phi, dx, self_test=True)
626 >>> d = distance(mphi, dx, self_test=True)
627 >>> d0[mask] = 0
628 >>> d[mask] = 0
629 >>> shadow = d0 - d
630 >>> bsh = abs(shadow) > 0.001
631 >>> diff = (bsh).sum()
632
633 >>> assert diff > 635 and diff < 645
634
635 Test Eikonal solution
636
637 >>> N = 50
638 >>> X, Y = np.meshgrid(np.linspace(-1, 1, N), np.linspace(-1, 1, N))
639 >>> r = 0.5
640 >>> dx = 2.0 / (N - 1)
641 >>> phi = (X) ** 2 + (Y) ** 2 - r ** 2
642 >>> speed = np.ones_like(phi) * 2
643 >>> t = travel_time(phi, speed, dx)
644 >>> exact = 0.5 * np.abs(np.sqrt(X ** 2 + Y ** 2) - 0.5)
645
646 >>> np.testing.assert_allclose(t, exact, atol=dx)
647
648 Test 1d
649
650 >>> N = 100
651 >>> X = np.linspace(-1.0, 1.0, N)
652 >>> dx = 2.0 / (N - 1)
653 >>> phi = np.zeros_like(X)
654 >>> phi[X < 0] = -1
655 >>> phi[X > 0] = 1
656 >>> d = distance(phi, dx, self_test=True)
657
658 >>> np.testing.assert_allclose(d, X)
659
660 Test 3d
661
662 >>> N = 15
663 >>> X = np.linspace(-1, 1, N)
664 >>> Y = np.linspace(-1, 1, N)
665 >>> Z = np.linspace(-1, 1, N)
666 >>> phi = np.ones((N, N, N))
667 >>> phi[0, 0, 0] = -1.0
668 >>> dx = 2.0 / (N - 1)
669 >>> d = distance(phi, dx, self_test=True)
670
671 >>> exact = np.sqrt((X + 1) ** 2 +
672 ... (Y + 1)[:, np.newaxis] ** 2 +
673 ... (Z + 1)[:, np.newaxis, np.newaxis] ** 2)
674
675 >>> np.testing.assert_allclose(d, exact, atol=dx)
676
677 Test default dx
678
679 >>> N = 50
680 >>> X, Y = np.meshgrid(np.linspace(-1, 1, N), np.linspace(-1, 1, N))
681 >>> r = 0.5
682 >>> phi = (X) ** 2 + (Y) ** 2 - r ** 2
683 >>> speed = np.ones_like(phi) * 2
684 >>> out = travel_time(phi, speed, self_test=True)
685
686 Test non-square grid and dx different in different directions
687
688 >>> N = 50
689 >>> NX, NY = N, 5 * N
690 >>> X, Y = np.meshgrid(np.linspace(-1, 1, NY), np.linspace(-1, 1, NX))
691 >>> r = 0.5
692 >>> phi = X ** 2 + Y ** 2 - r ** 2
693 >>> dx = [2.0 / (NX - 1), 2.0 / (NY - 1)]
694 >>> d = distance(phi, dx, self_test=True)
695 >>> exact = np.sqrt(X ** 2 + Y ** 2) - r
696
697 >>> np.testing.assert_allclose(d, exact, atol=1.3*max(dx))
698
699
700 No zero level set test
701
702 >>> distance([1, 1], self_test=False)
703 Traceback (most recent call last):
704 ...
705 ValueError: the array phi contains no zero contour (no zero level set)
706
707 Shape mismatch test
708
709 >>> travel_time([-1, 1], [2])
710 Traceback (most recent call last):
711 ...
712 ValueError: phi and speed must have the same shape
713
714 Speed wrong type test
715
716 >>> travel_time([0, 0, 1, 1], 2)
717 Traceback (most recent call last):
718 ...
719 ValueError: speed must be a 1D to 12-D array of doubles
720
721 dx mismatch test
722
723 >>> travel_time([-1, 1], [2, 2], [2, 2, 2, 2])
724 Traceback (most recent call last):
725 ...
726 ValueError: dx must be of length len(phi.shape)
727
728 Test c error handling
729
730 >>> distance([-1, 1], self_test=44)
731 Traceback (most recent call last):
732 ...
733 ValueError: self_test must be 0 or 1
734
735 Check array type test
736
737 >>> distance(np.array(["a", "b"]))
738 Traceback (most recent call last):
739 ...
740 ValueError: phi must be a 1 to 12-D array of doubles
741
742 >>> from skfmm import heap
743 >>> h = heap(10,True)
744 >>> h.push(0,0.2)
745 0
746 >>> h.push(1,0.3)
747 1
748 >>> h.push(2,0.1)
749 2
750 >>> h.update(1, 0.01)
751 >>> h.pop()
752 (1, 0.01)
753 >>> h.pop()
754 (2, 0.1)
755 >>> h.pop()
756 (0, 0.2)
757 >>> h.empty()
758 True
759 >>> h.pop()
760 Traceback (most recent call last):
761 ...
762 RuntimeError: heap pop error: empty heap
763 <BLANKLINE>
764
765 Test narrow optional argument.
766
767 >>> phi = np.array([-1,-1,-1,1,1,1])
768 >>> d = distance(phi, narrow=1.0)
769 >>> d.data[2:-2]
770 array([-0.5, 0.5])
771 >>> assert (d.mask == [ True, True, False, False, True, True]).all()
772 >>> N = 50
773 >>> X, Y = np.meshgrid(np.linspace(-1, 1, N), np.linspace(-1, 1, N))
774 >>> r = 0.5
775 >>> dx = 2.0 / (N - 1)
776 >>> phi = (X) ** 2 + (Y) ** 2 - r ** 2
777 >>> exact = np.sqrt(X ** 2 + Y ** 2) - r
778
779 >>> d = distance(phi, dx)
780 >>> bandwidth=5*dx
781 >>> d2 = distance(phi, dx, narrow=bandwidth)
782 >>> np.testing.assert_allclose(d, exact, atol=dx)
783 >>> # make sure we get a normal array if there are no points outside the narrow band
784 >>> np.testing.assert_allclose(distance(phi, dx, narrow=1000*dx), exact, atol=dx)
785
786 >>> assert (d2<bandwidth).all()
787 >>> assert type(d2) is np.ma.masked_array
788
789 >>> speed = np.ones_like(phi)
790 >>> speed[X>0] = 1.8
791 >>> t = travel_time(phi, speed, dx)
792 >>> t2 = travel_time(phi, speed, dx, narrow=bandwidth)
793 >>> assert type(t2) is np.ma.masked_array
794 >>> assert (t2<bandwidth).all()
795
796 >>> speed = np.ones_like(phi)
797 >>> speed = X + Y
798 >>> ed, ev = extension_velocities(phi, speed, dx)
799 >>> ed2, ev2 = extension_velocities(phi, speed, dx, narrow=bandwidth)
800 >>> assert type(ed2) is np.ma.masked_array
801 >>> assert type(ev2) is np.ma.masked_array
802 >>> assert (ed2<bandwidth).all()
803 >>> assert ed2.shape == ed.shape == ev.shape == ev2.shape
804 >>> distance(phi, dx, narrow=-1)
805 Traceback (most recent call last):
806 ...
807 ValueError: parameter "narrow" must be greater than or equal to zero.
808 >>> # make sure the narrow options works with an existing mask.
809 >>> mask = abs(X)<0.25
810 >>> d3 = distance(np.ma.masked_array(phi, mask), dx, narrow=bandwidth)
811 >>> assert (d3.mask[mask]==True).all()
812 >>> assert d3.mask.sum() > mask.sum()
813
814 Testing periodic argument
815
816 >>> X, Y = np.meshgrid(np.linspace(-2,2,200), np.linspace(-2,2,200))
817 >>> phi = -1*np.ones_like(X); phi[X**2+(Y-0.9)**2<0.5] = 1.0
818 >>> speed = np.ones_like(X); speed[(X-0.9)**2+Y**2<1.0] = 2.0
819 >>> np.allclose(distance(phi),distance(phi,periodic=False)) and np.allclose(distance(phi),distance(phi,periodic=(0,0)))
820 True
821 >>> np.allclose(travel_time(phi,speed),travel_time(phi,speed,periodic=False)) and np.allclose(travel_time(phi,speed),travel_time(phi,speed,periodic=(0,0)))
822 True
823 >>> phi = -1*np.ones_like(X); phi[X**2+Y**2<0.5] = 1.0
824 >>> speed = np.ones_like(X); speed[X**2+Y**2<1.0] = 2.0
825 >>> np.allclose(distance(phi),distance(phi,periodic=True)) and np.allclose(distance(phi),distance(phi,periodic=(1,1)))
826 True
827 >>> np.allclose(travel_time(phi,speed),travel_time(phi,speed,periodic=True)) and np.allclose(travel_time(phi,speed),travel_time(phi,speed,periodic=(1,1)))
828 True
829 >>> np.allclose(travel_time(phi,speed),travel_time(phi,speed,periodic=True)) and np.allclose(travel_time(phi,speed),travel_time(phi,speed,periodic=[1,1]))
830 True
831 >>> np.allclose(travel_time(phi,speed),travel_time(phi,speed,periodic=True)) and np.allclose(travel_time(phi,speed),travel_time(phi,speed,periodic=[True,True]))
832 True
833 >>> phi = -1*np.ones_like(X); phi[X**2+(Y-0.9)**2<0.5] = 1.0
834 >>> speed = np.ones_like(X); speed[(X-0.9)**2+Y**2<1.0] = 2.0
835 >>> np.allclose(distance(np.roll(phi,137,axis=0),periodic=True),np.roll(distance(phi,periodic=True),137,axis=0))
836 True
837 >>> np.allclose(travel_time(np.roll(phi,-77,axis=1),np.roll(speed,-77,axis=1),periodic=True),np.roll(travel_time(phi,speed,periodic=True),-77,axis=1))
838 True
839
840 >>> phi=[1,-1,1,1,1,1]
841 >>> speed=[4,1,2,2,2,2]
842 >>> np.allclose(extension_velocities(phi,speed)[1],(2.5,2.5,1.5,1.5,1.5,1.5))
843 True
844 >>> np.allclose(extension_velocities(phi,speed,periodic=True)[1],(2.5,2.5,1.5,1.5,1.5,2.5))
845 True
846
847
848 This is issue #18,
849
850 >>> phi = np.array([[ 1, 1, -1, -1, -1, -1, 1],
851 ... [ 3, 1, -1, -1, -1, -1, 1],
852 ... [ 3, 3, 1, 1, 1, 1, 3],
853 ... [ 3, 3, 3, 3, 3, 3, 3],
854 ... [ 3, 3, 3, 3, 3, 3, 3]])
855 >>> speed = np.array([[ 1. , 1. , 0.057, 0.128, 0.037, 0.039, 1. ],
856 ... [ 1. , 1. , 0.199, 0.408, 0.997, 0.688, 1. ],
857 ... [ 1. , 1. , 1. , 1. , 1. , 1. , 1. ],
858 ... [ 1. , 1. , 1. , 1. , 1. , 1. , 1. ],
859 ... [ 1. , 1. , 1. , 1. , 1. , 1. , 1. ]])
860 >>> assert not travel_time(phi,speed)[0][3] == 0
861
862 >>> phi = np.array([[1, -1, -1],
863 ... [0, 0, -1],
864 ... [0, 0, 1]])
865 >>> value = 0.01
866 >>> speed = np.array([[ 1, value, 0.1],
867 ... [ 0, 0, 1. ],
868 ... [ 0, 0, 1. ]])
869 >>> phi = np.ma.MaskedArray(phi, phi==0)
870 >>> tt = travel_time(phi,speed)
871 >>> tt.fill_value=0
872 >>> np.testing.assert_allclose(tt.data, ((0.5, 50, 7.5),
873 ... (0, 0, 0.5),
874 ... (0, 0, 0.5)))
875
876 This is from Pull Request #57:
877
878 >>> a = np.array([[[600, 399, 641], [607, 605, 796], [602, 641, 797], [602, 658, 814]], [[272, -1, 398], [208, 282, 539], [209, 285, 513], [208, 298, 519]], [[-19, 51, 307], [-191, 2, 403], [-171, 5, 325], [-172, 3, 318]]])
879
880 >>> d = distance(a)
881 >>> assert not (d==0).any()
882
883 A 2D version of this bug was also discovered
884
885 >>> a = np.array([[399, -1, 51, 10.0], [605, 282, 2, -3], [641, 285, 5, -100], [658, 298, 3, -3]])
886 >>> d = distance(a)
887 >>> assert not (d==0).any()
888
889 """
890
891 def test(verbose=None):
892 r"""
893 Run all the doctests available.
894 """
895 import doctest
896 import skfmm
897 fail0, test0 = doctest.testmod(skfmm, verbose=verbose)
898 fail1, test1 = doctest.testfile("heap.py", verbose=verbose)
899
900 print ("Summary: {} tests run {} failures".format(test0+test1,
901 fail0+fail1))
902 return fail0+fail1