Debian Codegraph @

python/test/unit/function/test_expression.py

raw ◀ ▶
1 Debian patch touch this file
1 """Unit tests for the function library"""
2
3 # Copyright (C) 2007-2014 Anders Logg
4 #
5 # This file is part of DOLFIN.
6 #
7 # DOLFIN is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Lesser General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # DOLFIN is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public License
18 # along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.
19 #
20 # Modified by Benjamin Kehlet 2012
21
22 import pytest
23 from dolfin import *
24 from math import sin, cos, exp, tan
•25 from numpy import array, zeros
26 import numpy as np
27
28 from dolfin_utils.test import fixture, skip_in_parallel
29
30 @fixture
31 def mesh():
32 return UnitCubeMesh(8, 8, 8)
33
34
35 @fixture
36 def V(mesh):
37 return FunctionSpace(mesh, 'CG', 1)
38
39
40 @fixture
41 def W(mesh):
42 return VectorFunctionSpace(mesh, 'CG', 1)
43
44
45 def test_arbitrary_eval(mesh):
46 class F0(UserExpression):
47 def eval(self, values, x):
48 values[0] = sin(3.0*x[0])*sin(3.0*x[1])*sin(3.0*x[2])
49
50 f0 = F0(name="f0", label="My expression", degree=2)
51 f1 = Expression("a*sin(3.0*x[0])*sin(3.0*x[1])*sin(3.0*x[2])",
52 degree=2, a=1., name="f1")
53 x = array([0.31, 0.32, 0.33])
54 u00 = zeros(1)
55 u01 = zeros(1)
56 u10 = zeros(1)
57 u20 = zeros(1)
58
59 # Check usergeneration of name and label
60 assert f0.name() == "f0"
61 assert str(f0) == "f0"
62 assert f0.label() == "My expression"
63 assert f1.name() == "f1"
64 assert str(f1) == "f1"
65 assert f1.label() == "User defined expression"
66
67 # Check outgeneration of name
68 count = int(F0(degree=0).name()[2:])
69 assert F0(degree=0).count() == count + 1
70
71 # Test original and vs short evaluation
72 f0.eval(u00, x)
73 f0(x, values=u01)
74 assert round(u00[0] - u01[0], 7) == 0
75
76 # Evaluation with and without return value
77 f1(x, values=u10)
78 u11 = f1(x)
79 assert round(u10[0] - u11, 7) == 0
80
81 # Test *args for coordinate argument
82 f1(0.31, 0.32, 0.33, values=u20)
83 u21 = f0(0.31, 0.32, 0.33)
84 assert round(u20[0] - u21, 7) == 0
85
86 # Test Point evaluation
87 p0 = Point(0.31, 0.32, 0.33)
88 u21 = f1(p0)
89 assert round(u20[0] - u21, 7) == 0
90
91 same_result = sin(3.0*x[0])*sin(3.0*x[1])*sin(3.0*x[2])
92 assert round(u00[0] - same_result, 7) == 0
93 assert round(u11 - same_result, 7) == 0
94 assert round(u21 - same_result, 7) == 0
95
96 # For MUMPS, increase estimated require memory increase. Typically
97 # required for small meshes in 3D (solver is called by 'project')
98 if has_petsc():
99 PETScOptions.set("mat_mumps_icntl_14", 40)
100
101 x = (mesh.coordinates()[0]+mesh.coordinates()[1])/2
102 f2 = Expression("1.0 + 3.0*x[0] + 4.0*x[1] + 0.5*x[2]", degree=2)
103 V2 = FunctionSpace(mesh, 'CG', 2)
104 g0 = interpolate(f2, V=V2)
105 g1 = project(f2, V=V2)
106
107 u3 = f2(x)
108 u4 = g0(x)
109 u5 = g1(x)
110 assert round(u3 - u4, 7) == 0
111 assert round(u3 - u5, 4) == 0
112
113 if has_petsc():
114 PETScOptions.clear("mat_mumps_icntl_14")
115
116
117 def test_ufl_eval():
118 class F0(UserExpression):
119 def eval(self, values, x):
120 values[0] = sin(3.0*x[0])*sin(3.0*x[1])*sin(3.0*x[2])
121
122 class V0(UserExpression):
123 def eval(self, values, x):
124 values[0] = x[0]**2
125 values[1] = x[1]**2
126 values[2] = x[2]**2
127
128 def value_shape(self):
129 return (3,)
130
131 f0 = F0(degree=2)
132 v0 = V0(degree=2)
133
134 x = (2.0, 1.0, 3.0)
135
136 # Test ufl evaluation through mapping (overriding the Expression
137 # with N here):
138 def N(x):
139 return x[0]**2 + x[1] + 3*x[2]
140
141 assert f0(x, {f0: N}) == 14
142
143 a = f0**2
144 b = a(x, {f0: N})
145 assert b == 196
146
147 # Test ufl evaluation together with Expression evaluation by dolfin
148 # scalar
149 assert f0(x) == f0(*x)
150 assert (f0**2)(x) == f0(*x)**2
151 # vector
152 assert all(a == b for a, b in zip(v0(x), v0(*x)))
153 assert dot(v0, v0)(x) == sum(v**2 for v in v0(*x))
154 assert dot(v0, v0)(x) == 98
155
156
157 def test_overload_and_call_back(V, mesh):
158 class F0(UserExpression):
159 def eval(self, values, x):
160 values[0] = sin(3.0*x[0])*sin(3.0*x[1])*sin(3.0*x[2])
161
162 class F1(UserExpression):
163 def __init__(self, mesh, *arg, **kwargs):
164 super().__init__(*arg, **kwargs)
165 self.mesh = mesh
166
167 def eval_cell(self, values, x, cell):
168 c = Cell(self.mesh, cell.index)
169 values[0] = sin(3.0*x[0])*sin(3.0*x[1])*sin(3.0*x[2])
170
171 e0 = F0(degree=2)
172 e1 = F1(mesh, degree=2)
173 e2 = Expression("sin(3.0*x[0])*sin(3.0*x[1])*sin(3.0*x[2])", degree=2)
174
175 u0 = interpolate(e0, V)
176 u1 = interpolate(e1, V)
177 u2 = interpolate(e2, V)
178
179 s0 = norm(u0)
180 s1 = norm(u1)
181 s2 = norm(u2)
182
183 ref = 0.36557637568519191
184 assert round(s0 - ref, 7) == 0
185 assert round(s1 - ref, 7) == 0
186 assert round(s2 - ref, 7) == 0
187
188
189 def test_wrong_eval():
190 # Test wrong evaluation
191 class F0(UserExpression):
192 def eval(self, values, x):
193 values[0] = sin(3.0*x[0])*sin(3.0*x[1])*sin(3.0*x[2])
194
195 f0 = F0(degree=2)
196 f1 = Expression("sin(3.0*x[0])*sin(3.0*x[1])*sin(3.0*x[2])", degree=2)
197
198 for f in [f0, f1]:
199 with pytest.raises(TypeError):
200 f("s")
201 with pytest.raises(TypeError):
202 f([])
203 with pytest.raises(TypeError):
204 f(0.5, 0.5, 0.5, values=zeros(3, 'i'))
205 with pytest.raises(TypeError):
206 f([0.3, 0.2, []])
207 with pytest.raises(TypeError):
208 f(0.3, 0.2, {})
209 with pytest.raises(TypeError):
210 f(zeros(3), values=zeros(4))
211 with pytest.raises(TypeError):
212 f(zeros(4), values=zeros(3))
213
214
215 def test_vector_valued_expression_member_function(mesh):
216 V = FunctionSpace(mesh,'CG',1)
217 W = VectorFunctionSpace(mesh,'CG',1, dim=3)
218 fs = [
219 Expression(("1", "2", "3"), degree=1),
220 Constant((1, 2, 3)),
221 interpolate(Constant((1, 2, 3)), W),
222 ]
223 for f in fs:
224 u = Expression("f[0] + f[1] + f[2]", f=f, degree=1)
225 v = interpolate(u, V)
226 assert np.allclose(v.vector().get_local(), 6.0)
227 for g in fs:
228 u.f = g
229 v = interpolate(u, V)
230 assert np.allclose(v.vector().get_local(), 6.0)
231
232
233 def test_no_write_to_const_array():
234 class F1(UserExpression):
235 def eval(self, values, x):
236 x[0] = 1.0
237 values[0] = sin(3.0*x[0])*sin(3.0*x[1])*sin(3.0*x[2])
238
239 mesh = UnitCubeMesh(3, 3, 3)
240 f1 = F1(degree=1)
241 with pytest.raises(Exception):
242 assemble(f1*dx(mesh))
243
244
245 def test_compute_vertex_values(mesh):
246 from numpy import zeros, all, array
247
248 e0 = Expression("1", degree=0)
249 e1 = Expression(("1", "2", "3"), degree=0)
250
251 e0_values = e0.compute_vertex_values(mesh)
252 e1_values = e1.compute_vertex_values(mesh)
253
254 assert all(e0_values == 1)
255 assert all(e1_values[:mesh.num_vertices()] == 1)
256 assert all(e1_values[mesh.num_vertices():mesh.num_vertices()*2] == 2)
257 assert all(e1_values[mesh.num_vertices()*2:mesh.num_vertices()*3] == 3)
258
259
260 def test_runtime_exceptions():
261
262 def noDefaultValues():
263 Expression("a")
264
265 def wrongDefaultType():
266 Expression("a", a="1", degree=1)
267
268 def wrongParameterNames0():
269 Expression("foo", bar=1.0, degree=1)
270
271 def wrongParameterNames1():
272 Expression("user_parameters", user_parameters=1.0, degree=1)
273
274 with pytest.raises(RuntimeError):
275 noDefaultValues()
276 with pytest.raises(RuntimeError):
277 wrongDefaultType()
278 with pytest.raises(RuntimeError):
279 wrongParameterNames0()
280 with pytest.raises(RuntimeError):
281 wrongParameterNames1()
282
283
284 def test_fail_expression_compilation():
285 # Compilation failure only happens on one process,
286 # and involves a barrier to let the compilation finish
287 # before the other processes loads from disk.
288 # This tests that a failure can be caught without deadlock.
289
290 def invalidCppExpression():
291 Expression("/", degree=0)
292
293 with pytest.raises(RuntimeError):
294 invalidCppExpression()
295
296
297 def test_element_instantiation():
298 class F0(UserExpression):
299 def eval(self, values, x):
300 values[0] = 1.0
301
302 class F1(UserExpression):
303 def eval(self, values, x):
304 values[0] = 1.0
305 values[1] = 1.0
306
307 def value_shape(self):
308 return (2,)
309
310 class F2(UserExpression):
311 def eval(self, values, x):
312 values[0] = 1.0
313 values[1] = 1.0
314 values[2] = 1.0
315 values[3] = 1.0
316
317 def value_shape(self):
318 return (2, 2)
319
320 e0 = Expression("1", degree=0)
321 assert e0.ufl_element().cell() is None
322
323 e1 = Expression("1", cell=triangle, degree=0)
324 assert not e1.ufl_element().cell() is None
325
326 e2 = Expression("1", cell=triangle, degree=2)
327 assert e2.ufl_element().degree() == 2
328
329 e3 = Expression(["1", "1"], cell=triangle, degree=0)
330 assert isinstance(e3.ufl_element(), VectorElement)
331
332 e4 = Expression((("1", "1"), ("1", "1")), cell=triangle, degree=0)
333 assert isinstance(e4.ufl_element(), TensorElement)
334
335 f0 = F0(degree=0)
336 assert f0.ufl_element().cell() is None
337
338 f1 = F0(cell=triangle, degree=0)
339 assert not f1.ufl_element().cell() is None
340
341 f2 = F0(cell=triangle, degree=2)
342 assert f2.ufl_element().degree() == 2
343
344 f3 = F1(cell=triangle, degree=0)
345 assert isinstance(f3.ufl_element(), VectorElement)
346
347 f4 = F2(cell=triangle, degree=0)
348 assert isinstance(f4.ufl_element(), TensorElement)
349
350
351 def test_num_literal():
352 e0 = Expression("1e10", degree=0)
353 assert e0(0, 0, 0) == 1e10
354
355 e1 = Expression("1e-10", degree=0)
356 assert e1(0, 0, 0) == 1e-10
357
358 e2 = Expression("1e+10", degree=0)
359 assert e2(0, 0, 0) == 1e+10
360
361 e3 = Expression(".5", degree=0)
362 assert e3(0, 0, 0) == 0.5
363
364 e4 = Expression("x[0] * sin(.5)", degree=2)
365 assert e4(0, 0, 0) == 0.
366
367 e5 = Expression(["2*t0", "-t0"], t0=1.0, degree=0)
368 values = e5(0, 0, 0)
369 assert values[0] == 2.
370 assert values[1] == -1.
371
372
373 def test_name_space_usage(mesh):
374 e0 = Expression("std::sin(x[0])*cos(x[1])", degree=2)
375 e1 = Expression("sin(x[0])*std::cos(x[1])", degree=2)
376 assert round(assemble(e0*dx(mesh)) - assemble(e1*dx(mesh)), 7) == 0
377
378
379 def test_generic_function_attributes(mesh, V):
380 tc = Constant(2.0)
381 te = Expression("value", value=tc, degree=0)
382
383 assert round(tc(0) - te(0), 7) == 0
384 tc.assign(1.0)
385 assert round(tc(0) - te(0), 7) == 0
386
387 tf = Function(V)
388 tf.vector()[:] = 1.0
389
390 e0 = Expression(["2*t", "-t"], t=tc, degree=0)
391 e1 = Expression(["2*t0", "-t0"], t0=1.0, degree=0)
392 e2 = Expression("t", t=te, degree=0)
393 e3 = Expression("t", t=tf, degree=0)
394
395 assert (round(assemble(inner(e0, e0)*dx(mesh)) -
396 assemble(inner(e1, e1)*dx(mesh)), 7) == 0)
397
398 assert (round(assemble(inner(e2, e2)*dx(mesh)) -
399 assemble(inner(e3, e3)*dx(mesh)), 7) == 0)
400
401 tc.assign(3.0)
402 e1.t0 = float(tc)
403
404 assert (round(assemble(inner(e0, e0)*dx(mesh)) -
405 assemble(inner(e1, e1)*dx(mesh)), 7) == 0)
406
407 tc.assign(5.0)
408
409 assert assemble(inner(e2, e2)*dx(mesh)) != assemble(inner(e3, e3)*dx(mesh))
410
411 assert (round(assemble(e0[0]*dx(mesh)) -
412 assemble(2*e2*dx(mesh)), 7) == 0)
413
414 e2.t = e3.t
415
416 assert (round(assemble(inner(e2, e2)*dx(mesh)) -
417 assemble(inner(e3, e3)*dx(mesh)), 7) == 0)
418
419 W = FunctionSpace(mesh, V.ufl_element()*V.ufl_element())
420
421 # Test wrong kwargs
422 with pytest.raises(Exception):
423 Expression("t", t=mesh, degree=0)
424 with pytest.raises(Exception):
425 Expression("t", t=W, degree=0)
426
427 # Test using generic function parameter with wrong shape
428 f2 = Function(W)
429 e2.t = f2
430 if has_debug(): # The condition is caught by assertion
431 with pytest.raises(RuntimeError):
432 e2(0, 0)
433
434 # Test user_parameters assignment
435 assert "value" in te.user_parameters
436 te.user_parameters["value"] = Constant(5.0)
437 assert te(0.0) == 5.0
438
439 te.user_parameters.update(dict(value=Constant(3.0)))
440 assert te(0.0) == 3.0
441
442 te.user_parameters.update([("value", Constant(4.0))])
443 assert te(0.0) == 4.0
444
445 # Test wrong assignment
446 with pytest.raises(Exception):
447 te.user_parameters.__setitem__("value", 1.0)
448 with pytest.raises(KeyError):
449 te.user_parameters.__setitem__("values", 1.0)
450
451
452 def test_doc_string_eval():
453 """
454 This test tests all features documented in the doc string of
455 Expression. If this test breaks and it is fixed the corresponding fixes
456 need also be updated in the docstring.
457 """
458
459 square = UnitSquareMesh(10, 10)
460 V = VectorFunctionSpace(square, "CG", 1)
461
462 f0 = Expression('sin(x[0]) + cos(x[1])', degree=1)
463 f1 = Expression(('cos(x[0])', 'sin(x[1])'), element=V.ufl_element())
464 assert round(f0(0, 0) - sum(f1(0, 0)), 7) == 0
465
466 f2 = Expression((('exp(x[0])', 'sin(x[1])'),
467 ('sin(x[0])', 'tan(x[1])')), degree=1)
468 assert round(sum(f2(0, 0)) - 1.0, 7) == 0
469
470 f = Expression('A*sin(x[0]) + B*cos(x[1])', A=2.0, B=Constant(4.0),
471 degree=2)
472 assert round(f(pi/4, pi/4) - 6./sqrt(2), 7) == 0
473
474 f.A = 5.0
475 f.B = Expression("value", value=6.0, degree=0)
476 assert round(f(pi/4, pi/4) - 11./sqrt(2), 7) == 0
477
478 f.user_parameters["A"] = 1.0
479 f.user_parameters["B"] = Constant(5.0)
480 assert round(f(pi/4, pi/4) - 6./sqrt(2), 7) == 0
481
482
483
484 def test_doc_string_python_expressions(mesh):
485 """This test tests all features documented in the doc string of
486 Expression. If this test breaks and it is fixed the corresponding
487 fixes need also be updated in the docstring.
488
489 """
490
491 square = UnitSquareMesh(4, 4)
492
493 class MyExpression0(UserExpression):
494 def eval(self, value, x):
495 dx = x[0] - 0.5
496 dy = x[1] - 0.5
497 value[0] = 500.0*exp(-(dx*dx + dy*dy)/0.02)
498 value[1] = 250.0*exp(-(dx*dx + dy*dy)/0.01)
499
500 def value_shape(self):
501 return (2,)
502
503 f0 = MyExpression0(degree=2)
504 values = f0(0.2, 0.3)
505 dx = 0.2 - 0.5
506 dy = 0.3 - 0.5
507
508 assert round(values[0] - 500.0*exp(-(dx*dx + dy*dy)/0.02), 7) == 0
509 assert round(values[1] - 250.0*exp(-(dx*dx + dy*dy)/0.01), 7) == 0
510
511 ufc_cell_attrs = ["cell_shape", "index", "topological_dimension",
512 "geometric_dimension", "local_facet", "mesh_identifier"]
513
514 class MyExpression1(UserExpression):
515 def eval_cell(self_expr, value, x, ufc_cell):
516 # Check attributes in ufc cell
517 for attr in ufc_cell_attrs:
518 assert hasattr(ufc_cell, attr)
519
520 if ufc_cell.index > 10:
521 value[0] = 1.0
522 else:
523 value[0] = -1.0
524
525 f1 = MyExpression1(degree=0)
526 assemble(f1*ds(square))
527
528 class MyExpression2(UserExpression):
529 def __init__(self, mesh, domain, *arg, **kwargs):
530 super().__init__(*arg, **kwargs)
531 self._mesh = mesh
532 self._domain = domain
533
534 def eval(self, values, x):
535 pass
536
537 cell_data = MeshFunction('size_t', square, square.topology().dim())
538
539 P1 = FiniteElement("Lagrange", square.ufl_cell(), 1)
540 f3 = MyExpression2(square, cell_data, element=P1)
541
542 assert id(f3._mesh) == id(square)
543 assert id(f3._domain) == id(cell_data)
544
545 def test_rename():
546 c1 = Expression("1", degree=2)
547 c1.rename("constant1","")
548 assert c1.name()=="constant1"
549
550 def test_restrict(mesh, V):
551 from numpy import array
552
553 # Non-linear would be better
554 expr = Expression('x[0]+x[1]+x[2]', degree=1)
555
556 # Arbitrary cell and point within it.
557 cell = list(cells(mesh))[-1]
558 x = cell.midpoint()[:]
559
560 element = V.dolfin_element()
561 weights = expr.restrict(element, cell)
562
563 coords = array(cell.get_vertex_coordinates())
564 basis = element.evaluate_basis_all(x, coords, cell.orientation())
565
566 assert near(np.dot(weights, basis), x[0]+x[1]+x[2])