prompt
stringlengths
174
59.5k
completion
stringlengths
7
228
api
stringlengths
12
64
import os.path as op from sfepy.base.base import * from sfepy.base.conf import transform_variables, transform_fields from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def do_interpolation(m2, m1, data, field_name): """Interpolate data from m1 to m2. """ from sfepy.fem import Domain, Field, Variables fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = Domain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = Domain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.fem import Mesh, Domain, Field, Variables m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 = Domain('d1', m1) omega1 = d1.create_region('Omega', 'all') field1 = Field('scalar_tp', nm.float64, (1,1), omega1, approx_order=1) ff1 = {field1.name : field1} d2 = Domain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field('scalar_si', nm.float64, (1,1), omega2, approx_order=0) ff2 = {field2.name : field2} vv1 = Variables.from_conf(
transform_variables(variables1)
sfepy.base.conf.transform_variables
import os.path as op from sfepy.base.base import * from sfepy.base.conf import transform_variables, transform_fields from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def do_interpolation(m2, m1, data, field_name): """Interpolate data from m1 to m2. """ from sfepy.fem import Domain, Field, Variables fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = Domain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = Domain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.fem import Mesh, Domain, Field, Variables m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 = Domain('d1', m1) omega1 = d1.create_region('Omega', 'all') field1 = Field('scalar_tp', nm.float64, (1,1), omega1, approx_order=1) ff1 = {field1.name : field1} d2 = Domain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field('scalar_si', nm.float64, (1,1), omega2, approx_order=0) ff2 = {field2.name : field2} vv1 = Variables.from_conf(transform_variables(variables1), ff1) u1 = vv1['u'] u1.set_from_mesh_vertices(data) vv2 = Variables.from_conf(
transform_variables(variables2)
sfepy.base.conf.transform_variables
import os.path as op from sfepy.base.base import * from sfepy.base.conf import transform_variables, transform_fields from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def do_interpolation(m2, m1, data, field_name): """Interpolate data from m1 to m2. """ from sfepy.fem import Domain, Field, Variables fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = Domain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = Domain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx =
make_axis_rotation_matrix([0, 1, 0], angle)
sfepy.linalg.make_axis_rotation_matrix
#!/usr/bin/env python def configuration(parent_package='', top_path=None): import os.path as op from numpy.distutils.misc_util import Configuration from sfepy import Config site_config =
Config()
sfepy.Config
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh =
Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp')
sfepy.discrete.fem.Mesh.from_file
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain =
FEDomain('domain', mesh)
sfepy.discrete.fem.FEDomain
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field =
Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1)
sfepy.discrete.fem.Field.from_args
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1) u =
FieldVariable('u', 'unknown', field)
sfepy.discrete.FieldVariable
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1) u = FieldVariable('u', 'unknown', field) v =
FieldVariable('v', 'test', field, primary_var_name='u')
sfepy.discrete.FieldVariable
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_youngpoisson(dim=3, young=2, poisson=0.3)) # m = Material('m', D=stiffness_for_transIso(dim=3, Ex=2.5, Ez=2, vxy=0.25, vxz=0.3, Gxz=1.75)) integral =
Integral('i', order=1)
sfepy.discrete.Integral
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_youngpoisson(dim=3, young=2, poisson=0.3)) # m = Material('m', D=stiffness_for_transIso(dim=3, Ex=2.5, Ez=2, vxy=0.25, vxz=0.3, Gxz=1.75)) integral = Integral('i', order=1) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) eq =
Equation('balance', t1)
sfepy.discrete.Equation
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_youngpoisson(dim=3, young=2, poisson=0.3)) # m = Material('m', D=stiffness_for_transIso(dim=3, Ex=2.5, Ez=2, vxy=0.25, vxz=0.3, Gxz=1.75)) integral = Integral('i', order=1) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) eq = Equation('balance', t1) eqs =
Equations([eq])
sfepy.discrete.Equations
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_youngpoisson(dim=3, young=2, poisson=0.3)) # m = Material('m', D=stiffness_for_transIso(dim=3, Ex=2.5, Ez=2, vxy=0.25, vxz=0.3, Gxz=1.75)) integral = Integral('i', order=1) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) eq = Equation('balance', t1) eqs = Equations([eq]) Fixed = EssentialBC('Fixed', Bottom, {'u.all' : 0.0}) Displaced = EssentialBC('Displaced', Top, {'u.1' : 0.01, 'u.[0,2]' : 0.0}) ls =
ScipyDirect({})
sfepy.solvers.ls.ScipyDirect
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_youngpoisson(dim=3, young=2, poisson=0.3)) # m = Material('m', D=stiffness_for_transIso(dim=3, Ex=2.5, Ez=2, vxy=0.25, vxz=0.3, Gxz=1.75)) integral = Integral('i', order=1) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) eq = Equation('balance', t1) eqs = Equations([eq]) Fixed = EssentialBC('Fixed', Bottom, {'u.all' : 0.0}) Displaced = EssentialBC('Displaced', Top, {'u.1' : 0.01, 'u.[0,2]' : 0.0}) ls = ScipyDirect({}) nls_status =
IndexedStruct()
sfepy.base.base.IndexedStruct
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_youngpoisson(dim=3, young=2, poisson=0.3)) # m = Material('m', D=stiffness_for_transIso(dim=3, Ex=2.5, Ez=2, vxy=0.25, vxz=0.3, Gxz=1.75)) integral = Integral('i', order=1) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) eq = Equation('balance', t1) eqs = Equations([eq]) Fixed = EssentialBC('Fixed', Bottom, {'u.all' : 0.0}) Displaced = EssentialBC('Displaced', Top, {'u.1' : 0.01, 'u.[0,2]' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls =
Newton({}, lin_solver=ls, status=nls_status)
sfepy.solvers.nls.Newton
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_youngpoisson(dim=3, young=2, poisson=0.3)) # m = Material('m', D=stiffness_for_transIso(dim=3, Ex=2.5, Ez=2, vxy=0.25, vxz=0.3, Gxz=1.75)) integral = Integral('i', order=1) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) eq = Equation('balance', t1) eqs = Equations([eq]) Fixed = EssentialBC('Fixed', Bottom, {'u.all' : 0.0}) Displaced = EssentialBC('Displaced', Top, {'u.1' : 0.01, 'u.[0,2]' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb =
Problem('elasticity', equations=eqs)
sfepy.discrete.Problem
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_youngpoisson(dim=3, young=2, poisson=0.3)) # m = Material('m', D=stiffness_for_transIso(dim=3, Ex=2.5, Ez=2, vxy=0.25, vxz=0.3, Gxz=1.75)) integral = Integral('i', order=1) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) eq = Equation('balance', t1) eqs = Equations([eq]) Fixed = EssentialBC('Fixed', Bottom, {'u.all' : 0.0}) Displaced = EssentialBC('Displaced', Top, {'u.1' : 0.01, 'u.[0,2]' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs) pb.save_regions_as_groups('regions') pb.set_bcs(ebcs=Conditions([Fixed, Displaced])) pb.set_solver(nls) status =
IndexedStruct()
sfepy.base.base.IndexedStruct
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_youngpoisson(dim=3, young=2, poisson=0.3)) # m = Material('m', D=stiffness_for_transIso(dim=3, Ex=2.5, Ez=2, vxy=0.25, vxz=0.3, Gxz=1.75)) integral = Integral('i', order=1) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) eq = Equation('balance', t1) eqs = Equations([eq]) Fixed = EssentialBC('Fixed', Bottom, {'u.all' : 0.0}) Displaced = EssentialBC('Displaced', Top, {'u.1' : 0.01, 'u.[0,2]' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs) pb.save_regions_as_groups('regions') pb.set_bcs(ebcs=Conditions([Fixed, Displaced])) pb.set_solver(nls) status = IndexedStruct() ##### state = pb.solve(status=status, save_results=True, post_process_hook=post_process) out = state.create_output_dict() out = post_process(out, pb, state, extend=True) pb.save_state('postprocess.vtk', out=out) prb =
Probe(out,pb.domain.mesh)
sfepy.postprocess.probes_vtk.Probe
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=
stiffness_from_youngpoisson(dim=3, young=2, poisson=0.3)
sfepy.mechanics.matcoefs.stiffness_from_youngpoisson
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 25 09:19:35 2020 @author: dhulls """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser import numpy as nm import sys sys.path.append('.') from sfepy.base.base import IndexedStruct, Struct from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.postprocess.viewer import Viewer from sfepy.postprocess.probes_vtk import ProbeFromFile, Probe from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.matcoefs import stiffness_for_transIso from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson import numpy as np def shift_u_fun(ts, coors, bc=None, problem=None, shift=0.0): """ Define a displacement depending on the y coordinate. """ val = shift * coors[:,1]**2 return val helps = { 'show' : 'show the results figure', } def post_process(out, problem, state, extend=False): """ Calculate and output strain and stress for given displacements. """ ev = problem.evaluate stress = ev('ev_cauchy_stress.%d.Omega(m.D, u)' % (2), mode='el_avg', copy_materials=False, verbose=False) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) return out from sfepy import data_dir parser = ArgumentParser() parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) options = parser.parse_args() mesh = Mesh.from_file(data_dir + '/meshes/3d/cylinder.inp') domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') Bottom = domain.create_region('Bottom', 'vertices in (z < -0.049)', 'facet') Top = domain.create_region('Top', 'vertices in (z > 0.049)', 'facet') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=1) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = Material('m', D=stiffness_from_youngpoisson(dim=3, young=2, poisson=0.3)) # m = Material('m', D=stiffness_for_transIso(dim=3, Ex=2.5, Ez=2, vxy=0.25, vxz=0.3, Gxz=1.75)) integral = Integral('i', order=1) t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) eq = Equation('balance', t1) eqs = Equations([eq]) Fixed = EssentialBC('Fixed', Bottom, {'u.all' : 0.0}) Displaced = EssentialBC('Displaced', Top, {'u.1' : 0.01, 'u.[0,2]' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs) pb.save_regions_as_groups('regions') pb.set_bcs(ebcs=
Conditions([Fixed, Displaced])
sfepy.discrete.conditions.Conditions
""" Functions for a mesh refinement with hanging nodes. Notes ----- Using LCBCs with hanging nodes is not supported. """ from __future__ import absolute_import from six.moves import range, zip import numpy as nm from sfepy.base.base import assert_ from sfepy.discrete import Functions, Function from sfepy.discrete.fem import Mesh, FEDomain # Rows = facets of reference cell, columns = [sub_cell_i, local facet_i] refine_edges_2_4 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]]]) refine_faces_3_8 = nm.array([[[0, 0], [1, 0], [2, 0], [3, 0]], [[0, 1], [3, 2], [4, 2], [7, 1]], [[0, 2], [1, 1], [4, 1], [5, 2]], [[4, 0], [5, 0], [6, 0], [7, 0]], [[1, 2], [2, 1], [5, 1], [6, 2]], [[2, 2], [3, 1], [6, 1], [7, 2]]]) refine_edges_3_8 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]], [[4, 3], [5, 0]], [[5, 3], [6, 0]], [[6, 3], [7, 0]], [[7, 3], [4, 0]], [[0, 8], [4, 8]], [[1, 8], [5, 8]], [[2, 8], [6, 8]], [[3, 8], [7, 8]]]) def find_level_interface(domain, refine_flag): """ Find facets of the coarse mesh that are on the coarse-refined cell boundary. ids w.r.t. current mesh: - facets: global, local w.r.t. cells[:, 0], local w.r.t. cells[:, 1] - interface cells: - cells[:, 0] - cells to refine - cells[:, 1] - their facet sharing neighbors (w.r.t. both meshes) - cells[:, 2] - facet kind: 0 = face, 1 = edge """ if not refine_flag.any(): facets = nm.zeros((0, 3), dtype=nm.uint32) cells = nm.zeros((0, 3), dtype=nm.uint32) return facets, cells, 0, None, None def _get_refine(coors, domain=None): return nm.nonzero(refine_flag)[0] def _get_coarse(coors, domain=None): return nm.nonzero(1 - refine_flag)[0] get_refine =
Function('get_refine', _get_refine)
sfepy.discrete.Function
""" Functions for a mesh refinement with hanging nodes. Notes ----- Using LCBCs with hanging nodes is not supported. """ from __future__ import absolute_import from six.moves import range, zip import numpy as nm from sfepy.base.base import assert_ from sfepy.discrete import Functions, Function from sfepy.discrete.fem import Mesh, FEDomain # Rows = facets of reference cell, columns = [sub_cell_i, local facet_i] refine_edges_2_4 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]]]) refine_faces_3_8 = nm.array([[[0, 0], [1, 0], [2, 0], [3, 0]], [[0, 1], [3, 2], [4, 2], [7, 1]], [[0, 2], [1, 1], [4, 1], [5, 2]], [[4, 0], [5, 0], [6, 0], [7, 0]], [[1, 2], [2, 1], [5, 1], [6, 2]], [[2, 2], [3, 1], [6, 1], [7, 2]]]) refine_edges_3_8 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]], [[4, 3], [5, 0]], [[5, 3], [6, 0]], [[6, 3], [7, 0]], [[7, 3], [4, 0]], [[0, 8], [4, 8]], [[1, 8], [5, 8]], [[2, 8], [6, 8]], [[3, 8], [7, 8]]]) def find_level_interface(domain, refine_flag): """ Find facets of the coarse mesh that are on the coarse-refined cell boundary. ids w.r.t. current mesh: - facets: global, local w.r.t. cells[:, 0], local w.r.t. cells[:, 1] - interface cells: - cells[:, 0] - cells to refine - cells[:, 1] - their facet sharing neighbors (w.r.t. both meshes) - cells[:, 2] - facet kind: 0 = face, 1 = edge """ if not refine_flag.any(): facets = nm.zeros((0, 3), dtype=nm.uint32) cells = nm.zeros((0, 3), dtype=nm.uint32) return facets, cells, 0, None, None def _get_refine(coors, domain=None): return nm.nonzero(refine_flag)[0] def _get_coarse(coors, domain=None): return nm.nonzero(1 - refine_flag)[0] get_refine = Function('get_refine', _get_refine) get_coarse =
Function('get_coarse', _get_coarse)
sfepy.discrete.Function
""" Functions for a mesh refinement with hanging nodes. Notes ----- Using LCBCs with hanging nodes is not supported. """ from __future__ import absolute_import from six.moves import range, zip import numpy as nm from sfepy.base.base import assert_ from sfepy.discrete import Functions, Function from sfepy.discrete.fem import Mesh, FEDomain # Rows = facets of reference cell, columns = [sub_cell_i, local facet_i] refine_edges_2_4 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]]]) refine_faces_3_8 = nm.array([[[0, 0], [1, 0], [2, 0], [3, 0]], [[0, 1], [3, 2], [4, 2], [7, 1]], [[0, 2], [1, 1], [4, 1], [5, 2]], [[4, 0], [5, 0], [6, 0], [7, 0]], [[1, 2], [2, 1], [5, 1], [6, 2]], [[2, 2], [3, 1], [6, 1], [7, 2]]]) refine_edges_3_8 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]], [[4, 3], [5, 0]], [[5, 3], [6, 0]], [[6, 3], [7, 0]], [[7, 3], [4, 0]], [[0, 8], [4, 8]], [[1, 8], [5, 8]], [[2, 8], [6, 8]], [[3, 8], [7, 8]]]) def find_level_interface(domain, refine_flag): """ Find facets of the coarse mesh that are on the coarse-refined cell boundary. ids w.r.t. current mesh: - facets: global, local w.r.t. cells[:, 0], local w.r.t. cells[:, 1] - interface cells: - cells[:, 0] - cells to refine - cells[:, 1] - their facet sharing neighbors (w.r.t. both meshes) - cells[:, 2] - facet kind: 0 = face, 1 = edge """ if not refine_flag.any(): facets = nm.zeros((0, 3), dtype=nm.uint32) cells = nm.zeros((0, 3), dtype=nm.uint32) return facets, cells, 0, None, None def _get_refine(coors, domain=None): return nm.nonzero(refine_flag)[0] def _get_coarse(coors, domain=None): return nm.nonzero(1 - refine_flag)[0] get_refine = Function('get_refine', _get_refine) get_coarse = Function('get_coarse', _get_coarse) functions =
Functions([get_refine, get_coarse])
sfepy.discrete.Functions
""" Functions for a mesh refinement with hanging nodes. Notes ----- Using LCBCs with hanging nodes is not supported. """ from __future__ import absolute_import from six.moves import range, zip import numpy as nm from sfepy.base.base import assert_ from sfepy.discrete import Functions, Function from sfepy.discrete.fem import Mesh, FEDomain # Rows = facets of reference cell, columns = [sub_cell_i, local facet_i] refine_edges_2_4 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]]]) refine_faces_3_8 = nm.array([[[0, 0], [1, 0], [2, 0], [3, 0]], [[0, 1], [3, 2], [4, 2], [7, 1]], [[0, 2], [1, 1], [4, 1], [5, 2]], [[4, 0], [5, 0], [6, 0], [7, 0]], [[1, 2], [2, 1], [5, 1], [6, 2]], [[2, 2], [3, 1], [6, 1], [7, 2]]]) refine_edges_3_8 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]], [[4, 3], [5, 0]], [[5, 3], [6, 0]], [[6, 3], [7, 0]], [[7, 3], [4, 0]], [[0, 8], [4, 8]], [[1, 8], [5, 8]], [[2, 8], [6, 8]], [[3, 8], [7, 8]]]) def find_level_interface(domain, refine_flag): """ Find facets of the coarse mesh that are on the coarse-refined cell boundary. ids w.r.t. current mesh: - facets: global, local w.r.t. cells[:, 0], local w.r.t. cells[:, 1] - interface cells: - cells[:, 0] - cells to refine - cells[:, 1] - their facet sharing neighbors (w.r.t. both meshes) - cells[:, 2] - facet kind: 0 = face, 1 = edge """ if not refine_flag.any(): facets = nm.zeros((0, 3), dtype=nm.uint32) cells = nm.zeros((0, 3), dtype=nm.uint32) return facets, cells, 0, None, None def _get_refine(coors, domain=None): return nm.nonzero(refine_flag)[0] def _get_coarse(coors, domain=None): return nm.nonzero(1 - refine_flag)[0] get_refine = Function('get_refine', _get_refine) get_coarse = Function('get_coarse', _get_coarse) functions = Functions([get_refine, get_coarse]) region0 = domain.create_region('coarse', 'cells by get_coarse', functions=functions, add_to_regions=False, allow_empty=True) region1 = domain.create_region('refine', 'cells by get_refine', functions=functions, add_to_regions=False) cmesh = domain.mesh.cmesh dim = cmesh.dim if dim == 2: oe = 0 facets = nm.intersect1d(region0.facets, region1.facets) cmesh.setup_connectivity(dim - 1, dim) cells, offs = cmesh.get_incident(dim, facets, dim - 1, ret_offsets=True) assert_((nm.diff(offs) == 2).all()) ii = cmesh.get_local_ids(facets, dim - 1, cells, offs, dim) ii = ii.reshape((-1, 2)) cells = cells.reshape((-1, 2)) ii = nm.where(refine_flag[cells], ii[:, :1], ii[:, 1:]) cells = nm.where(refine_flag[cells], cells[:, :1], cells[:, 1:]) facets = nm.c_[facets, ii] cells = nm.c_[cells, nm.zeros_like(cells[:, 1])] else: # if dim == 3: gel = domain.geom_els['3_8'] epf = gel.get_edges_per_face() cmesh.setup_connectivity(dim, dim) fc, coffs = cmesh.get_incident(dim, region1.cells, dim, ret_offsets=True) cc = nm.repeat(region1.cells, nm.diff(coffs)) aux = nm.c_[cc, fc] """ nnn[:, 0] cells to refine, nnn[:, 1] non-refined neighbours, nnn[:, 2] neighbour kind : 0 face, 1 edge. """ nn = aux[refine_flag[fc] == 0] cf = nn[:, 0].copy().astype(nm.uint32) cc = nn[:, 1].copy().astype(nm.uint32) vc, vco = cmesh.get_incident(0, cc, dim, ret_offsets=True) vf, vfo = cmesh.get_incident(0, cf, dim, ret_offsets=True) vc = vc.reshape((-1, 8)) vf = vf.reshape((-1, 8)) nnn = [] oe = 0 ov = nn.shape[0] for ii in range(vc.shape[0]): aux = set(vc[ii]).intersection(vf[ii]) nc = len(aux) if nc == 1: nnn.append((0, 0, 2)) ov -= 1 elif nc == 4: nnn.append((nn[ii, 0], nn[ii, 1], 0)) oe += 1 else: nnn.append((nn[ii, 0], nn[ii, 1], 1)) nnn = nm.array(nnn) if nnn.shape[0] == 0: facets = nm.zeros((0, 3), dtype=nm.uint32) cells = nm.zeros((0, 4), dtype=nm.uint32) return facets, cells, 0, region0, region1 # Sort by neighbour kind, skip vertex-only neighbours. ii = nm.argsort(nnn[:, 2]) nnn = nnn[ii][:ov] cf = cf[ii][:ov] cc = cc[ii][:ov] ec, eco = cmesh.get_incident(1, cc, dim, ret_offsets=True) ef, efo = cmesh.get_incident(1, cf, dim, ret_offsets=True) ec = ec.reshape((-1, 12)) ef = ef.reshape((-1, 12)) fc, fco = cmesh.get_incident(2, cc, dim, ret_offsets=True) ff, ffo = cmesh.get_incident(2, cf, dim, ret_offsets=True) fc = fc.reshape((-1, 6)) ff = ff.reshape((-1, 6)) emask = nm.zeros((domain.shape.n_el, 12), dtype=nm.bool) ffs = [] for ii in range(oe): facet = nm.intersect1d(fc[ii], ff[ii])[0] i1 = nm.where(ff[ii] == facet)[0][0] i0 = nm.where(fc[ii] == facet)[0][0] ffs.append((facet, i1, i0)) emask[nnn[ii, 0], epf[i1]] = True for ii in range(oe, nnn.shape[0]): facet = nm.intersect1d(ec[ii], ef[ii])[0] i1 = nm.where(ef[ii] == facet)[0][0] i0 = nm.where(ec[ii] == facet)[0][0] ffs.append((facet, i1, i0)) ffs = nm.array(ffs) ie = nm.where(nnn[:, 2] == 1)[0] ennn = nnn[ie] effs = ffs[ie] omit = ie[emask[ennn[:, 0], effs[:, 1]]] valid = nm.ones(nnn.shape[0], dtype=nm.bool) valid[omit] = False cells = nnn[valid] facets = ffs[valid] return facets, cells, oe, region0, region1 def refine_region(domain0, region0, region1): """ Coarse cell sub_cells[ii, 0] in mesh0 is split into sub_cells[ii, 1:] in mesh1. The new fine cells are interleaved among the original coarse cells so that the indices of the coarse cells do not change. The cell groups are preserved. The vertex groups are preserved only in the coarse (non-refined) cells. """ if region1 is None: return domain0, None mesh0 = domain0.mesh mesh1 =
Mesh.from_region(region1, mesh0)
sfepy.discrete.fem.Mesh.from_region
""" Functions for a mesh refinement with hanging nodes. Notes ----- Using LCBCs with hanging nodes is not supported. """ from __future__ import absolute_import from six.moves import range, zip import numpy as nm from sfepy.base.base import assert_ from sfepy.discrete import Functions, Function from sfepy.discrete.fem import Mesh, FEDomain # Rows = facets of reference cell, columns = [sub_cell_i, local facet_i] refine_edges_2_4 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]]]) refine_faces_3_8 = nm.array([[[0, 0], [1, 0], [2, 0], [3, 0]], [[0, 1], [3, 2], [4, 2], [7, 1]], [[0, 2], [1, 1], [4, 1], [5, 2]], [[4, 0], [5, 0], [6, 0], [7, 0]], [[1, 2], [2, 1], [5, 1], [6, 2]], [[2, 2], [3, 1], [6, 1], [7, 2]]]) refine_edges_3_8 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]], [[4, 3], [5, 0]], [[5, 3], [6, 0]], [[6, 3], [7, 0]], [[7, 3], [4, 0]], [[0, 8], [4, 8]], [[1, 8], [5, 8]], [[2, 8], [6, 8]], [[3, 8], [7, 8]]]) def find_level_interface(domain, refine_flag): """ Find facets of the coarse mesh that are on the coarse-refined cell boundary. ids w.r.t. current mesh: - facets: global, local w.r.t. cells[:, 0], local w.r.t. cells[:, 1] - interface cells: - cells[:, 0] - cells to refine - cells[:, 1] - their facet sharing neighbors (w.r.t. both meshes) - cells[:, 2] - facet kind: 0 = face, 1 = edge """ if not refine_flag.any(): facets = nm.zeros((0, 3), dtype=nm.uint32) cells = nm.zeros((0, 3), dtype=nm.uint32) return facets, cells, 0, None, None def _get_refine(coors, domain=None): return nm.nonzero(refine_flag)[0] def _get_coarse(coors, domain=None): return nm.nonzero(1 - refine_flag)[0] get_refine = Function('get_refine', _get_refine) get_coarse = Function('get_coarse', _get_coarse) functions = Functions([get_refine, get_coarse]) region0 = domain.create_region('coarse', 'cells by get_coarse', functions=functions, add_to_regions=False, allow_empty=True) region1 = domain.create_region('refine', 'cells by get_refine', functions=functions, add_to_regions=False) cmesh = domain.mesh.cmesh dim = cmesh.dim if dim == 2: oe = 0 facets = nm.intersect1d(region0.facets, region1.facets) cmesh.setup_connectivity(dim - 1, dim) cells, offs = cmesh.get_incident(dim, facets, dim - 1, ret_offsets=True) assert_((nm.diff(offs) == 2).all()) ii = cmesh.get_local_ids(facets, dim - 1, cells, offs, dim) ii = ii.reshape((-1, 2)) cells = cells.reshape((-1, 2)) ii = nm.where(refine_flag[cells], ii[:, :1], ii[:, 1:]) cells = nm.where(refine_flag[cells], cells[:, :1], cells[:, 1:]) facets = nm.c_[facets, ii] cells = nm.c_[cells, nm.zeros_like(cells[:, 1])] else: # if dim == 3: gel = domain.geom_els['3_8'] epf = gel.get_edges_per_face() cmesh.setup_connectivity(dim, dim) fc, coffs = cmesh.get_incident(dim, region1.cells, dim, ret_offsets=True) cc = nm.repeat(region1.cells, nm.diff(coffs)) aux = nm.c_[cc, fc] """ nnn[:, 0] cells to refine, nnn[:, 1] non-refined neighbours, nnn[:, 2] neighbour kind : 0 face, 1 edge. """ nn = aux[refine_flag[fc] == 0] cf = nn[:, 0].copy().astype(nm.uint32) cc = nn[:, 1].copy().astype(nm.uint32) vc, vco = cmesh.get_incident(0, cc, dim, ret_offsets=True) vf, vfo = cmesh.get_incident(0, cf, dim, ret_offsets=True) vc = vc.reshape((-1, 8)) vf = vf.reshape((-1, 8)) nnn = [] oe = 0 ov = nn.shape[0] for ii in range(vc.shape[0]): aux = set(vc[ii]).intersection(vf[ii]) nc = len(aux) if nc == 1: nnn.append((0, 0, 2)) ov -= 1 elif nc == 4: nnn.append((nn[ii, 0], nn[ii, 1], 0)) oe += 1 else: nnn.append((nn[ii, 0], nn[ii, 1], 1)) nnn = nm.array(nnn) if nnn.shape[0] == 0: facets = nm.zeros((0, 3), dtype=nm.uint32) cells = nm.zeros((0, 4), dtype=nm.uint32) return facets, cells, 0, region0, region1 # Sort by neighbour kind, skip vertex-only neighbours. ii = nm.argsort(nnn[:, 2]) nnn = nnn[ii][:ov] cf = cf[ii][:ov] cc = cc[ii][:ov] ec, eco = cmesh.get_incident(1, cc, dim, ret_offsets=True) ef, efo = cmesh.get_incident(1, cf, dim, ret_offsets=True) ec = ec.reshape((-1, 12)) ef = ef.reshape((-1, 12)) fc, fco = cmesh.get_incident(2, cc, dim, ret_offsets=True) ff, ffo = cmesh.get_incident(2, cf, dim, ret_offsets=True) fc = fc.reshape((-1, 6)) ff = ff.reshape((-1, 6)) emask = nm.zeros((domain.shape.n_el, 12), dtype=nm.bool) ffs = [] for ii in range(oe): facet = nm.intersect1d(fc[ii], ff[ii])[0] i1 = nm.where(ff[ii] == facet)[0][0] i0 = nm.where(fc[ii] == facet)[0][0] ffs.append((facet, i1, i0)) emask[nnn[ii, 0], epf[i1]] = True for ii in range(oe, nnn.shape[0]): facet = nm.intersect1d(ec[ii], ef[ii])[0] i1 = nm.where(ef[ii] == facet)[0][0] i0 = nm.where(ec[ii] == facet)[0][0] ffs.append((facet, i1, i0)) ffs = nm.array(ffs) ie = nm.where(nnn[:, 2] == 1)[0] ennn = nnn[ie] effs = ffs[ie] omit = ie[emask[ennn[:, 0], effs[:, 1]]] valid = nm.ones(nnn.shape[0], dtype=nm.bool) valid[omit] = False cells = nnn[valid] facets = ffs[valid] return facets, cells, oe, region0, region1 def refine_region(domain0, region0, region1): """ Coarse cell sub_cells[ii, 0] in mesh0 is split into sub_cells[ii, 1:] in mesh1. The new fine cells are interleaved among the original coarse cells so that the indices of the coarse cells do not change. The cell groups are preserved. The vertex groups are preserved only in the coarse (non-refined) cells. """ if region1 is None: return domain0, None mesh0 = domain0.mesh mesh1 = Mesh.from_region(region1, mesh0) domain1 =
FEDomain('d', mesh1)
sfepy.discrete.fem.FEDomain
""" Functions for a mesh refinement with hanging nodes. Notes ----- Using LCBCs with hanging nodes is not supported. """ from __future__ import absolute_import from six.moves import range, zip import numpy as nm from sfepy.base.base import assert_ from sfepy.discrete import Functions, Function from sfepy.discrete.fem import Mesh, FEDomain # Rows = facets of reference cell, columns = [sub_cell_i, local facet_i] refine_edges_2_4 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]]]) refine_faces_3_8 = nm.array([[[0, 0], [1, 0], [2, 0], [3, 0]], [[0, 1], [3, 2], [4, 2], [7, 1]], [[0, 2], [1, 1], [4, 1], [5, 2]], [[4, 0], [5, 0], [6, 0], [7, 0]], [[1, 2], [2, 1], [5, 1], [6, 2]], [[2, 2], [3, 1], [6, 1], [7, 2]]]) refine_edges_3_8 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]], [[4, 3], [5, 0]], [[5, 3], [6, 0]], [[6, 3], [7, 0]], [[7, 3], [4, 0]], [[0, 8], [4, 8]], [[1, 8], [5, 8]], [[2, 8], [6, 8]], [[3, 8], [7, 8]]]) def find_level_interface(domain, refine_flag): """ Find facets of the coarse mesh that are on the coarse-refined cell boundary. ids w.r.t. current mesh: - facets: global, local w.r.t. cells[:, 0], local w.r.t. cells[:, 1] - interface cells: - cells[:, 0] - cells to refine - cells[:, 1] - their facet sharing neighbors (w.r.t. both meshes) - cells[:, 2] - facet kind: 0 = face, 1 = edge """ if not refine_flag.any(): facets = nm.zeros((0, 3), dtype=nm.uint32) cells = nm.zeros((0, 3), dtype=nm.uint32) return facets, cells, 0, None, None def _get_refine(coors, domain=None): return nm.nonzero(refine_flag)[0] def _get_coarse(coors, domain=None): return nm.nonzero(1 - refine_flag)[0] get_refine = Function('get_refine', _get_refine) get_coarse = Function('get_coarse', _get_coarse) functions = Functions([get_refine, get_coarse]) region0 = domain.create_region('coarse', 'cells by get_coarse', functions=functions, add_to_regions=False, allow_empty=True) region1 = domain.create_region('refine', 'cells by get_refine', functions=functions, add_to_regions=False) cmesh = domain.mesh.cmesh dim = cmesh.dim if dim == 2: oe = 0 facets = nm.intersect1d(region0.facets, region1.facets) cmesh.setup_connectivity(dim - 1, dim) cells, offs = cmesh.get_incident(dim, facets, dim - 1, ret_offsets=True) assert_((nm.diff(offs) == 2).all()) ii = cmesh.get_local_ids(facets, dim - 1, cells, offs, dim) ii = ii.reshape((-1, 2)) cells = cells.reshape((-1, 2)) ii = nm.where(refine_flag[cells], ii[:, :1], ii[:, 1:]) cells = nm.where(refine_flag[cells], cells[:, :1], cells[:, 1:]) facets = nm.c_[facets, ii] cells = nm.c_[cells, nm.zeros_like(cells[:, 1])] else: # if dim == 3: gel = domain.geom_els['3_8'] epf = gel.get_edges_per_face() cmesh.setup_connectivity(dim, dim) fc, coffs = cmesh.get_incident(dim, region1.cells, dim, ret_offsets=True) cc = nm.repeat(region1.cells, nm.diff(coffs)) aux = nm.c_[cc, fc] """ nnn[:, 0] cells to refine, nnn[:, 1] non-refined neighbours, nnn[:, 2] neighbour kind : 0 face, 1 edge. """ nn = aux[refine_flag[fc] == 0] cf = nn[:, 0].copy().astype(nm.uint32) cc = nn[:, 1].copy().astype(nm.uint32) vc, vco = cmesh.get_incident(0, cc, dim, ret_offsets=True) vf, vfo = cmesh.get_incident(0, cf, dim, ret_offsets=True) vc = vc.reshape((-1, 8)) vf = vf.reshape((-1, 8)) nnn = [] oe = 0 ov = nn.shape[0] for ii in range(vc.shape[0]): aux = set(vc[ii]).intersection(vf[ii]) nc = len(aux) if nc == 1: nnn.append((0, 0, 2)) ov -= 1 elif nc == 4: nnn.append((nn[ii, 0], nn[ii, 1], 0)) oe += 1 else: nnn.append((nn[ii, 0], nn[ii, 1], 1)) nnn = nm.array(nnn) if nnn.shape[0] == 0: facets = nm.zeros((0, 3), dtype=nm.uint32) cells = nm.zeros((0, 4), dtype=nm.uint32) return facets, cells, 0, region0, region1 # Sort by neighbour kind, skip vertex-only neighbours. ii = nm.argsort(nnn[:, 2]) nnn = nnn[ii][:ov] cf = cf[ii][:ov] cc = cc[ii][:ov] ec, eco = cmesh.get_incident(1, cc, dim, ret_offsets=True) ef, efo = cmesh.get_incident(1, cf, dim, ret_offsets=True) ec = ec.reshape((-1, 12)) ef = ef.reshape((-1, 12)) fc, fco = cmesh.get_incident(2, cc, dim, ret_offsets=True) ff, ffo = cmesh.get_incident(2, cf, dim, ret_offsets=True) fc = fc.reshape((-1, 6)) ff = ff.reshape((-1, 6)) emask = nm.zeros((domain.shape.n_el, 12), dtype=nm.bool) ffs = [] for ii in range(oe): facet = nm.intersect1d(fc[ii], ff[ii])[0] i1 = nm.where(ff[ii] == facet)[0][0] i0 = nm.where(fc[ii] == facet)[0][0] ffs.append((facet, i1, i0)) emask[nnn[ii, 0], epf[i1]] = True for ii in range(oe, nnn.shape[0]): facet = nm.intersect1d(ec[ii], ef[ii])[0] i1 = nm.where(ef[ii] == facet)[0][0] i0 = nm.where(ec[ii] == facet)[0][0] ffs.append((facet, i1, i0)) ffs = nm.array(ffs) ie = nm.where(nnn[:, 2] == 1)[0] ennn = nnn[ie] effs = ffs[ie] omit = ie[emask[ennn[:, 0], effs[:, 1]]] valid = nm.ones(nnn.shape[0], dtype=nm.bool) valid[omit] = False cells = nnn[valid] facets = ffs[valid] return facets, cells, oe, region0, region1 def refine_region(domain0, region0, region1): """ Coarse cell sub_cells[ii, 0] in mesh0 is split into sub_cells[ii, 1:] in mesh1. The new fine cells are interleaved among the original coarse cells so that the indices of the coarse cells do not change. The cell groups are preserved. The vertex groups are preserved only in the coarse (non-refined) cells. """ if region1 is None: return domain0, None mesh0 = domain0.mesh mesh1 = Mesh.from_region(region1, mesh0) domain1 = FEDomain('d', mesh1) domain1r = domain1.refine() mesh1r = domain1r.mesh n_cell = region1.shape.n_cell n_sub = 4 if mesh0.cmesh.tdim == 2 else 8 sub_cells = nm.empty((n_cell, n_sub + 1), dtype=nm.uint32) sub_cells[:, 0] = region1.cells sub_cells[:, 1] = region1.cells aux = nm.arange((n_sub - 1) * n_cell, dtype=nm.uint32) sub_cells[:, 2:] = mesh0.n_el + aux.reshape((n_cell, -1)) coors0, vgs0, conns0, mat_ids0, descs0 = mesh0._get_io_data() coors, vgs, _conns, _mat_ids, descs = mesh1r._get_io_data() # Preserve vertex groups of non-refined cells. vgs[:len(vgs0)] = vgs0 def _interleave_refined(c0, c1): if c1.ndim == 1: c0 = c0[:, None] c1 = c1[:, None] n_row, n_col = c1.shape n_new = region0.shape.n_cell + n_row out = nm.empty((n_new, n_col), dtype=c0.dtype) out[region0.cells] = c0[region0.cells] out[region1.cells] = c1[::n_sub] aux = c1.reshape((-1, n_col * n_sub)) out[mesh0.n_el:] = aux[:, n_col:].reshape((-1, n_col)) return out conn = _interleave_refined(conns0[0], _conns[0]) mat_id = _interleave_refined(mat_ids0[0], _mat_ids[0]).squeeze() mesh =
Mesh.from_data('a', coors, vgs, [conn], [mat_id], descs)
sfepy.discrete.fem.Mesh.from_data
""" Functions for a mesh refinement with hanging nodes. Notes ----- Using LCBCs with hanging nodes is not supported. """ from __future__ import absolute_import from six.moves import range, zip import numpy as nm from sfepy.base.base import assert_ from sfepy.discrete import Functions, Function from sfepy.discrete.fem import Mesh, FEDomain # Rows = facets of reference cell, columns = [sub_cell_i, local facet_i] refine_edges_2_4 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]]]) refine_faces_3_8 = nm.array([[[0, 0], [1, 0], [2, 0], [3, 0]], [[0, 1], [3, 2], [4, 2], [7, 1]], [[0, 2], [1, 1], [4, 1], [5, 2]], [[4, 0], [5, 0], [6, 0], [7, 0]], [[1, 2], [2, 1], [5, 1], [6, 2]], [[2, 2], [3, 1], [6, 1], [7, 2]]]) refine_edges_3_8 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]], [[4, 3], [5, 0]], [[5, 3], [6, 0]], [[6, 3], [7, 0]], [[7, 3], [4, 0]], [[0, 8], [4, 8]], [[1, 8], [5, 8]], [[2, 8], [6, 8]], [[3, 8], [7, 8]]]) def find_level_interface(domain, refine_flag): """ Find facets of the coarse mesh that are on the coarse-refined cell boundary. ids w.r.t. current mesh: - facets: global, local w.r.t. cells[:, 0], local w.r.t. cells[:, 1] - interface cells: - cells[:, 0] - cells to refine - cells[:, 1] - their facet sharing neighbors (w.r.t. both meshes) - cells[:, 2] - facet kind: 0 = face, 1 = edge """ if not refine_flag.any(): facets = nm.zeros((0, 3), dtype=nm.uint32) cells = nm.zeros((0, 3), dtype=nm.uint32) return facets, cells, 0, None, None def _get_refine(coors, domain=None): return nm.nonzero(refine_flag)[0] def _get_coarse(coors, domain=None): return nm.nonzero(1 - refine_flag)[0] get_refine = Function('get_refine', _get_refine) get_coarse = Function('get_coarse', _get_coarse) functions = Functions([get_refine, get_coarse]) region0 = domain.create_region('coarse', 'cells by get_coarse', functions=functions, add_to_regions=False, allow_empty=True) region1 = domain.create_region('refine', 'cells by get_refine', functions=functions, add_to_regions=False) cmesh = domain.mesh.cmesh dim = cmesh.dim if dim == 2: oe = 0 facets = nm.intersect1d(region0.facets, region1.facets) cmesh.setup_connectivity(dim - 1, dim) cells, offs = cmesh.get_incident(dim, facets, dim - 1, ret_offsets=True) assert_((nm.diff(offs) == 2).all()) ii = cmesh.get_local_ids(facets, dim - 1, cells, offs, dim) ii = ii.reshape((-1, 2)) cells = cells.reshape((-1, 2)) ii = nm.where(refine_flag[cells], ii[:, :1], ii[:, 1:]) cells = nm.where(refine_flag[cells], cells[:, :1], cells[:, 1:]) facets = nm.c_[facets, ii] cells = nm.c_[cells, nm.zeros_like(cells[:, 1])] else: # if dim == 3: gel = domain.geom_els['3_8'] epf = gel.get_edges_per_face() cmesh.setup_connectivity(dim, dim) fc, coffs = cmesh.get_incident(dim, region1.cells, dim, ret_offsets=True) cc = nm.repeat(region1.cells, nm.diff(coffs)) aux = nm.c_[cc, fc] """ nnn[:, 0] cells to refine, nnn[:, 1] non-refined neighbours, nnn[:, 2] neighbour kind : 0 face, 1 edge. """ nn = aux[refine_flag[fc] == 0] cf = nn[:, 0].copy().astype(nm.uint32) cc = nn[:, 1].copy().astype(nm.uint32) vc, vco = cmesh.get_incident(0, cc, dim, ret_offsets=True) vf, vfo = cmesh.get_incident(0, cf, dim, ret_offsets=True) vc = vc.reshape((-1, 8)) vf = vf.reshape((-1, 8)) nnn = [] oe = 0 ov = nn.shape[0] for ii in range(vc.shape[0]): aux = set(vc[ii]).intersection(vf[ii]) nc = len(aux) if nc == 1: nnn.append((0, 0, 2)) ov -= 1 elif nc == 4: nnn.append((nn[ii, 0], nn[ii, 1], 0)) oe += 1 else: nnn.append((nn[ii, 0], nn[ii, 1], 1)) nnn = nm.array(nnn) if nnn.shape[0] == 0: facets = nm.zeros((0, 3), dtype=nm.uint32) cells = nm.zeros((0, 4), dtype=nm.uint32) return facets, cells, 0, region0, region1 # Sort by neighbour kind, skip vertex-only neighbours. ii = nm.argsort(nnn[:, 2]) nnn = nnn[ii][:ov] cf = cf[ii][:ov] cc = cc[ii][:ov] ec, eco = cmesh.get_incident(1, cc, dim, ret_offsets=True) ef, efo = cmesh.get_incident(1, cf, dim, ret_offsets=True) ec = ec.reshape((-1, 12)) ef = ef.reshape((-1, 12)) fc, fco = cmesh.get_incident(2, cc, dim, ret_offsets=True) ff, ffo = cmesh.get_incident(2, cf, dim, ret_offsets=True) fc = fc.reshape((-1, 6)) ff = ff.reshape((-1, 6)) emask = nm.zeros((domain.shape.n_el, 12), dtype=nm.bool) ffs = [] for ii in range(oe): facet = nm.intersect1d(fc[ii], ff[ii])[0] i1 = nm.where(ff[ii] == facet)[0][0] i0 = nm.where(fc[ii] == facet)[0][0] ffs.append((facet, i1, i0)) emask[nnn[ii, 0], epf[i1]] = True for ii in range(oe, nnn.shape[0]): facet = nm.intersect1d(ec[ii], ef[ii])[0] i1 = nm.where(ef[ii] == facet)[0][0] i0 = nm.where(ec[ii] == facet)[0][0] ffs.append((facet, i1, i0)) ffs = nm.array(ffs) ie = nm.where(nnn[:, 2] == 1)[0] ennn = nnn[ie] effs = ffs[ie] omit = ie[emask[ennn[:, 0], effs[:, 1]]] valid = nm.ones(nnn.shape[0], dtype=nm.bool) valid[omit] = False cells = nnn[valid] facets = ffs[valid] return facets, cells, oe, region0, region1 def refine_region(domain0, region0, region1): """ Coarse cell sub_cells[ii, 0] in mesh0 is split into sub_cells[ii, 1:] in mesh1. The new fine cells are interleaved among the original coarse cells so that the indices of the coarse cells do not change. The cell groups are preserved. The vertex groups are preserved only in the coarse (non-refined) cells. """ if region1 is None: return domain0, None mesh0 = domain0.mesh mesh1 = Mesh.from_region(region1, mesh0) domain1 = FEDomain('d', mesh1) domain1r = domain1.refine() mesh1r = domain1r.mesh n_cell = region1.shape.n_cell n_sub = 4 if mesh0.cmesh.tdim == 2 else 8 sub_cells = nm.empty((n_cell, n_sub + 1), dtype=nm.uint32) sub_cells[:, 0] = region1.cells sub_cells[:, 1] = region1.cells aux = nm.arange((n_sub - 1) * n_cell, dtype=nm.uint32) sub_cells[:, 2:] = mesh0.n_el + aux.reshape((n_cell, -1)) coors0, vgs0, conns0, mat_ids0, descs0 = mesh0._get_io_data() coors, vgs, _conns, _mat_ids, descs = mesh1r._get_io_data() # Preserve vertex groups of non-refined cells. vgs[:len(vgs0)] = vgs0 def _interleave_refined(c0, c1): if c1.ndim == 1: c0 = c0[:, None] c1 = c1[:, None] n_row, n_col = c1.shape n_new = region0.shape.n_cell + n_row out = nm.empty((n_new, n_col), dtype=c0.dtype) out[region0.cells] = c0[region0.cells] out[region1.cells] = c1[::n_sub] aux = c1.reshape((-1, n_col * n_sub)) out[mesh0.n_el:] = aux[:, n_col:].reshape((-1, n_col)) return out conn = _interleave_refined(conns0[0], _conns[0]) mat_id = _interleave_refined(mat_ids0[0], _mat_ids[0]).squeeze() mesh = Mesh.from_data('a', coors, vgs, [conn], [mat_id], descs) domain =
FEDomain('d', mesh)
sfepy.discrete.fem.FEDomain
""" Functions for a mesh refinement with hanging nodes. Notes ----- Using LCBCs with hanging nodes is not supported. """ from __future__ import absolute_import from six.moves import range, zip import numpy as nm from sfepy.base.base import assert_ from sfepy.discrete import Functions, Function from sfepy.discrete.fem import Mesh, FEDomain # Rows = facets of reference cell, columns = [sub_cell_i, local facet_i] refine_edges_2_4 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]]]) refine_faces_3_8 = nm.array([[[0, 0], [1, 0], [2, 0], [3, 0]], [[0, 1], [3, 2], [4, 2], [7, 1]], [[0, 2], [1, 1], [4, 1], [5, 2]], [[4, 0], [5, 0], [6, 0], [7, 0]], [[1, 2], [2, 1], [5, 1], [6, 2]], [[2, 2], [3, 1], [6, 1], [7, 2]]]) refine_edges_3_8 = nm.array([[[0, 0], [1, 3]], [[1, 0], [2, 3]], [[2, 0], [3, 3]], [[3, 0], [0, 3]], [[4, 3], [5, 0]], [[5, 3], [6, 0]], [[6, 3], [7, 0]], [[7, 3], [4, 0]], [[0, 8], [4, 8]], [[1, 8], [5, 8]], [[2, 8], [6, 8]], [[3, 8], [7, 8]]]) def find_level_interface(domain, refine_flag): """ Find facets of the coarse mesh that are on the coarse-refined cell boundary. ids w.r.t. current mesh: - facets: global, local w.r.t. cells[:, 0], local w.r.t. cells[:, 1] - interface cells: - cells[:, 0] - cells to refine - cells[:, 1] - their facet sharing neighbors (w.r.t. both meshes) - cells[:, 2] - facet kind: 0 = face, 1 = edge """ if not refine_flag.any(): facets = nm.zeros((0, 3), dtype=nm.uint32) cells = nm.zeros((0, 3), dtype=nm.uint32) return facets, cells, 0, None, None def _get_refine(coors, domain=None): return nm.nonzero(refine_flag)[0] def _get_coarse(coors, domain=None): return nm.nonzero(1 - refine_flag)[0] get_refine = Function('get_refine', _get_refine) get_coarse = Function('get_coarse', _get_coarse) functions = Functions([get_refine, get_coarse]) region0 = domain.create_region('coarse', 'cells by get_coarse', functions=functions, add_to_regions=False, allow_empty=True) region1 = domain.create_region('refine', 'cells by get_refine', functions=functions, add_to_regions=False) cmesh = domain.mesh.cmesh dim = cmesh.dim if dim == 2: oe = 0 facets = nm.intersect1d(region0.facets, region1.facets) cmesh.setup_connectivity(dim - 1, dim) cells, offs = cmesh.get_incident(dim, facets, dim - 1, ret_offsets=True) assert_((nm.diff(offs) == 2).all()) ii = cmesh.get_local_ids(facets, dim - 1, cells, offs, dim) ii = ii.reshape((-1, 2)) cells = cells.reshape((-1, 2)) ii = nm.where(refine_flag[cells], ii[:, :1], ii[:, 1:]) cells = nm.where(refine_flag[cells], cells[:, :1], cells[:, 1:]) facets = nm.c_[facets, ii] cells = nm.c_[cells, nm.zeros_like(cells[:, 1])] else: # if dim == 3: gel = domain.geom_els['3_8'] epf = gel.get_edges_per_face() cmesh.setup_connectivity(dim, dim) fc, coffs = cmesh.get_incident(dim, region1.cells, dim, ret_offsets=True) cc = nm.repeat(region1.cells, nm.diff(coffs)) aux = nm.c_[cc, fc] """ nnn[:, 0] cells to refine, nnn[:, 1] non-refined neighbours, nnn[:, 2] neighbour kind : 0 face, 1 edge. """ nn = aux[refine_flag[fc] == 0] cf = nn[:, 0].copy().astype(nm.uint32) cc = nn[:, 1].copy().astype(nm.uint32) vc, vco = cmesh.get_incident(0, cc, dim, ret_offsets=True) vf, vfo = cmesh.get_incident(0, cf, dim, ret_offsets=True) vc = vc.reshape((-1, 8)) vf = vf.reshape((-1, 8)) nnn = [] oe = 0 ov = nn.shape[0] for ii in range(vc.shape[0]): aux = set(vc[ii]).intersection(vf[ii]) nc = len(aux) if nc == 1: nnn.append((0, 0, 2)) ov -= 1 elif nc == 4: nnn.append((nn[ii, 0], nn[ii, 1], 0)) oe += 1 else: nnn.append((nn[ii, 0], nn[ii, 1], 1)) nnn = nm.array(nnn) if nnn.shape[0] == 0: facets = nm.zeros((0, 3), dtype=nm.uint32) cells = nm.zeros((0, 4), dtype=nm.uint32) return facets, cells, 0, region0, region1 # Sort by neighbour kind, skip vertex-only neighbours. ii = nm.argsort(nnn[:, 2]) nnn = nnn[ii][:ov] cf = cf[ii][:ov] cc = cc[ii][:ov] ec, eco = cmesh.get_incident(1, cc, dim, ret_offsets=True) ef, efo = cmesh.get_incident(1, cf, dim, ret_offsets=True) ec = ec.reshape((-1, 12)) ef = ef.reshape((-1, 12)) fc, fco = cmesh.get_incident(2, cc, dim, ret_offsets=True) ff, ffo = cmesh.get_incident(2, cf, dim, ret_offsets=True) fc = fc.reshape((-1, 6)) ff = ff.reshape((-1, 6)) emask = nm.zeros((domain.shape.n_el, 12), dtype=nm.bool) ffs = [] for ii in range(oe): facet = nm.intersect1d(fc[ii], ff[ii])[0] i1 = nm.where(ff[ii] == facet)[0][0] i0 = nm.where(fc[ii] == facet)[0][0] ffs.append((facet, i1, i0)) emask[nnn[ii, 0], epf[i1]] = True for ii in range(oe, nnn.shape[0]): facet = nm.intersect1d(ec[ii], ef[ii])[0] i1 = nm.where(ef[ii] == facet)[0][0] i0 = nm.where(ec[ii] == facet)[0][0] ffs.append((facet, i1, i0)) ffs = nm.array(ffs) ie = nm.where(nnn[:, 2] == 1)[0] ennn = nnn[ie] effs = ffs[ie] omit = ie[emask[ennn[:, 0], effs[:, 1]]] valid = nm.ones(nnn.shape[0], dtype=nm.bool) valid[omit] = False cells = nnn[valid] facets = ffs[valid] return facets, cells, oe, region0, region1 def refine_region(domain0, region0, region1): """ Coarse cell sub_cells[ii, 0] in mesh0 is split into sub_cells[ii, 1:] in mesh1. The new fine cells are interleaved among the original coarse cells so that the indices of the coarse cells do not change. The cell groups are preserved. The vertex groups are preserved only in the coarse (non-refined) cells. """ if region1 is None: return domain0, None mesh0 = domain0.mesh mesh1 = Mesh.from_region(region1, mesh0) domain1 = FEDomain('d', mesh1) domain1r = domain1.refine() mesh1r = domain1r.mesh n_cell = region1.shape.n_cell n_sub = 4 if mesh0.cmesh.tdim == 2 else 8 sub_cells = nm.empty((n_cell, n_sub + 1), dtype=nm.uint32) sub_cells[:, 0] = region1.cells sub_cells[:, 1] = region1.cells aux = nm.arange((n_sub - 1) * n_cell, dtype=nm.uint32) sub_cells[:, 2:] = mesh0.n_el + aux.reshape((n_cell, -1)) coors0, vgs0, conns0, mat_ids0, descs0 = mesh0._get_io_data() coors, vgs, _conns, _mat_ids, descs = mesh1r._get_io_data() # Preserve vertex groups of non-refined cells. vgs[:len(vgs0)] = vgs0 def _interleave_refined(c0, c1): if c1.ndim == 1: c0 = c0[:, None] c1 = c1[:, None] n_row, n_col = c1.shape n_new = region0.shape.n_cell + n_row out = nm.empty((n_new, n_col), dtype=c0.dtype) out[region0.cells] = c0[region0.cells] out[region1.cells] = c1[::n_sub] aux = c1.reshape((-1, n_col * n_sub)) out[mesh0.n_el:] = aux[:, n_col:].reshape((-1, n_col)) return out conn = _interleave_refined(conns0[0], _conns[0]) mat_id = _interleave_refined(mat_ids0[0], _mat_ids[0]).squeeze() mesh = Mesh.from_data('a', coors, vgs, [conn], [mat_id], descs) domain = FEDomain('d', mesh) return domain, sub_cells def find_facet_substitutions(facets, cells, sub_cells, refine_facets): """ Find facet substitutions in connectivity. sub = [coarse cell, coarse facet, fine1 cell, fine1 facet, fine2 cell, fine2 facet] """ subs = [] for ii, fac in enumerate(facets): fine = cells[ii, 0] coarse = cells[ii, 1] isub = nm.searchsorted(sub_cells[:, 0], fine) refined = sub_cells[isub, 1:] rf = refine_facets[fac[1]] used = refined[rf[:, 0]] fused = rf[:, 1] master = [coarse, fac[2]] slave = list(zip(used, fused)) sub = nm.r_[[master], slave].ravel() subs.append(sub) subs = nm.array(subs) return subs def refine(domain0, refine, subs=None, ret_sub_cells=False): desc = domain0.mesh.descs[0]
assert_(desc in ['2_4', '3_8'])
sfepy.base.base.assert_
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None):
Container.__init__(self, objs=objs)
sfepy.base.base.Container.__init__
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj):
Container.insert(self, ii, obj)
sfepy.base.base.Container.insert
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj):
Container.append(self, obj)
sfepy.base.base.Container.append
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function =
Struct.get(self, 'function', None)
sfepy.base.base.Struct.get
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step =
get_default(step, self.arg_steps[name])
sfepy.base.base.get_default
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration =
get_default(integration, self.geometry_types[name])
sfepy.base.base.get_default
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym =
dim2sym(dim)
sfepy.mechanics.tensors.dim2sym
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number. return nm.inf elif sh == 'str': return 'str' else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return tuple((_parse_scalar_shape(ii.strip()) for ii in sh.split(','))) else: return (int(sh),) arg_kinds = get_arg_kinds(self.ats) arg_shapes_list = self.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] # Loop allowed shapes until a match is found, else error. allowed_shapes = [] prev_shapes = {} actual_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes allowed_shapes.append(arg_shapes) n_ok = 0 for ii, arg_kind in enumerate(arg_kinds): if arg_kind in ('user', 'ts'): n_ok += 1 continue arg = args[ii] key = '%s:%s' % (self.ats[ii], self.arg_names[ii]) if self.mode is not None: extended_ats = self.ats[ii] + ('/%s' % self.mode) else: extended_ats = self.ats[ii] try: sh = arg_shapes[self.ats[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): n_el, n_qp, _dim, n_en, n_c = self.get_data_shape(arg) actual_shapes[key] = (n_c,) shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) if nm.isinf(shape): n_ok += 1 else: n_ok += shape == n_c elif arg_kind.endswith('material'): if arg is None: # Switched-off opt_material. n_ok += sh is None continue if sh is None: continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if sh == 'str': n_ok += isinstance(arg, basestr) continue shape = _parse_tuple_shape(sh) ls = len(shape) aarg = nm.array(arg, ndmin=1) actual_shapes[key] = aarg.shape # Substiture general dimension 'N' with actual value. iinfs = nm.where(nm.isinf(shape))[0] if len(iinfs): shape = list(shape) for iinf in iinfs: shape[iinf] = aarg.shape[-ls+iinf] shape = tuple(shape) if (ls > 1) or (shape[0] > 1): # Array. n_ok += shape == aarg.shape[-ls:] actual_shapes[key] = aarg.shape[-ls:] elif (ls == 1) and (shape[0] == 1): # Scalar constant. from numbers import Number n_ok += isinstance(arg, Number) else: n_ok += 1 if n_ok == len(arg_kinds): break else: term_str = self.get_str() output('allowed argument shapes for term "%s":' % term_str) output(allowed_shapes) output('actual argument shapes:') output(actual_shapes) raise ValueError('wrong arguments shapes for "%s" term! (see above)' % term_str) def standalone_setup(self): from sfepy.discrete import create_adof_conns, Variables conn_info = {'aux' : self.get_conn_info()} adcs =
create_adof_conns(conn_info, None)
sfepy.discrete.create_adof_conns
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals)
terms.append(term)
sfepy.terms.extmods.terms.append
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals =
Integrals()
sfepy.discrete.Integrals
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul =
as_float_or_complex(other)
sfepy.base.base.as_float_or_complex
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts',
Struct()
sfepy.base.base.Struct
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode =
Struct.get(self, 'mode', None)
sfepy.base.base.Struct.get
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps =
PhysicalQPs()
sfepy.discrete.common.mappings.PhysicalQPs
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps =
get_physical_qps(self.region, self.integral)
sfepy.discrete.common.mappings.get_physical_qps
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number. return nm.inf elif sh == 'str': return 'str' else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return tuple((_parse_scalar_shape(ii.strip()) for ii in sh.split(','))) else: return (int(sh),) arg_kinds = get_arg_kinds(self.ats) arg_shapes_list = self.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] # Loop allowed shapes until a match is found, else error. allowed_shapes = [] prev_shapes = {} actual_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes allowed_shapes.append(arg_shapes) n_ok = 0 for ii, arg_kind in enumerate(arg_kinds): if arg_kind in ('user', 'ts'): n_ok += 1 continue arg = args[ii] key = '%s:%s' % (self.ats[ii], self.arg_names[ii]) if self.mode is not None: extended_ats = self.ats[ii] + ('/%s' % self.mode) else: extended_ats = self.ats[ii] try: sh = arg_shapes[self.ats[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): n_el, n_qp, _dim, n_en, n_c = self.get_data_shape(arg) actual_shapes[key] = (n_c,) shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) if nm.isinf(shape): n_ok += 1 else: n_ok += shape == n_c elif arg_kind.endswith('material'): if arg is None: # Switched-off opt_material. n_ok += sh is None continue if sh is None: continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if sh == 'str': n_ok += isinstance(arg, basestr) continue shape = _parse_tuple_shape(sh) ls = len(shape) aarg = nm.array(arg, ndmin=1) actual_shapes[key] = aarg.shape # Substiture general dimension 'N' with actual value. iinfs = nm.where(nm.isinf(shape))[0] if len(iinfs): shape = list(shape) for iinf in iinfs: shape[iinf] = aarg.shape[-ls+iinf] shape = tuple(shape) if (ls > 1) or (shape[0] > 1): # Array. n_ok += shape == aarg.shape[-ls:] actual_shapes[key] = aarg.shape[-ls:] elif (ls == 1) and (shape[0] == 1): # Scalar constant. from numbers import Number n_ok += isinstance(arg, Number) else: n_ok += 1 if n_ok == len(arg_kinds): break else: term_str = self.get_str()
output('allowed argument shapes for term "%s":' % term_str)
sfepy.base.base.output
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number. return nm.inf elif sh == 'str': return 'str' else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return tuple((_parse_scalar_shape(ii.strip()) for ii in sh.split(','))) else: return (int(sh),) arg_kinds = get_arg_kinds(self.ats) arg_shapes_list = self.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] # Loop allowed shapes until a match is found, else error. allowed_shapes = [] prev_shapes = {} actual_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes allowed_shapes.append(arg_shapes) n_ok = 0 for ii, arg_kind in enumerate(arg_kinds): if arg_kind in ('user', 'ts'): n_ok += 1 continue arg = args[ii] key = '%s:%s' % (self.ats[ii], self.arg_names[ii]) if self.mode is not None: extended_ats = self.ats[ii] + ('/%s' % self.mode) else: extended_ats = self.ats[ii] try: sh = arg_shapes[self.ats[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): n_el, n_qp, _dim, n_en, n_c = self.get_data_shape(arg) actual_shapes[key] = (n_c,) shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) if nm.isinf(shape): n_ok += 1 else: n_ok += shape == n_c elif arg_kind.endswith('material'): if arg is None: # Switched-off opt_material. n_ok += sh is None continue if sh is None: continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if sh == 'str': n_ok += isinstance(arg, basestr) continue shape = _parse_tuple_shape(sh) ls = len(shape) aarg = nm.array(arg, ndmin=1) actual_shapes[key] = aarg.shape # Substiture general dimension 'N' with actual value. iinfs = nm.where(nm.isinf(shape))[0] if len(iinfs): shape = list(shape) for iinf in iinfs: shape[iinf] = aarg.shape[-ls+iinf] shape = tuple(shape) if (ls > 1) or (shape[0] > 1): # Array. n_ok += shape == aarg.shape[-ls:] actual_shapes[key] = aarg.shape[-ls:] elif (ls == 1) and (shape[0] == 1): # Scalar constant. from numbers import Number n_ok += isinstance(arg, Number) else: n_ok += 1 if n_ok == len(arg_kinds): break else: term_str = self.get_str() output('allowed argument shapes for term "%s":' % term_str)
output(allowed_shapes)
sfepy.base.base.output
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number. return nm.inf elif sh == 'str': return 'str' else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return tuple((_parse_scalar_shape(ii.strip()) for ii in sh.split(','))) else: return (int(sh),) arg_kinds = get_arg_kinds(self.ats) arg_shapes_list = self.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] # Loop allowed shapes until a match is found, else error. allowed_shapes = [] prev_shapes = {} actual_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes allowed_shapes.append(arg_shapes) n_ok = 0 for ii, arg_kind in enumerate(arg_kinds): if arg_kind in ('user', 'ts'): n_ok += 1 continue arg = args[ii] key = '%s:%s' % (self.ats[ii], self.arg_names[ii]) if self.mode is not None: extended_ats = self.ats[ii] + ('/%s' % self.mode) else: extended_ats = self.ats[ii] try: sh = arg_shapes[self.ats[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): n_el, n_qp, _dim, n_en, n_c = self.get_data_shape(arg) actual_shapes[key] = (n_c,) shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) if nm.isinf(shape): n_ok += 1 else: n_ok += shape == n_c elif arg_kind.endswith('material'): if arg is None: # Switched-off opt_material. n_ok += sh is None continue if sh is None: continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if sh == 'str': n_ok += isinstance(arg, basestr) continue shape = _parse_tuple_shape(sh) ls = len(shape) aarg = nm.array(arg, ndmin=1) actual_shapes[key] = aarg.shape # Substiture general dimension 'N' with actual value. iinfs = nm.where(nm.isinf(shape))[0] if len(iinfs): shape = list(shape) for iinf in iinfs: shape[iinf] = aarg.shape[-ls+iinf] shape = tuple(shape) if (ls > 1) or (shape[0] > 1): # Array. n_ok += shape == aarg.shape[-ls:] actual_shapes[key] = aarg.shape[-ls:] elif (ls == 1) and (shape[0] == 1): # Scalar constant. from numbers import Number n_ok += isinstance(arg, Number) else: n_ok += 1 if n_ok == len(arg_kinds): break else: term_str = self.get_str() output('allowed argument shapes for term "%s":' % term_str) output(allowed_shapes)
output('actual argument shapes:')
sfepy.base.base.output
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number. return nm.inf elif sh == 'str': return 'str' else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return tuple((_parse_scalar_shape(ii.strip()) for ii in sh.split(','))) else: return (int(sh),) arg_kinds = get_arg_kinds(self.ats) arg_shapes_list = self.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] # Loop allowed shapes until a match is found, else error. allowed_shapes = [] prev_shapes = {} actual_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes allowed_shapes.append(arg_shapes) n_ok = 0 for ii, arg_kind in enumerate(arg_kinds): if arg_kind in ('user', 'ts'): n_ok += 1 continue arg = args[ii] key = '%s:%s' % (self.ats[ii], self.arg_names[ii]) if self.mode is not None: extended_ats = self.ats[ii] + ('/%s' % self.mode) else: extended_ats = self.ats[ii] try: sh = arg_shapes[self.ats[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): n_el, n_qp, _dim, n_en, n_c = self.get_data_shape(arg) actual_shapes[key] = (n_c,) shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) if nm.isinf(shape): n_ok += 1 else: n_ok += shape == n_c elif arg_kind.endswith('material'): if arg is None: # Switched-off opt_material. n_ok += sh is None continue if sh is None: continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if sh == 'str': n_ok += isinstance(arg, basestr) continue shape = _parse_tuple_shape(sh) ls = len(shape) aarg = nm.array(arg, ndmin=1) actual_shapes[key] = aarg.shape # Substiture general dimension 'N' with actual value. iinfs = nm.where(nm.isinf(shape))[0] if len(iinfs): shape = list(shape) for iinf in iinfs: shape[iinf] = aarg.shape[-ls+iinf] shape = tuple(shape) if (ls > 1) or (shape[0] > 1): # Array. n_ok += shape == aarg.shape[-ls:] actual_shapes[key] = aarg.shape[-ls:] elif (ls == 1) and (shape[0] == 1): # Scalar constant. from numbers import Number n_ok += isinstance(arg, Number) else: n_ok += 1 if n_ok == len(arg_kinds): break else: term_str = self.get_str() output('allowed argument shapes for term "%s":' % term_str) output(allowed_shapes) output('actual argument shapes:')
output(actual_shapes)
sfepy.base.base.output
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number. return nm.inf elif sh == 'str': return 'str' else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return tuple((_parse_scalar_shape(ii.strip()) for ii in sh.split(','))) else: return (int(sh),) arg_kinds = get_arg_kinds(self.ats) arg_shapes_list = self.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] # Loop allowed shapes until a match is found, else error. allowed_shapes = [] prev_shapes = {} actual_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes allowed_shapes.append(arg_shapes) n_ok = 0 for ii, arg_kind in enumerate(arg_kinds): if arg_kind in ('user', 'ts'): n_ok += 1 continue arg = args[ii] key = '%s:%s' % (self.ats[ii], self.arg_names[ii]) if self.mode is not None: extended_ats = self.ats[ii] + ('/%s' % self.mode) else: extended_ats = self.ats[ii] try: sh = arg_shapes[self.ats[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): n_el, n_qp, _dim, n_en, n_c = self.get_data_shape(arg) actual_shapes[key] = (n_c,) shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) if nm.isinf(shape): n_ok += 1 else: n_ok += shape == n_c elif arg_kind.endswith('material'): if arg is None: # Switched-off opt_material. n_ok += sh is None continue if sh is None: continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if sh == 'str': n_ok += isinstance(arg, basestr) continue shape = _parse_tuple_shape(sh) ls = len(shape) aarg = nm.array(arg, ndmin=1) actual_shapes[key] = aarg.shape # Substiture general dimension 'N' with actual value. iinfs = nm.where(nm.isinf(shape))[0] if len(iinfs): shape = list(shape) for iinf in iinfs: shape[iinf] = aarg.shape[-ls+iinf] shape = tuple(shape) if (ls > 1) or (shape[0] > 1): # Array. n_ok += shape == aarg.shape[-ls:] actual_shapes[key] = aarg.shape[-ls:] elif (ls == 1) and (shape[0] == 1): # Scalar constant. from numbers import Number n_ok += isinstance(arg, Number) else: n_ok += 1 if n_ok == len(arg_kinds): break else: term_str = self.get_str() output('allowed argument shapes for term "%s":' % term_str) output(allowed_shapes) output('actual argument shapes:') output(actual_shapes) raise ValueError('wrong arguments shapes for "%s" term! (see above)' % term_str) def standalone_setup(self): from sfepy.discrete import create_adof_conns, Variables conn_info = {'aux' : self.get_conn_info()} adcs = create_adof_conns(conn_info, None) variables = Variables(self.get_variables()) variables.set_adof_conns(adcs) materials = self.get_materials(join=True) for mat in materials: mat.time_update(None, [Struct(terms=[self])]) def call_get_fargs(self, args, kwargs): try: fargs = self.get_fargs(*args, **kwargs) except (RuntimeError, ValueError): terms.errclear() raise return fargs def call_function(self, out, fargs): try: status = self.function(out, *fargs) except (RuntimeError, ValueError): terms.errclear() raise if status:
terms.errclear()
sfepy.terms.extmods.terms.errclear
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number. return nm.inf elif sh == 'str': return 'str' else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return tuple((_parse_scalar_shape(ii.strip()) for ii in sh.split(','))) else: return (int(sh),) arg_kinds = get_arg_kinds(self.ats) arg_shapes_list = self.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] # Loop allowed shapes until a match is found, else error. allowed_shapes = [] prev_shapes = {} actual_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes allowed_shapes.append(arg_shapes) n_ok = 0 for ii, arg_kind in enumerate(arg_kinds): if arg_kind in ('user', 'ts'): n_ok += 1 continue arg = args[ii] key = '%s:%s' % (self.ats[ii], self.arg_names[ii]) if self.mode is not None: extended_ats = self.ats[ii] + ('/%s' % self.mode) else: extended_ats = self.ats[ii] try: sh = arg_shapes[self.ats[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): n_el, n_qp, _dim, n_en, n_c = self.get_data_shape(arg) actual_shapes[key] = (n_c,) shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) if nm.isinf(shape): n_ok += 1 else: n_ok += shape == n_c elif arg_kind.endswith('material'): if arg is None: # Switched-off opt_material. n_ok += sh is None continue if sh is None: continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if sh == 'str': n_ok += isinstance(arg, basestr) continue shape = _parse_tuple_shape(sh) ls = len(shape) aarg = nm.array(arg, ndmin=1) actual_shapes[key] = aarg.shape # Substiture general dimension 'N' with actual value. iinfs = nm.where(nm.isinf(shape))[0] if len(iinfs): shape = list(shape) for iinf in iinfs: shape[iinf] = aarg.shape[-ls+iinf] shape = tuple(shape) if (ls > 1) or (shape[0] > 1): # Array. n_ok += shape == aarg.shape[-ls:] actual_shapes[key] = aarg.shape[-ls:] elif (ls == 1) and (shape[0] == 1): # Scalar constant. from numbers import Number n_ok += isinstance(arg, Number) else: n_ok += 1 if n_ok == len(arg_kinds): break else: term_str = self.get_str() output('allowed argument shapes for term "%s":' % term_str) output(allowed_shapes) output('actual argument shapes:') output(actual_shapes) raise ValueError('wrong arguments shapes for "%s" term! (see above)' % term_str) def standalone_setup(self): from sfepy.discrete import create_adof_conns, Variables conn_info = {'aux' : self.get_conn_info()} adcs = create_adof_conns(conn_info, None) variables = Variables(self.get_variables()) variables.set_adof_conns(adcs) materials = self.get_materials(join=True) for mat in materials: mat.time_update(None, [Struct(terms=[self])]) def call_get_fargs(self, args, kwargs): try: fargs = self.get_fargs(*args, **kwargs) except (RuntimeError, ValueError):
terms.errclear()
sfepy.terms.extmods.terms.errclear
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number. return nm.inf elif sh == 'str': return 'str' else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return tuple((_parse_scalar_shape(ii.strip()) for ii in sh.split(','))) else: return (int(sh),) arg_kinds = get_arg_kinds(self.ats) arg_shapes_list = self.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] # Loop allowed shapes until a match is found, else error. allowed_shapes = [] prev_shapes = {} actual_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes allowed_shapes.append(arg_shapes) n_ok = 0 for ii, arg_kind in enumerate(arg_kinds): if arg_kind in ('user', 'ts'): n_ok += 1 continue arg = args[ii] key = '%s:%s' % (self.ats[ii], self.arg_names[ii]) if self.mode is not None: extended_ats = self.ats[ii] + ('/%s' % self.mode) else: extended_ats = self.ats[ii] try: sh = arg_shapes[self.ats[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): n_el, n_qp, _dim, n_en, n_c = self.get_data_shape(arg) actual_shapes[key] = (n_c,) shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) if nm.isinf(shape): n_ok += 1 else: n_ok += shape == n_c elif arg_kind.endswith('material'): if arg is None: # Switched-off opt_material. n_ok += sh is None continue if sh is None: continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if sh == 'str': n_ok += isinstance(arg, basestr) continue shape = _parse_tuple_shape(sh) ls = len(shape) aarg = nm.array(arg, ndmin=1) actual_shapes[key] = aarg.shape # Substiture general dimension 'N' with actual value. iinfs = nm.where(nm.isinf(shape))[0] if len(iinfs): shape = list(shape) for iinf in iinfs: shape[iinf] = aarg.shape[-ls+iinf] shape = tuple(shape) if (ls > 1) or (shape[0] > 1): # Array. n_ok += shape == aarg.shape[-ls:] actual_shapes[key] = aarg.shape[-ls:] elif (ls == 1) and (shape[0] == 1): # Scalar constant. from numbers import Number n_ok += isinstance(arg, Number) else: n_ok += 1 if n_ok == len(arg_kinds): break else: term_str = self.get_str() output('allowed argument shapes for term "%s":' % term_str) output(allowed_shapes) output('actual argument shapes:') output(actual_shapes) raise ValueError('wrong arguments shapes for "%s" term! (see above)' % term_str) def standalone_setup(self): from sfepy.discrete import create_adof_conns, Variables conn_info = {'aux' : self.get_conn_info()} adcs = create_adof_conns(conn_info, None) variables = Variables(self.get_variables()) variables.set_adof_conns(adcs) materials = self.get_materials(join=True) for mat in materials: mat.time_update(None, [Struct(terms=[self])]) def call_get_fargs(self, args, kwargs): try: fargs = self.get_fargs(*args, **kwargs) except (RuntimeError, ValueError): terms.errclear() raise return fargs def call_function(self, out, fargs): try: status = self.function(out, *fargs) except (RuntimeError, ValueError):
terms.errclear()
sfepy.terms.extmods.terms.errclear
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number. return nm.inf elif sh == 'str': return 'str' else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return tuple((_parse_scalar_shape(ii.strip()) for ii in sh.split(','))) else: return (int(sh),) arg_kinds = get_arg_kinds(self.ats) arg_shapes_list = self.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] # Loop allowed shapes until a match is found, else error. allowed_shapes = [] prev_shapes = {} actual_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes allowed_shapes.append(arg_shapes) n_ok = 0 for ii, arg_kind in enumerate(arg_kinds): if arg_kind in ('user', 'ts'): n_ok += 1 continue arg = args[ii] key = '%s:%s' % (self.ats[ii], self.arg_names[ii]) if self.mode is not None: extended_ats = self.ats[ii] + ('/%s' % self.mode) else: extended_ats = self.ats[ii] try: sh = arg_shapes[self.ats[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): n_el, n_qp, _dim, n_en, n_c = self.get_data_shape(arg) actual_shapes[key] = (n_c,) shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) if nm.isinf(shape): n_ok += 1 else: n_ok += shape == n_c elif arg_kind.endswith('material'): if arg is None: # Switched-off opt_material. n_ok += sh is None continue if sh is None: continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if sh == 'str': n_ok += isinstance(arg, basestr) continue shape = _parse_tuple_shape(sh) ls = len(shape) aarg = nm.array(arg, ndmin=1) actual_shapes[key] = aarg.shape # Substiture general dimension 'N' with actual value. iinfs = nm.where(nm.isinf(shape))[0] if len(iinfs): shape = list(shape) for iinf in iinfs: shape[iinf] = aarg.shape[-ls+iinf] shape = tuple(shape) if (ls > 1) or (shape[0] > 1): # Array. n_ok += shape == aarg.shape[-ls:] actual_shapes[key] = aarg.shape[-ls:] elif (ls == 1) and (shape[0] == 1): # Scalar constant. from numbers import Number n_ok += isinstance(arg, Number) else: n_ok += 1 if n_ok == len(arg_kinds): break else: term_str = self.get_str() output('allowed argument shapes for term "%s":' % term_str) output(allowed_shapes) output('actual argument shapes:') output(actual_shapes) raise ValueError('wrong arguments shapes for "%s" term! (see above)' % term_str) def standalone_setup(self): from sfepy.discrete import create_adof_conns, Variables conn_info = {'aux' : self.get_conn_info()} adcs = create_adof_conns(conn_info, None) variables = Variables(self.get_variables()) variables.set_adof_conns(adcs) materials = self.get_materials(join=True) for mat in materials: mat.time_update(None, [Struct(terms=[self])]) def call_get_fargs(self, args, kwargs): try: fargs = self.get_fargs(*args, **kwargs) except (RuntimeError, ValueError): terms.errclear() raise return fargs def call_function(self, out, fargs): try: status = self.function(out, *fargs) except (RuntimeError, ValueError): terms.errclear() raise if status: terms.errclear() raise ValueError('term evaluation failed! (%s)' % self.name) return status def eval_real(self, shape, fargs, mode='eval', term_mode=None, diff_var=None, **kwargs): out = nm.empty(shape, dtype=nm.float64) if mode == 'eval': status = self.call_function(out, fargs) # Sum over elements but not over components. out1 = nm.sum(out, 0).squeeze() return out1, status else: status = self.call_function(out, fargs) return out, status def eval_complex(self, shape, fargs, mode='eval', term_mode=None, diff_var=None, **kwargs): rout = nm.empty(shape, dtype=nm.float64) fargsd = split_complex_args(fargs) # Assuming linear forms. Then the matrix is the # same both for real and imaginary part. rstatus = self.call_function(rout, fargsd['r']) if (diff_var is None) and len(fargsd) >= 2: iout = nm.empty(shape, dtype=nm.float64) istatus = self.call_function(iout, fargsd['i']) if mode == 'eval' and len(fargsd) >= 4: irout = nm.empty(shape, dtype=nm.float64) irstatus = self.call_function(irout, fargsd['ir']) riout = nm.empty(shape, dtype=nm.float64) ristatus = self.call_function(riout, fargsd['ri']) out = (rout - iout) + (riout + irout) * 1j status = rstatus or istatus or ristatus or irstatus else: out = rout + 1j * iout status = rstatus or istatus else: out, status = rout + 0j, rstatus if mode == 'eval': out1 = nm.sum(out, 0).squeeze() return out1, status else: return out, status def evaluate(self, mode='eval', diff_var=None, standalone=True, ret_status=False, **kwargs): """ Evaluate the term. Parameters ---------- mode : 'eval' (default), or 'weak' The term evaluation mode. Returns ------- val : float or array In 'eval' mode, the term returns a single value (the integral, it does not need to be a scalar), while in 'weak' mode it returns an array for each element. status : int, optional The flag indicating evaluation success (0) or failure (nonzero). Only provided if `ret_status` is True. iels : array of ints, optional The local elements indices in 'weak' mode. Only provided in non-'eval' modes. """ if standalone: self.standalone_setup() kwargs = kwargs.copy() term_mode = kwargs.pop('term_mode', None) if mode in ('eval', 'el_eval', 'el_avg', 'qp'): args = self.get_args(**kwargs) self.check_shapes(*args) emode = 'eval' if mode == 'el_eval' else mode _args = tuple(args) + (emode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) shape, dtype = self.get_eval_shape(*_args, **kwargs) if dtype == nm.float64: val, status = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif dtype == nm.complex128: val, status = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % dtype) val *= self.sign out = (val,) elif mode == 'weak': varr = self.get_virtual_variable() if varr is None: raise ValueError('no virtual variable in weak mode! (in "%s")' % self.get_str()) if diff_var is not None: varc = self.get_variables(as_list=False)[diff_var] args = self.get_args(**kwargs) self.check_shapes(*args) _args = tuple(args) + (mode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) n_elr, n_qpr, dim, n_enr, n_cr = self.get_data_shape(varr) n_row = n_cr * n_enr if diff_var is None: shape = (n_elr, 1, n_row, 1) else: n_elc, n_qpc, dim, n_enc, n_cc = self.get_data_shape(varc) n_col = n_cc * n_enc shape = (n_elr, 1, n_row, n_col) if varr.dtype == nm.float64: vals, status = self.eval_real(shape, fargs, mode, term_mode, diff_var, **kwargs) elif varr.dtype == nm.complex128: vals, status = self.eval_complex(shape, fargs, mode, term_mode, diff_var, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % varr.dtype) if not isinstance(vals, tuple): vals *= self.sign iels = self.get_assembling_cells(vals.shape) else: vals = (self.sign * vals[0],) + vals[1:] iels = None out = (vals, iels) if goptions['check_term_finiteness']: assert_(nm.isfinite(out[0]).all(), msg='"%s" term values not finite!' % self.get_str()) if ret_status: out = out + (status,) if len(out) == 1: out = out[0] return out def assemble_to(self, asm_obj, val, iels, mode='vector', diff_var=None): """ Assemble the results of term evaluation. For standard terms, assemble the values in `val` corresponding to elements/cells `iels` into a vector or a CSR sparse matrix `asm_obj`, depending on `mode`. For terms with a dynamic connectivity (e.g. contact terms), in `'matrix'` mode, return the extra COO sparse matrix instead. The extra matrix has to be added to the global matrix by the caller. By default, this is done in :func:`Equations.evaluate() <sfepy.discrete.equations.Equations.evaluate()>`. """ import sfepy.discrete.common.extmods.assemble as asm vvar = self.get_virtual_variable() dc_type = self.get_dof_conn_type() extra = None if mode == 'vector': if asm_obj.dtype == nm.float64: assemble = asm.assemble_vector else:
assert_(asm_obj.dtype == nm.complex128)
sfepy.base.base.assert_
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number. return nm.inf elif sh == 'str': return 'str' else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return tuple((_parse_scalar_shape(ii.strip()) for ii in sh.split(','))) else: return (int(sh),) arg_kinds = get_arg_kinds(self.ats) arg_shapes_list = self.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] # Loop allowed shapes until a match is found, else error. allowed_shapes = [] prev_shapes = {} actual_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes allowed_shapes.append(arg_shapes) n_ok = 0 for ii, arg_kind in enumerate(arg_kinds): if arg_kind in ('user', 'ts'): n_ok += 1 continue arg = args[ii] key = '%s:%s' % (self.ats[ii], self.arg_names[ii]) if self.mode is not None: extended_ats = self.ats[ii] + ('/%s' % self.mode) else: extended_ats = self.ats[ii] try: sh = arg_shapes[self.ats[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): n_el, n_qp, _dim, n_en, n_c = self.get_data_shape(arg) actual_shapes[key] = (n_c,) shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) if nm.isinf(shape): n_ok += 1 else: n_ok += shape == n_c elif arg_kind.endswith('material'): if arg is None: # Switched-off opt_material. n_ok += sh is None continue if sh is None: continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if sh == 'str': n_ok += isinstance(arg, basestr) continue shape = _parse_tuple_shape(sh) ls = len(shape) aarg = nm.array(arg, ndmin=1) actual_shapes[key] = aarg.shape # Substiture general dimension 'N' with actual value. iinfs = nm.where(nm.isinf(shape))[0] if len(iinfs): shape = list(shape) for iinf in iinfs: shape[iinf] = aarg.shape[-ls+iinf] shape = tuple(shape) if (ls > 1) or (shape[0] > 1): # Array. n_ok += shape == aarg.shape[-ls:] actual_shapes[key] = aarg.shape[-ls:] elif (ls == 1) and (shape[0] == 1): # Scalar constant. from numbers import Number n_ok += isinstance(arg, Number) else: n_ok += 1 if n_ok == len(arg_kinds): break else: term_str = self.get_str() output('allowed argument shapes for term "%s":' % term_str) output(allowed_shapes) output('actual argument shapes:') output(actual_shapes) raise ValueError('wrong arguments shapes for "%s" term! (see above)' % term_str) def standalone_setup(self): from sfepy.discrete import create_adof_conns, Variables conn_info = {'aux' : self.get_conn_info()} adcs = create_adof_conns(conn_info, None) variables = Variables(self.get_variables()) variables.set_adof_conns(adcs) materials = self.get_materials(join=True) for mat in materials: mat.time_update(None, [Struct(terms=[self])]) def call_get_fargs(self, args, kwargs): try: fargs = self.get_fargs(*args, **kwargs) except (RuntimeError, ValueError): terms.errclear() raise return fargs def call_function(self, out, fargs): try: status = self.function(out, *fargs) except (RuntimeError, ValueError): terms.errclear() raise if status: terms.errclear() raise ValueError('term evaluation failed! (%s)' % self.name) return status def eval_real(self, shape, fargs, mode='eval', term_mode=None, diff_var=None, **kwargs): out = nm.empty(shape, dtype=nm.float64) if mode == 'eval': status = self.call_function(out, fargs) # Sum over elements but not over components. out1 = nm.sum(out, 0).squeeze() return out1, status else: status = self.call_function(out, fargs) return out, status def eval_complex(self, shape, fargs, mode='eval', term_mode=None, diff_var=None, **kwargs): rout = nm.empty(shape, dtype=nm.float64) fargsd = split_complex_args(fargs) # Assuming linear forms. Then the matrix is the # same both for real and imaginary part. rstatus = self.call_function(rout, fargsd['r']) if (diff_var is None) and len(fargsd) >= 2: iout = nm.empty(shape, dtype=nm.float64) istatus = self.call_function(iout, fargsd['i']) if mode == 'eval' and len(fargsd) >= 4: irout = nm.empty(shape, dtype=nm.float64) irstatus = self.call_function(irout, fargsd['ir']) riout = nm.empty(shape, dtype=nm.float64) ristatus = self.call_function(riout, fargsd['ri']) out = (rout - iout) + (riout + irout) * 1j status = rstatus or istatus or ristatus or irstatus else: out = rout + 1j * iout status = rstatus or istatus else: out, status = rout + 0j, rstatus if mode == 'eval': out1 = nm.sum(out, 0).squeeze() return out1, status else: return out, status def evaluate(self, mode='eval', diff_var=None, standalone=True, ret_status=False, **kwargs): """ Evaluate the term. Parameters ---------- mode : 'eval' (default), or 'weak' The term evaluation mode. Returns ------- val : float or array In 'eval' mode, the term returns a single value (the integral, it does not need to be a scalar), while in 'weak' mode it returns an array for each element. status : int, optional The flag indicating evaluation success (0) or failure (nonzero). Only provided if `ret_status` is True. iels : array of ints, optional The local elements indices in 'weak' mode. Only provided in non-'eval' modes. """ if standalone: self.standalone_setup() kwargs = kwargs.copy() term_mode = kwargs.pop('term_mode', None) if mode in ('eval', 'el_eval', 'el_avg', 'qp'): args = self.get_args(**kwargs) self.check_shapes(*args) emode = 'eval' if mode == 'el_eval' else mode _args = tuple(args) + (emode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) shape, dtype = self.get_eval_shape(*_args, **kwargs) if dtype == nm.float64: val, status = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif dtype == nm.complex128: val, status = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % dtype) val *= self.sign out = (val,) elif mode == 'weak': varr = self.get_virtual_variable() if varr is None: raise ValueError('no virtual variable in weak mode! (in "%s")' % self.get_str()) if diff_var is not None: varc = self.get_variables(as_list=False)[diff_var] args = self.get_args(**kwargs) self.check_shapes(*args) _args = tuple(args) + (mode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) n_elr, n_qpr, dim, n_enr, n_cr = self.get_data_shape(varr) n_row = n_cr * n_enr if diff_var is None: shape = (n_elr, 1, n_row, 1) else: n_elc, n_qpc, dim, n_enc, n_cc = self.get_data_shape(varc) n_col = n_cc * n_enc shape = (n_elr, 1, n_row, n_col) if varr.dtype == nm.float64: vals, status = self.eval_real(shape, fargs, mode, term_mode, diff_var, **kwargs) elif varr.dtype == nm.complex128: vals, status = self.eval_complex(shape, fargs, mode, term_mode, diff_var, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % varr.dtype) if not isinstance(vals, tuple): vals *= self.sign iels = self.get_assembling_cells(vals.shape) else: vals = (self.sign * vals[0],) + vals[1:] iels = None out = (vals, iels) if goptions['check_term_finiteness']: assert_(nm.isfinite(out[0]).all(), msg='"%s" term values not finite!' % self.get_str()) if ret_status: out = out + (status,) if len(out) == 1: out = out[0] return out def assemble_to(self, asm_obj, val, iels, mode='vector', diff_var=None): """ Assemble the results of term evaluation. For standard terms, assemble the values in `val` corresponding to elements/cells `iels` into a vector or a CSR sparse matrix `asm_obj`, depending on `mode`. For terms with a dynamic connectivity (e.g. contact terms), in `'matrix'` mode, return the extra COO sparse matrix instead. The extra matrix has to be added to the global matrix by the caller. By default, this is done in :func:`Equations.evaluate() <sfepy.discrete.equations.Equations.evaluate()>`. """ import sfepy.discrete.common.extmods.assemble as asm vvar = self.get_virtual_variable() dc_type = self.get_dof_conn_type() extra = None if mode == 'vector': if asm_obj.dtype == nm.float64: assemble = asm.assemble_vector else: assert_(asm_obj.dtype == nm.complex128) assemble = asm.assemble_vector_complex for ii in range(len(val)): if not(val[ii].dtype == nm.complex128): val[ii] = nm.complex128(val[ii]) if not isinstance(val, tuple): dc = vvar.get_dof_conn(dc_type)
assert_(val.shape[2] == dc.shape[1])
sfepy.base.base.assert_
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number. return nm.inf elif sh == 'str': return 'str' else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return tuple((_parse_scalar_shape(ii.strip()) for ii in sh.split(','))) else: return (int(sh),) arg_kinds = get_arg_kinds(self.ats) arg_shapes_list = self.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] # Loop allowed shapes until a match is found, else error. allowed_shapes = [] prev_shapes = {} actual_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes allowed_shapes.append(arg_shapes) n_ok = 0 for ii, arg_kind in enumerate(arg_kinds): if arg_kind in ('user', 'ts'): n_ok += 1 continue arg = args[ii] key = '%s:%s' % (self.ats[ii], self.arg_names[ii]) if self.mode is not None: extended_ats = self.ats[ii] + ('/%s' % self.mode) else: extended_ats = self.ats[ii] try: sh = arg_shapes[self.ats[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): n_el, n_qp, _dim, n_en, n_c = self.get_data_shape(arg) actual_shapes[key] = (n_c,) shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) if nm.isinf(shape): n_ok += 1 else: n_ok += shape == n_c elif arg_kind.endswith('material'): if arg is None: # Switched-off opt_material. n_ok += sh is None continue if sh is None: continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if sh == 'str': n_ok += isinstance(arg, basestr) continue shape = _parse_tuple_shape(sh) ls = len(shape) aarg = nm.array(arg, ndmin=1) actual_shapes[key] = aarg.shape # Substiture general dimension 'N' with actual value. iinfs = nm.where(nm.isinf(shape))[0] if len(iinfs): shape = list(shape) for iinf in iinfs: shape[iinf] = aarg.shape[-ls+iinf] shape = tuple(shape) if (ls > 1) or (shape[0] > 1): # Array. n_ok += shape == aarg.shape[-ls:] actual_shapes[key] = aarg.shape[-ls:] elif (ls == 1) and (shape[0] == 1): # Scalar constant. from numbers import Number n_ok += isinstance(arg, Number) else: n_ok += 1 if n_ok == len(arg_kinds): break else: term_str = self.get_str() output('allowed argument shapes for term "%s":' % term_str) output(allowed_shapes) output('actual argument shapes:') output(actual_shapes) raise ValueError('wrong arguments shapes for "%s" term! (see above)' % term_str) def standalone_setup(self): from sfepy.discrete import create_adof_conns, Variables conn_info = {'aux' : self.get_conn_info()} adcs = create_adof_conns(conn_info, None) variables = Variables(self.get_variables()) variables.set_adof_conns(adcs) materials = self.get_materials(join=True) for mat in materials: mat.time_update(None, [
Struct(terms=[self])
sfepy.base.base.Struct
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number. return nm.inf elif sh == 'str': return 'str' else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return tuple((_parse_scalar_shape(ii.strip()) for ii in sh.split(','))) else: return (int(sh),) arg_kinds = get_arg_kinds(self.ats) arg_shapes_list = self.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] # Loop allowed shapes until a match is found, else error. allowed_shapes = [] prev_shapes = {} actual_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes allowed_shapes.append(arg_shapes) n_ok = 0 for ii, arg_kind in enumerate(arg_kinds): if arg_kind in ('user', 'ts'): n_ok += 1 continue arg = args[ii] key = '%s:%s' % (self.ats[ii], self.arg_names[ii]) if self.mode is not None: extended_ats = self.ats[ii] + ('/%s' % self.mode) else: extended_ats = self.ats[ii] try: sh = arg_shapes[self.ats[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): n_el, n_qp, _dim, n_en, n_c = self.get_data_shape(arg) actual_shapes[key] = (n_c,) shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) if nm.isinf(shape): n_ok += 1 else: n_ok += shape == n_c elif arg_kind.endswith('material'): if arg is None: # Switched-off opt_material. n_ok += sh is None continue if sh is None: continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if sh == 'str': n_ok += isinstance(arg, basestr) continue shape = _parse_tuple_shape(sh) ls = len(shape) aarg = nm.array(arg, ndmin=1) actual_shapes[key] = aarg.shape # Substiture general dimension 'N' with actual value. iinfs = nm.where(nm.isinf(shape))[0] if len(iinfs): shape = list(shape) for iinf in iinfs: shape[iinf] = aarg.shape[-ls+iinf] shape = tuple(shape) if (ls > 1) or (shape[0] > 1): # Array. n_ok += shape == aarg.shape[-ls:] actual_shapes[key] = aarg.shape[-ls:] elif (ls == 1) and (shape[0] == 1): # Scalar constant. from numbers import Number n_ok += isinstance(arg, Number) else: n_ok += 1 if n_ok == len(arg_kinds): break else: term_str = self.get_str() output('allowed argument shapes for term "%s":' % term_str) output(allowed_shapes) output('actual argument shapes:') output(actual_shapes) raise ValueError('wrong arguments shapes for "%s" term! (see above)' % term_str) def standalone_setup(self): from sfepy.discrete import create_adof_conns, Variables conn_info = {'aux' : self.get_conn_info()} adcs = create_adof_conns(conn_info, None) variables = Variables(self.get_variables()) variables.set_adof_conns(adcs) materials = self.get_materials(join=True) for mat in materials: mat.time_update(None, [Struct(terms=[self])]) def call_get_fargs(self, args, kwargs): try: fargs = self.get_fargs(*args, **kwargs) except (RuntimeError, ValueError): terms.errclear() raise return fargs def call_function(self, out, fargs): try: status = self.function(out, *fargs) except (RuntimeError, ValueError): terms.errclear() raise if status: terms.errclear() raise ValueError('term evaluation failed! (%s)' % self.name) return status def eval_real(self, shape, fargs, mode='eval', term_mode=None, diff_var=None, **kwargs): out = nm.empty(shape, dtype=nm.float64) if mode == 'eval': status = self.call_function(out, fargs) # Sum over elements but not over components. out1 = nm.sum(out, 0).squeeze() return out1, status else: status = self.call_function(out, fargs) return out, status def eval_complex(self, shape, fargs, mode='eval', term_mode=None, diff_var=None, **kwargs): rout = nm.empty(shape, dtype=nm.float64) fargsd = split_complex_args(fargs) # Assuming linear forms. Then the matrix is the # same both for real and imaginary part. rstatus = self.call_function(rout, fargsd['r']) if (diff_var is None) and len(fargsd) >= 2: iout = nm.empty(shape, dtype=nm.float64) istatus = self.call_function(iout, fargsd['i']) if mode == 'eval' and len(fargsd) >= 4: irout = nm.empty(shape, dtype=nm.float64) irstatus = self.call_function(irout, fargsd['ir']) riout = nm.empty(shape, dtype=nm.float64) ristatus = self.call_function(riout, fargsd['ri']) out = (rout - iout) + (riout + irout) * 1j status = rstatus or istatus or ristatus or irstatus else: out = rout + 1j * iout status = rstatus or istatus else: out, status = rout + 0j, rstatus if mode == 'eval': out1 = nm.sum(out, 0).squeeze() return out1, status else: return out, status def evaluate(self, mode='eval', diff_var=None, standalone=True, ret_status=False, **kwargs): """ Evaluate the term. Parameters ---------- mode : 'eval' (default), or 'weak' The term evaluation mode. Returns ------- val : float or array In 'eval' mode, the term returns a single value (the integral, it does not need to be a scalar), while in 'weak' mode it returns an array for each element. status : int, optional The flag indicating evaluation success (0) or failure (nonzero). Only provided if `ret_status` is True. iels : array of ints, optional The local elements indices in 'weak' mode. Only provided in non-'eval' modes. """ if standalone: self.standalone_setup() kwargs = kwargs.copy() term_mode = kwargs.pop('term_mode', None) if mode in ('eval', 'el_eval', 'el_avg', 'qp'): args = self.get_args(**kwargs) self.check_shapes(*args) emode = 'eval' if mode == 'el_eval' else mode _args = tuple(args) + (emode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) shape, dtype = self.get_eval_shape(*_args, **kwargs) if dtype == nm.float64: val, status = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif dtype == nm.complex128: val, status = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % dtype) val *= self.sign out = (val,) elif mode == 'weak': varr = self.get_virtual_variable() if varr is None: raise ValueError('no virtual variable in weak mode! (in "%s")' % self.get_str()) if diff_var is not None: varc = self.get_variables(as_list=False)[diff_var] args = self.get_args(**kwargs) self.check_shapes(*args) _args = tuple(args) + (mode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) n_elr, n_qpr, dim, n_enr, n_cr = self.get_data_shape(varr) n_row = n_cr * n_enr if diff_var is None: shape = (n_elr, 1, n_row, 1) else: n_elc, n_qpc, dim, n_enc, n_cc = self.get_data_shape(varc) n_col = n_cc * n_enc shape = (n_elr, 1, n_row, n_col) if varr.dtype == nm.float64: vals, status = self.eval_real(shape, fargs, mode, term_mode, diff_var, **kwargs) elif varr.dtype == nm.complex128: vals, status = self.eval_complex(shape, fargs, mode, term_mode, diff_var, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % varr.dtype) if not isinstance(vals, tuple): vals *= self.sign iels = self.get_assembling_cells(vals.shape) else: vals = (self.sign * vals[0],) + vals[1:] iels = None out = (vals, iels) if goptions['check_term_finiteness']: assert_(nm.isfinite(out[0]).all(), msg='"%s" term values not finite!' % self.get_str()) if ret_status: out = out + (status,) if len(out) == 1: out = out[0] return out def assemble_to(self, asm_obj, val, iels, mode='vector', diff_var=None): """ Assemble the results of term evaluation. For standard terms, assemble the values in `val` corresponding to elements/cells `iels` into a vector or a CSR sparse matrix `asm_obj`, depending on `mode`. For terms with a dynamic connectivity (e.g. contact terms), in `'matrix'` mode, return the extra COO sparse matrix instead. The extra matrix has to be added to the global matrix by the caller. By default, this is done in :func:`Equations.evaluate() <sfepy.discrete.equations.Equations.evaluate()>`. """ import sfepy.discrete.common.extmods.assemble as asm vvar = self.get_virtual_variable() dc_type = self.get_dof_conn_type() extra = None if mode == 'vector': if asm_obj.dtype == nm.float64: assemble = asm.assemble_vector else: assert_(asm_obj.dtype == nm.complex128) assemble = asm.assemble_vector_complex for ii in range(len(val)): if not(val[ii].dtype == nm.complex128): val[ii] = nm.complex128(val[ii]) if not isinstance(val, tuple): dc = vvar.get_dof_conn(dc_type) assert_(val.shape[2] == dc.shape[1]) assemble(asm_obj, val, iels, 1.0, dc) else: vals, rows, var = val if var.eq_map is not None: eq = var.eq_map.eq rows = eq[rows] active = (rows >= 0) vals, rows = vals[active], rows[active] # Assumes no repeated indices in rows! asm_obj[rows] += vals elif mode == 'matrix': if asm_obj.dtype == nm.float64: assemble = asm.assemble_matrix else:
assert_(asm_obj.dtype == nm.complex128)
sfepy.base.base.assert_
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(term_table.keys())) raise ValueError(msg) obj = constructor(name, arg_str, integral, region, **kwargs) return obj @staticmethod def from_desc(constructor, desc, region, integrals=None): from sfepy.discrete import Integrals if integrals is None: integrals = Integrals() integral = integrals.get(desc.integral) obj = constructor(desc.name, desc.args, integral, region) obj.sign = desc.sign return obj def __init__(self, name, arg_str, integral, region, **kwargs): self.name = name self.arg_str = arg_str self.region = region self._kwargs = kwargs self._integration = self.integration self.sign = 1.0 self.set_integral(integral) def __mul__(self, other): try: mul = as_float_or_complex(other) except ValueError: raise ValueError('cannot multiply Term with %s!' % other) out = self.copy(name=self.name) out.sign = mul * self.sign return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = Terms([self, other]) else: out = NotImplemented return out def __sub__(self, other): if isinstance(other, Term): out = Terms([self, -1.0 * other]) else: out = NotImplemented return out def __pos__(self): return self def __neg__(self): out = -1.0 * self return out def get_str(self): return ('%+.2e * %s.%d.%s(%s)' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_str)) def set_integral(self, integral): """ Set the term integral. """ self.integral = integral if self.integral is not None: self.integral_name = self.integral.name def setup(self): self.function = Struct.get(self, 'function', None) self.step = 0 self.dt = 1.0 self.is_quasistatic = False self.has_region = True self.setup_formal_args() if self._kwargs: self.setup_args(**self._kwargs) else: self.args = [] def setup_formal_args(self): self.arg_names = [] self.arg_steps = {} self.arg_derivatives = {} self.arg_traces = {} parser = create_arg_parser() self.arg_desc = parser.parseString(self.arg_str) for arg in self.arg_desc: trace = False derivative = None if isinstance(arg[1], int): name, step = arg else: kind = arg[0] name, step = arg[1] if kind == 'd': derivative = arg[2] elif kind == 'tr': trace = True match = _match_material_root(name) if match: name = (match.group(1), match.group(2)) self.arg_names.append(name) self.arg_steps[name] = step self.arg_derivatives[name] = derivative self.arg_traces[name] = trace def setup_args(self, **kwargs): self._kwargs = kwargs self.args = [] for arg_name in self.arg_names: if isinstance(arg_name, basestr): self.args.append(self._kwargs[arg_name]) else: self.args.append((self._kwargs[arg_name[0]], arg_name[1])) self.classify_args() self.check_args() def assign_args(self, variables, materials, user=None): """ Check term argument existence in variables, materials, user data and assign the arguments to terms. Also check compatibility of field and term regions. """ if user is None: user = {} user.setdefault('ts', Struct()) kwargs = {} for arg_name in self.arg_names: if isinstance(arg_name, basestr): if arg_name in variables.names: kwargs[arg_name] = variables[arg_name] elif arg_name in user: kwargs[arg_name] = user[arg_name] else: raise ValueError('argument %s not found!' % arg_name) else: arg_name = arg_name[0] if arg_name in materials.names: kwargs[arg_name] = materials[arg_name] else: raise ValueError('material argument %s not found!' % arg_name) self.setup_args(**kwargs) def classify_args(self): """ Classify types of the term arguments and find matching call signature. A state variable can be in place of a parameter variable and vice versa. """ self.names = Struct(name='arg_names', material=[], variable=[], user=[], state=[], virtual=[], parameter=[]) # Prepare for 'opt_material' - just prepend a None argument if needed. if isinstance(self.arg_types[0], tuple): arg_types = self.arg_types[0] else: arg_types = self.arg_types if len(arg_types) == (len(self.args) + 1): self.args.insert(0, (None, None)) self.arg_names.insert(0, (None, None)) if isinstance(self.arg_types[0], tuple): assert_(len(self.modes) == len(self.arg_types)) # Find matching call signature using variable arguments - material # and user arguments are ignored! matched = [] for it, arg_types in enumerate(self.arg_types): arg_kinds = get_arg_kinds(arg_types) if self._check_variables(arg_kinds): matched.append((it, arg_kinds)) if len(matched) == 1: i_match, arg_kinds = matched[0] arg_types = self.arg_types[i_match] self.mode = self.modes[i_match] elif len(matched) == 0: msg = 'cannot match arguments! (%s)' % self.arg_names raise ValueError(msg) else: msg = 'ambiguous arguments! (%s)' % self.arg_names raise ValueError(msg) else: arg_types = self.arg_types arg_kinds = get_arg_kinds(self.arg_types) self.mode = Struct.get(self, 'mode', None) if not self._check_variables(arg_kinds): raise ValueError('cannot match variables! (%s)' % self.arg_names) # Set actual argument types. self.ats = list(arg_types) for ii, arg_kind in enumerate(arg_kinds): name = self.arg_names[ii] if arg_kind.endswith('variable'): names = self.names.variable if arg_kind == 'virtual_variable': self.names.virtual.append(name) elif arg_kind == 'state_variable': self.names.state.append(name) elif arg_kind == 'parameter_variable': self.names.parameter.append(name) elif arg_kind.endswith('material'): names = self.names.material else: names = self.names.user names.append(name) self.n_virtual = len(self.names.virtual) if self.n_virtual > 1: raise ValueError('at most one virtual variable is allowed! (%d)' % self.n_virtual) self.set_arg_types() self.setup_integration() def _check_variables(self, arg_kinds): for ii, arg_kind in enumerate(arg_kinds): if arg_kind.endswith('variable'): var = self.args[ii] check = {'virtual_variable' : var.is_virtual, 'state_variable' : var.is_state_or_parameter, 'parameter_variable' : var.is_state_or_parameter} if not check[arg_kind](): return False else: return True def set_arg_types(self): pass def check_args(self): """ Common checking to all terms. Check compatibility of field and term regions. """ vns = self.get_variable_names() for name in vns: field = self._kwargs[name].get_field() if field is None: continue if not nm.all(in1d(self.region.vertices, field.region.vertices)): msg = ('%s: incompatible regions: (self, field %s)' + '(%s in %s)') %\ (self.name, field.name, self.region.vertices, field.region.vertices) raise ValueError(msg) def get_variable_names(self): return self.names.variable def get_material_names(self): out = [] for aux in self.names.material: if aux[0] is not None: out.append(aux[0]) return out def get_user_names(self): return self.names.user def get_virtual_name(self): if not self.names.virtual: return None var = self.get_virtual_variable() return var.name def get_state_names(self): """ If variables are given, return only true unknowns whose data are of the current time step (0). """ variables = self.get_state_variables() return [var.name for var in variables] def get_parameter_names(self): return copy(self.names.parameter) def get_conn_key(self): """The key to be used in DOF connectivity information.""" key = (self.name,) + tuple(self.arg_names) key += (self.integral_name, self.region.name) return key def get_conn_info(self): vvar = self.get_virtual_variable() svars = self.get_state_variables() pvars = self.get_parameter_variables() all_vars = self.get_variables() dc_type = self.get_dof_conn_type() tgs = self.get_geometry_types() v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: if vvar.name in tgs: v_tg = tgs[vvar.name] else: v_tg = None else: # No virtual variable -> all unknowns are in fact known parameters. pvars += svars svars = [] region = self.get_region() if region is not None: is_any_trace = reduce(lambda x, y: x or y, list(self.arg_traces.values())) if is_any_trace: region.setup_mirror_region() vals = [] aux_pvars = [] for svar in svars: # Allow only true state variables. if not svar.is_state(): aux_pvars.append(svar) continue field = svar.get_field() is_trace = self.arg_traces[svar.name] if svar.name in tgs: ps_tg = tgs[svar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=svar, primary=svar, has_virtual=True, has_state=True, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) pvars += aux_pvars for pvar in pvars: field = pvar.get_field() is_trace = self.arg_traces[pvar.name] if pvar.name in tgs: ps_tg = tgs[pvar.name] else: ps_tg = v_tg val = ConnInfo(virtual=vvar, state=None, primary=pvar.get_primary(), has_virtual=vvar is not None, has_state=False, is_trace=is_trace, dc_type=dc_type, v_tg=v_tg, ps_tg=ps_tg, region=region, all_vars=all_vars) vals.append(val) if vvar and (len(vals) == 0): # No state, parameter variables, just the virtual one. val = ConnInfo(virtual=vvar, state=vvar.get_primary(), primary=vvar.get_primary(), has_virtual=True, has_state=False, is_trace=False, dc_type=dc_type, v_tg=v_tg, ps_tg=v_tg, region=region, all_vars=all_vars) vals.append(val) return vals def get_args_by_name(self, arg_names): """ Return arguments by name. """ out = [] for name in arg_names: try: ii = self.arg_names.index(name) except ValueError: raise ValueError('non-existing argument! (%s)' % name) out.append(self.args[ii]) return out def get_args(self, arg_types=None, **kwargs): """ Return arguments by type as specified in arg_types (or self.ats). Arguments in **kwargs can override the ones assigned at the term construction - this is useful for passing user data. """ ats = self.ats if arg_types is None: arg_types = ats args = [] region_name, iorder = self.region.name, self.integral.order for at in arg_types: ii = ats.index(at) arg_name = self.arg_names[ii] if isinstance(arg_name, basestr): if arg_name in kwargs: args.append(kwargs[arg_name]) else: args.append(self.args[ii]) else: mat, par_name = self.args[ii] if mat is not None: mat_data = mat.get_data((region_name, iorder), par_name) else: mat_data = None args.append(mat_data) return args def get_kwargs(self, keys, **kwargs): """Extract arguments from **kwargs listed in keys (default is None).""" return [kwargs.get(name) for name in keys] def get_arg_name(self, arg_type, full=False, join=None): """ Get the name of the argument specified by `arg_type.` Parameters ---------- arg_type : str The argument type string. full : bool If True, return the full name. For example, if the name of a variable argument is 'u' and its time derivative is requested, the full name is 'du/dt'. join : str, optional Optionally, the material argument name tuple can be joined to a single string using the `join` string. Returns ------- name : str The argument name. """ try: ii = self.ats.index(arg_type) except ValueError: return None name = self.arg_names[ii] if full: # Include derivatives. if self.arg_derivatives[name]: name = 'd%s/%s' % (name, self.arg_derivatives[name]) if (join is not None) and isinstance(name, tuple): name = join.join(name) return name def setup_integration(self): self.has_geometry = True self.geometry_types = {} if isinstance(self.integration, basestr): for var in self.get_variables(): self.geometry_types[var.name] = self.integration else: if self.mode is not None: self.integration = self._integration[self.mode] if self.integration is not None: for arg_type, gtype in six.iteritems(self.integration): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.values())) if 'surface_extra' in gtypes: self.dof_conn_type = 'volume' elif len(gtypes): self.dof_conn_type = gtypes[0] def get_region(self): return self.region def get_geometry_types(self): """ Returns ------- out : dict The required geometry types for each variable argument. """ return self.geometry_types def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def get_assembling_cells(self, shape=None): """ Return the assembling cell indices into a DOF connectivity. """ cells = nm.arange(shape[0], dtype=nm.int32) return cells def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic if 'ts' in self._kwargs: self._kwargs['ts'].update(ts) def advance(self, ts): """ Advance to the next time step. Implemented in subclasses. """ def get_vector(self, variable): """Get the vector stored in `variable` according to self.arg_steps and self.arg_derivatives. Supports only the backward difference w.r.t. time.""" name = variable.name return variable(step=self.arg_steps[name], derivative=self.arg_derivatives[name]) def get_variables(self, as_list=True): if as_list: variables = self.get_args_by_name(self.names.variable) else: variables = {} for var in self.get_args_by_name(self.names.variable): variables[var.name] = var return variables def get_virtual_variable(self): aux = self.get_args_by_name(self.names.virtual) if len(aux) == 1: var = aux[0] else: var = None return var def get_state_variables(self, unknown_only=False): variables = self.get_args_by_name(self.names.state) if unknown_only: variables = [var for var in variables if (var.kind == 'unknown') and (self.arg_steps[var.name] == 0)] return variables def get_parameter_variables(self): return self.get_args_by_name(self.names.parameter) def get_materials(self, join=False): materials = self.get_args_by_name(self.names.material) for mat in materials: if mat[0] is None: materials.remove(mat) if join: materials = list(set(mat[0] for mat in materials)) return materials def get_qp_key(self): """ Return a key identifying uniquely the term quadrature points. """ return (self.region.name, self.integral.order) def get_physical_qps(self): """ Get physical quadrature points corresponding to the term region and integral. """ from sfepy.discrete.common.mappings import get_physical_qps, PhysicalQPs if self.integration == 'point': phys_qps = PhysicalQPs() else: phys_qps = get_physical_qps(self.region, self.integral) return phys_qps def get_mapping(self, variable, get_saved=False, return_key=False): """ Get the reference mapping from a variable. Notes ----- This is a convenience wrapper of Field.get_mapping() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.field.get_mapping(region, self.integral, integration, get_saved=get_saved, return_key=return_key) return out def get_data_shape(self, variable): """ Get data shape information from variable. Notes ----- This is a convenience wrapper of FieldVariable.get_data_shape() that initializes the arguments using the term data. """ integration = self.geometry_types[variable.name] is_trace = self.arg_traces[variable.name] if is_trace: region = self.region.get_mirror_region() else: region = self.region out = variable.get_data_shape(self.integral, integration, region.name) return out def get(self, variable, quantity_name, bf=None, integration=None, step=None, time_derivative=None): """ Get the named quantity related to the variable. Notes ----- This is a convenience wrapper of Variable.evaluate() that initializes the arguments using the term data. """ name = variable.name step = get_default(step, self.arg_steps[name]) time_derivative = get_default(time_derivative, self.arg_derivatives[name]) integration = get_default(integration, self.geometry_types[name]) data = variable.evaluate(mode=quantity_name, region=self.region, integral=self.integral, integration=integration, step=step, time_derivative=time_derivative, is_trace=self.arg_traces[name], bf=bf) return data def check_shapes(self, *args, **kwargs): """ Check term argument shapes at run-time. """ from sfepy.base.base import output from sfepy.mechanics.tensors import dim2sym dim = self.region.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number. return nm.inf elif sh == 'str': return 'str' else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return tuple((_parse_scalar_shape(ii.strip()) for ii in sh.split(','))) else: return (int(sh),) arg_kinds = get_arg_kinds(self.ats) arg_shapes_list = self.arg_shapes if not isinstance(arg_shapes_list, list): arg_shapes_list = [arg_shapes_list] # Loop allowed shapes until a match is found, else error. allowed_shapes = [] prev_shapes = {} actual_shapes = {} for _arg_shapes in arg_shapes_list: # Unset shapes are taken from the previous iteration. arg_shapes = copy(prev_shapes) arg_shapes.update(_arg_shapes) prev_shapes = arg_shapes allowed_shapes.append(arg_shapes) n_ok = 0 for ii, arg_kind in enumerate(arg_kinds): if arg_kind in ('user', 'ts'): n_ok += 1 continue arg = args[ii] key = '%s:%s' % (self.ats[ii], self.arg_names[ii]) if self.mode is not None: extended_ats = self.ats[ii] + ('/%s' % self.mode) else: extended_ats = self.ats[ii] try: sh = arg_shapes[self.ats[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): n_el, n_qp, _dim, n_en, n_c = self.get_data_shape(arg) actual_shapes[key] = (n_c,) shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) if nm.isinf(shape): n_ok += 1 else: n_ok += shape == n_c elif arg_kind.endswith('material'): if arg is None: # Switched-off opt_material. n_ok += sh is None continue if sh is None: continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if sh == 'str': n_ok += isinstance(arg, basestr) continue shape = _parse_tuple_shape(sh) ls = len(shape) aarg = nm.array(arg, ndmin=1) actual_shapes[key] = aarg.shape # Substiture general dimension 'N' with actual value. iinfs = nm.where(nm.isinf(shape))[0] if len(iinfs): shape = list(shape) for iinf in iinfs: shape[iinf] = aarg.shape[-ls+iinf] shape = tuple(shape) if (ls > 1) or (shape[0] > 1): # Array. n_ok += shape == aarg.shape[-ls:] actual_shapes[key] = aarg.shape[-ls:] elif (ls == 1) and (shape[0] == 1): # Scalar constant. from numbers import Number n_ok += isinstance(arg, Number) else: n_ok += 1 if n_ok == len(arg_kinds): break else: term_str = self.get_str() output('allowed argument shapes for term "%s":' % term_str) output(allowed_shapes) output('actual argument shapes:') output(actual_shapes) raise ValueError('wrong arguments shapes for "%s" term! (see above)' % term_str) def standalone_setup(self): from sfepy.discrete import create_adof_conns, Variables conn_info = {'aux' : self.get_conn_info()} adcs = create_adof_conns(conn_info, None) variables = Variables(self.get_variables()) variables.set_adof_conns(adcs) materials = self.get_materials(join=True) for mat in materials: mat.time_update(None, [Struct(terms=[self])]) def call_get_fargs(self, args, kwargs): try: fargs = self.get_fargs(*args, **kwargs) except (RuntimeError, ValueError): terms.errclear() raise return fargs def call_function(self, out, fargs): try: status = self.function(out, *fargs) except (RuntimeError, ValueError): terms.errclear() raise if status: terms.errclear() raise ValueError('term evaluation failed! (%s)' % self.name) return status def eval_real(self, shape, fargs, mode='eval', term_mode=None, diff_var=None, **kwargs): out = nm.empty(shape, dtype=nm.float64) if mode == 'eval': status = self.call_function(out, fargs) # Sum over elements but not over components. out1 = nm.sum(out, 0).squeeze() return out1, status else: status = self.call_function(out, fargs) return out, status def eval_complex(self, shape, fargs, mode='eval', term_mode=None, diff_var=None, **kwargs): rout = nm.empty(shape, dtype=nm.float64) fargsd = split_complex_args(fargs) # Assuming linear forms. Then the matrix is the # same both for real and imaginary part. rstatus = self.call_function(rout, fargsd['r']) if (diff_var is None) and len(fargsd) >= 2: iout = nm.empty(shape, dtype=nm.float64) istatus = self.call_function(iout, fargsd['i']) if mode == 'eval' and len(fargsd) >= 4: irout = nm.empty(shape, dtype=nm.float64) irstatus = self.call_function(irout, fargsd['ir']) riout = nm.empty(shape, dtype=nm.float64) ristatus = self.call_function(riout, fargsd['ri']) out = (rout - iout) + (riout + irout) * 1j status = rstatus or istatus or ristatus or irstatus else: out = rout + 1j * iout status = rstatus or istatus else: out, status = rout + 0j, rstatus if mode == 'eval': out1 = nm.sum(out, 0).squeeze() return out1, status else: return out, status def evaluate(self, mode='eval', diff_var=None, standalone=True, ret_status=False, **kwargs): """ Evaluate the term. Parameters ---------- mode : 'eval' (default), or 'weak' The term evaluation mode. Returns ------- val : float or array In 'eval' mode, the term returns a single value (the integral, it does not need to be a scalar), while in 'weak' mode it returns an array for each element. status : int, optional The flag indicating evaluation success (0) or failure (nonzero). Only provided if `ret_status` is True. iels : array of ints, optional The local elements indices in 'weak' mode. Only provided in non-'eval' modes. """ if standalone: self.standalone_setup() kwargs = kwargs.copy() term_mode = kwargs.pop('term_mode', None) if mode in ('eval', 'el_eval', 'el_avg', 'qp'): args = self.get_args(**kwargs) self.check_shapes(*args) emode = 'eval' if mode == 'el_eval' else mode _args = tuple(args) + (emode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) shape, dtype = self.get_eval_shape(*_args, **kwargs) if dtype == nm.float64: val, status = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif dtype == nm.complex128: val, status = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % dtype) val *= self.sign out = (val,) elif mode == 'weak': varr = self.get_virtual_variable() if varr is None: raise ValueError('no virtual variable in weak mode! (in "%s")' % self.get_str()) if diff_var is not None: varc = self.get_variables(as_list=False)[diff_var] args = self.get_args(**kwargs) self.check_shapes(*args) _args = tuple(args) + (mode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) n_elr, n_qpr, dim, n_enr, n_cr = self.get_data_shape(varr) n_row = n_cr * n_enr if diff_var is None: shape = (n_elr, 1, n_row, 1) else: n_elc, n_qpc, dim, n_enc, n_cc = self.get_data_shape(varc) n_col = n_cc * n_enc shape = (n_elr, 1, n_row, n_col) if varr.dtype == nm.float64: vals, status = self.eval_real(shape, fargs, mode, term_mode, diff_var, **kwargs) elif varr.dtype == nm.complex128: vals, status = self.eval_complex(shape, fargs, mode, term_mode, diff_var, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % varr.dtype) if not isinstance(vals, tuple): vals *= self.sign iels = self.get_assembling_cells(vals.shape) else: vals = (self.sign * vals[0],) + vals[1:] iels = None out = (vals, iels) if goptions['check_term_finiteness']: assert_(nm.isfinite(out[0]).all(), msg='"%s" term values not finite!' % self.get_str()) if ret_status: out = out + (status,) if len(out) == 1: out = out[0] return out def assemble_to(self, asm_obj, val, iels, mode='vector', diff_var=None): """ Assemble the results of term evaluation. For standard terms, assemble the values in `val` corresponding to elements/cells `iels` into a vector or a CSR sparse matrix `asm_obj`, depending on `mode`. For terms with a dynamic connectivity (e.g. contact terms), in `'matrix'` mode, return the extra COO sparse matrix instead. The extra matrix has to be added to the global matrix by the caller. By default, this is done in :func:`Equations.evaluate() <sfepy.discrete.equations.Equations.evaluate()>`. """ import sfepy.discrete.common.extmods.assemble as asm vvar = self.get_virtual_variable() dc_type = self.get_dof_conn_type() extra = None if mode == 'vector': if asm_obj.dtype == nm.float64: assemble = asm.assemble_vector else: assert_(asm_obj.dtype == nm.complex128) assemble = asm.assemble_vector_complex for ii in range(len(val)): if not(val[ii].dtype == nm.complex128): val[ii] = nm.complex128(val[ii]) if not isinstance(val, tuple): dc = vvar.get_dof_conn(dc_type) assert_(val.shape[2] == dc.shape[1]) assemble(asm_obj, val, iels, 1.0, dc) else: vals, rows, var = val if var.eq_map is not None: eq = var.eq_map.eq rows = eq[rows] active = (rows >= 0) vals, rows = vals[active], rows[active] # Assumes no repeated indices in rows! asm_obj[rows] += vals elif mode == 'matrix': if asm_obj.dtype == nm.float64: assemble = asm.assemble_matrix else: assert_(asm_obj.dtype == nm.complex128) assemble = asm.assemble_matrix_complex svar = diff_var tmd = (asm_obj.data, asm_obj.indptr, asm_obj.indices) if ((asm_obj.dtype == nm.complex128) and (val.dtype == nm.float64)): val = val.astype(nm.complex128) sign = 1.0 if self.arg_derivatives[svar.name]: if not self.is_quasistatic or (self.step > 0): sign *= 1.0 / self.dt else: sign = 0.0 if not isinstance(val, tuple): rdc = vvar.get_dof_conn(dc_type) is_trace = self.arg_traces[svar.name] cdc = svar.get_dof_conn(dc_type, is_trace=is_trace)
assert_(val.shape[2:] == (rdc.shape[1], cdc.shape[1]))
sfepy.base.base.assert_
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(term_table.keys())) raise ValueError(msg) try: region = regions[td.region] except IndexError: raise KeyError('region "%s" does not exist!' % td.region) term = Term.from_desc(constructor, td, region, integrals=integrals) terms.append(term) return terms def __init__(self, objs=None): Container.__init__(self, objs=objs) self.update_expression() def insert(self, ii, obj): Container.insert(self, ii, obj) self.update_expression() def append(self, obj): Container.append(self, obj) self.update_expression() def update_expression(self): self.expression = [] for term in self: aux = [term.sign, term.name, term.arg_str, term.integral_name, term.region.name] self.expression.append(aux) def __mul__(self, other): out = Terms() for name, term in self.iteritems(): out.append(term * other) return out def __rmul__(self, other): return self * other def __add__(self, other): if isinstance(other, Term): out = self.copy() out.append(other) elif isinstance(other, Terms): out = Terms(self._objs + other._objs) else: raise ValueError('cannot add Terms with %s!' % other) return out def __radd__(self, other): return self + other def __sub__(self, other): if isinstance(other, Term): out = self + (-other) elif isinstance(other, Terms): out = self + (-other) else: raise ValueError('cannot subtract Terms with %s!' % other) return out def __rsub__(self, other): return -self + other def __pos__(self): return self def __neg__(self): return -1.0 * self def setup(self): for term in self: term.setup() def assign_args(self, variables, materials, user=None): """ Assign all term arguments. """ for term in self: term.assign_args(variables, materials, user) def get_variable_names(self): out = [] for term in self: out.extend(term.get_variable_names()) return list(set(out)) def get_material_names(self): out = [] for term in self: out.extend(term.get_material_names()) return list(set(out)) def get_user_names(self): out = [] for term in self: out.extend(term.get_user_names()) return list(set(out)) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['1_2', '2_3', '2_4', '3_4', '3_8'] @staticmethod def new(name, integral, region, **kwargs): from sfepy.terms import term_table arg_str = _match_args(name) if arg_str is not None: name, arg_str = arg_str.groups() else: raise ValueError('bad term syntax! (%s)' % name) if name in term_table: constructor = term_table[name] else: msg = "term '%s' is not in %s" % (name, sorted(
term_table.keys()
sfepy.terms.term_table.keys
from __future__ import absolute_import import re from copy import copy import numpy as nm from sfepy.base.base import (as_float_or_complex, get_default, assert_, Container, Struct, basestr, goptions) from sfepy.base.compat import in1d # Used for imports in term files. from sfepy.terms.extmods import terms import six from six.moves import range from functools import reduce _match_args = re.compile('^([^\(\}]*)\((.*)\)$').match _match_virtual = re.compile('^virtual$').match _match_state = re.compile('^state(_[_a-zA-Z0-9]+)?$').match _match_parameter = re.compile('^parameter(_[_a-zA-Z0-9]+)?$').match _match_material = re.compile('^material(_[_a-zA-Z0-9]+)?$').match _match_material_opt = re.compile('^opt_material(_[_a-zA-Z0-9]+)?$').match _match_material_root = re.compile('(.+)\.(.*)').match _match_ts = re.compile('^ts$').match def get_arg_kinds(arg_types): """ Translate `arg_types` of a Term to a canonical form. Parameters ---------- arg_types : tuple of strings The term argument types, as given in the `arg_types` attribute. Returns ------- arg_kinds : list of strings The argument kinds - one of 'virtual_variable', 'state_variable', 'parameter_variable', 'opt_material', 'ts', 'user'. """ arg_kinds = [] for ii, arg_type in enumerate(arg_types): if _match_virtual(arg_type): arg_kinds.append('virtual_variable') elif _match_state(arg_type): arg_kinds.append('state_variable') elif _match_parameter(arg_type): arg_kinds.append('parameter_variable') elif _match_material(arg_type): arg_kinds.append('material') elif _match_material_opt(arg_type): arg_kinds.append('opt_material') if ii > 0: msg = 'opt_material at position %d, must be at 0!' % ii raise ValueError(msg) elif _match_ts(arg_type): arg_kinds.append('ts') else: arg_kinds.append('user') return arg_kinds def get_shape_kind(integration): """ Get data shape kind for given integration type. """ if integration == 'surface': shape_kind = 'surface' elif integration in ('volume', 'plate', 'surface_extra'): shape_kind = 'volume' elif integration == 'point': shape_kind = 'point' else: raise NotImplementedError('unsupported term integration! (%s)' % integration) return shape_kind def split_complex_args(args): """ Split complex arguments to real and imaginary parts. Returns ------- newargs : dictionary Dictionary with lists corresponding to `args` such that each argument of numpy.complex128 data type is split to its real and imaginary part. The output depends on the number of complex arguments in 'args': - 0: list (key 'r') identical to input one - 1: two lists with keys 'r', 'i' corresponding to real and imaginary parts - 2: output dictionary contains four lists: - 'r' - real(arg1), real(arg2) - 'i' - imag(arg1), imag(arg2) - 'ri' - real(arg1), imag(arg2) - 'ir' - imag(arg1), real(arg2) """ newargs = {} cai = [] for ii, arg in enumerate(args): if isinstance(arg, nm.ndarray) and (arg.dtype == nm.complex128): cai.append(ii) if len(cai) > 0: newargs['r'] = list(args[:]) newargs['i'] = list(args[:]) arg1 = cai[0] newargs['r'][arg1] = args[arg1].real.copy() newargs['i'][arg1] = args[arg1].imag.copy() if len(cai) == 2: arg2 = cai[1] newargs['r'][arg2] = args[arg2].real.copy() newargs['i'][arg2] = args[arg2].imag.copy() newargs['ri'] = list(args[:]) newargs['ir'] = list(args[:]) newargs['ri'][arg1] = newargs['r'][arg1] newargs['ri'][arg2] = newargs['i'][arg2] newargs['ir'][arg1] = newargs['i'][arg1] newargs['ir'][arg2] = newargs['r'][arg2] elif len(cai) > 2: raise NotImplementedError('more than 2 complex arguments! (%d)' % len(cai)) else: newargs['r'] = args[:] return newargs def create_arg_parser(): from pyparsing import Literal, Word, delimitedList, Group, \ StringStart, StringEnd, Optional, nums, alphas, alphanums inumber = Word("+-" + nums, nums) history = Optional(Literal('[').suppress() + inumber + Literal(']').suppress(), default=0)("history") history.setParseAction(lambda str, loc, toks: int(toks[0])) variable = Group(Word(alphas, alphanums + '._') + history) derivative = Group(Literal('d') + variable\ + Literal('/').suppress() + Literal('dt')) trace = Group(Literal('tr') + Literal('(').suppress() + variable \ + Literal(')').suppress()) generalized_var = derivative | trace | variable args = StringStart() + delimitedList(generalized_var) + StringEnd() return args class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region() else: return self.region def get_region_name(self, can_trace=True): if self.is_trace and can_trace: reg = self.region.get_mirror_region() else: reg = self.region if reg is not None: return reg.name else: return None class Terms(Container): @staticmethod def from_desc(term_descs, regions, integrals=None): """ Create terms, assign each term its region. """ from sfepy.terms import term_table terms = Terms() for td in term_descs: try: constructor = term_table[td.name] except: msg = "term '%s' is not in %s" % (td.name, sorted(
term_table.keys()
sfepy.terms.term_table.keys
#%% import numpy as np from sfepy.discrete.fem import Mesh, FEDomain, Field mesh_path = 'C:/Users/lzy71/miniconda3/envs/lego/lib/site-packages/sfepy/meshes/2d/rectangle_tri.mesh' #%% mesh =
Mesh.from_file(mesh_path)
sfepy.discrete.fem.Mesh.from_file
#%% import numpy as np from sfepy.discrete.fem import Mesh, FEDomain, Field mesh_path = 'C:/Users/lzy71/miniconda3/envs/lego/lib/site-packages/sfepy/meshes/2d/rectangle_tri.mesh' #%% mesh = Mesh.from_file(mesh_path) domain =
FEDomain('domain', mesh)
sfepy.discrete.fem.FEDomain
#%% import numpy as np from sfepy.discrete.fem import Mesh, FEDomain, Field mesh_path = 'C:/Users/lzy71/miniconda3/envs/lego/lib/site-packages/sfepy/meshes/2d/rectangle_tri.mesh' #%% mesh = Mesh.from_file(mesh_path) domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:, 0] eps = 1e-8 * (max_x - min_x) omega = domain.create_region('Omega', 'all') # %% from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem ) field =
Field.from_args('fu', np.float64, 'vector', omega, approx_order=2)
sfepy.discrete.fem.Field.from_args
#%% import numpy as np from sfepy.discrete.fem import Mesh, FEDomain, Field mesh_path = 'C:/Users/lzy71/miniconda3/envs/lego/lib/site-packages/sfepy/meshes/2d/rectangle_tri.mesh' #%% mesh = Mesh.from_file(mesh_path) domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:, 0] eps = 1e-8 * (max_x - min_x) omega = domain.create_region('Omega', 'all') # %% from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem ) field = Field.from_args('fu', np.float64, 'vector', omega, approx_order=2) u =
FieldVariable('u', 'unknown', field)
sfepy.discrete.FieldVariable
#%% import numpy as np from sfepy.discrete.fem import Mesh, FEDomain, Field mesh_path = 'C:/Users/lzy71/miniconda3/envs/lego/lib/site-packages/sfepy/meshes/2d/rectangle_tri.mesh' #%% mesh = Mesh.from_file(mesh_path) domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:, 0] eps = 1e-8 * (max_x - min_x) omega = domain.create_region('Omega', 'all') # %% from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem ) field = Field.from_args('fu', np.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', field) v =
FieldVariable('v', 'test', field, primary_var_name='u')
sfepy.discrete.FieldVariable
#%% import numpy as np from sfepy.discrete.fem import Mesh, FEDomain, Field mesh_path = 'C:/Users/lzy71/miniconda3/envs/lego/lib/site-packages/sfepy/meshes/2d/rectangle_tri.mesh' #%% mesh = Mesh.from_file(mesh_path) domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:, 0] eps = 1e-8 * (max_x - min_x) omega = domain.create_region('Omega', 'all') # %% from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem ) field = Field.from_args('fu', np.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') # %% from sfepy.mechanics.matcoefs import stiffness_from_lame m = Material('m', D=stiffness_from_lame(dim=2, lam=1.0, mu=1.0)) f =
Material('f', val=[[0.02], [0.01]])
sfepy.discrete.Material
#%% import numpy as np from sfepy.discrete.fem import Mesh, FEDomain, Field mesh_path = 'C:/Users/lzy71/miniconda3/envs/lego/lib/site-packages/sfepy/meshes/2d/rectangle_tri.mesh' #%% mesh = Mesh.from_file(mesh_path) domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:, 0] eps = 1e-8 * (max_x - min_x) omega = domain.create_region('Omega', 'all') # %% from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem ) field = Field.from_args('fu', np.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') # %% from sfepy.mechanics.matcoefs import stiffness_from_lame m = Material('m', D=stiffness_from_lame(dim=2, lam=1.0, mu=1.0)) f = Material('f', val=[[0.02], [0.01]]) integral =
Integral('i', order=3)
sfepy.discrete.Integral
#%% import numpy as np from sfepy.discrete.fem import Mesh, FEDomain, Field mesh_path = 'C:/Users/lzy71/miniconda3/envs/lego/lib/site-packages/sfepy/meshes/2d/rectangle_tri.mesh' #%% mesh = Mesh.from_file(mesh_path) domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:, 0] eps = 1e-8 * (max_x - min_x) omega = domain.create_region('Omega', 'all') # %% from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem ) field = Field.from_args('fu', np.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') # %% from sfepy.mechanics.matcoefs import stiffness_from_lame m = Material('m', D=stiffness_from_lame(dim=2, lam=1.0, mu=1.0)) f = Material('f', val=[[0.02], [0.01]]) integral = Integral('i', order=3) # %% from sfepy.terms import Term t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) t2 = Term.new('dw_volume_lvf(f.val, v)', integral, omega, f=f, v=v) eq =
Equation('balance', t1 + t2)
sfepy.discrete.Equation
#%% import numpy as np from sfepy.discrete.fem import Mesh, FEDomain, Field mesh_path = 'C:/Users/lzy71/miniconda3/envs/lego/lib/site-packages/sfepy/meshes/2d/rectangle_tri.mesh' #%% mesh = Mesh.from_file(mesh_path) domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:, 0] eps = 1e-8 * (max_x - min_x) omega = domain.create_region('Omega', 'all') # %% from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem ) field = Field.from_args('fu', np.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') # %% from sfepy.mechanics.matcoefs import stiffness_from_lame m = Material('m', D=stiffness_from_lame(dim=2, lam=1.0, mu=1.0)) f = Material('f', val=[[0.02], [0.01]]) integral = Integral('i', order=3) # %% from sfepy.terms import Term t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) t2 = Term.new('dw_volume_lvf(f.val, v)', integral, omega, f=f, v=v) eq = Equation('balance', t1 + t2) eqs =
Equations([eq])
sfepy.discrete.Equations
#%% import numpy as np from sfepy.discrete.fem import Mesh, FEDomain, Field mesh_path = 'C:/Users/lzy71/miniconda3/envs/lego/lib/site-packages/sfepy/meshes/2d/rectangle_tri.mesh' #%% mesh = Mesh.from_file(mesh_path) domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:, 0] eps = 1e-8 * (max_x - min_x) omega = domain.create_region('Omega', 'all') # %% from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem ) field = Field.from_args('fu', np.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') # %% from sfepy.mechanics.matcoefs import stiffness_from_lame m = Material('m', D=stiffness_from_lame(dim=2, lam=1.0, mu=1.0)) f = Material('f', val=[[0.02], [0.01]]) integral = Integral('i', order=3) # %% from sfepy.terms import Term t1 = Term.new('dw_lin_elastic(m.D, v, u)', integral, omega, m=m, v=v, u=u) t2 = Term.new('dw_volume_lvf(f.val, v)', integral, omega, f=f, v=v) eq = Equation('balance', t1 + t2) eqs = Equations([eq]) #%% pb =
Problem('elasticity', equations=eqs)
sfepy.discrete.Problem
#%% import numpy as np from sfepy.discrete.fem import Mesh, FEDomain, Field mesh_path = 'C:/Users/lzy71/miniconda3/envs/lego/lib/site-packages/sfepy/meshes/2d/rectangle_tri.mesh' #%% mesh = Mesh.from_file(mesh_path) domain = FEDomain('domain', mesh) min_x, max_x = domain.get_mesh_bounding_box()[:, 0] eps = 1e-8 * (max_x - min_x) omega = domain.create_region('Omega', 'all') # %% from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem ) field = Field.from_args('fu', np.float64, 'vector', omega, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') # %% from sfepy.mechanics.matcoefs import stiffness_from_lame m = Material('m', D=
stiffness_from_lame(dim=2, lam=1.0, mu=1.0)
sfepy.mechanics.matcoefs.stiffness_from_lame
from __future__ import absolute_import import numpy as nm from sfepy.base.base import load_classes, Struct from sfepy import get_paths def transform_basis(transform, bf): """ Transform a basis `bf` using `transform` array of matrices. """ if bf.ndim == 3: nbf = nm.einsum('cij,qdj->cqdi', transform, bf, order='C') elif bf.ndim == 4: if bf.shape[0] == 1: nbf = nm.einsum('cij,qdj->cqdi', transform, bf[0], order='C') else: nbf = nm.einsum('cij,cqdj->cqdi', transform, bf, order='C') # Note: the 2nd derivatives are not supported here. # Workaround for NumPy 1.14.0 - order is ignored(?) nbf = nm.ascontiguousarray(nbf) return nbf class PolySpace(Struct): """Abstract polynomial space class.""" _all = None keys = { (0, 1) : 'simplex', (1, 2) : 'simplex', (2, 3) : 'simplex', (3, 4) : 'simplex', (2, 4) : 'tensor_product', (3, 8) : 'tensor_product', } @staticmethod def any_from_args(name, geometry, order, base='lagrange', force_bubble=False): """ Construct a particular polynomial space classes according to the arguments passed in. """ if name is None: name = PolySpace.suggest_name(geometry, order, base, force_bubble) if PolySpace._all is None: ps_files =
get_paths('sfepy/discrete/fem/poly_spaces.py')
sfepy.get_paths
from __future__ import absolute_import import numpy as nm from sfepy.base.base import load_classes, Struct from sfepy import get_paths def transform_basis(transform, bf): """ Transform a basis `bf` using `transform` array of matrices. """ if bf.ndim == 3: nbf = nm.einsum('cij,qdj->cqdi', transform, bf, order='C') elif bf.ndim == 4: if bf.shape[0] == 1: nbf = nm.einsum('cij,qdj->cqdi', transform, bf[0], order='C') else: nbf = nm.einsum('cij,cqdj->cqdi', transform, bf, order='C') # Note: the 2nd derivatives are not supported here. # Workaround for NumPy 1.14.0 - order is ignored(?) nbf = nm.ascontiguousarray(nbf) return nbf class PolySpace(Struct): """Abstract polynomial space class.""" _all = None keys = { (0, 1) : 'simplex', (1, 2) : 'simplex', (2, 3) : 'simplex', (3, 4) : 'simplex', (2, 4) : 'tensor_product', (3, 8) : 'tensor_product', } @staticmethod def any_from_args(name, geometry, order, base='lagrange', force_bubble=False): """ Construct a particular polynomial space classes according to the arguments passed in. """ if name is None: name = PolySpace.suggest_name(geometry, order, base, force_bubble) if PolySpace._all is None: ps_files = get_paths('sfepy/discrete/fem/poly_spaces.py') ps_files +=
get_paths('sfepy/discrete/dg/poly_spaces.py')
sfepy.get_paths
# This example implements homogenization of porous structures undergoing finite strains. # # largedef_porous_mac.py - problem at (global) macroscopic level # largedef_porous_mic.py - local subproblems, homogenized coefficients # # The mathematical model and numerical results are described in: # # <NAME>., <NAME>. # Homogenization of large deforming fluid-saturated porous structures # https://arxiv.org/abs/2012.03730 # # Run simulation: # # ./simple.py example_largedef_porous-1/largedef_porous_mac.py # # The results are stored in `example_largedef_porous-1/results` directory. # import numpy as nm import six import os.path as osp from sfepy import data_dir from sfepy.base.base import Struct, output, debug from sfepy.terms.terms_hyperelastic_ul import HyperElasticULFamilyData from sfepy.homogenization.micmac import get_homog_coefs_nonlinear import sfepy.linalg as la from sfepy.solvers.ts import TimeStepper from sfepy.discrete.state import State wdir = osp.dirname(__file__) hyperelastic_data = { 'update_materials': True, 'state': {'u': None, 'du': None, 'p': None, 'dp': None}, 'mapping0': None, 'coors0': None, 'macro_data': None, } def post_process(out, pb, state, extend=False): ts = hyperelastic_data['ts'] if isinstance(state, dict): pass else: stress = pb.evaluate('ev_volume_integrate_mat.i.Omega(solid.S, u)', mode='el_avg') out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress) ret_stress = pb.evaluate('ev_volume_integrate_mat.i.Omega(solid.Q, u)', mode='el_avg') out['retardation_stress'] = Struct(name='output_data', mode='cell', data=ret_stress) strain = pb.evaluate('ev_volume_integrate_mat.i.Omega(solid.E, u)', mode='el_avg') out['green_strain'] = Struct(name='output_data', mode='cell', data=strain) he_state = hyperelastic_data['state'] for ch in pb.conf.chs: plab = 'p%d' % ch out['p0_%d' % ch] = Struct(name='output_data', mode='vertex', data=he_state[plab][:, nm.newaxis]) dvel = pb.evaluate('ev_diffusion_velocity.i.Omega(solid.C%d, %s)' % (ch, plab), mode='el_avg') out['w%d' % ch] = Struct(name='output_data', mode='cell', data=dvel) out['u0'] = Struct(name='output_data', mode='vertex', data=he_state['u']) return out def homog_macro_map(ccoors, macro, nel): nqpe = ccoors.shape[0] // nel macro_ = {k: nm.sum(v.reshape((nel, nqpe) + v.shape[1:]), axis=1) / nqpe for k, v in macro.items()} macro_['recovery_idxs'] = [] ccoors_ = nm.sum(ccoors.reshape((nel, nqpe) + ccoors.shape[1:]), axis=1) / nqpe return ccoors_, macro_ def homog_macro_remap(homcf, ncoor): nqpe = ncoor // homcf['Volume_total'].shape[0] homcf_ = {k: nm.repeat(v, nqpe, axis=0) for k, v in homcf.items() if not k == 'Volume_total'} return homcf_ def get_homog_mat(ts, coors, mode, term=None, problem=None, **kwargs): hyperela = hyperelastic_data ts = hyperela['ts'] output('get_homog_mat: mode=%s, update=%s'\ % (mode, hyperela['update_materials'])) if not mode == 'qp': return if not hyperela['update_materials']: out = hyperela['homog_mat'] return {k: nm.array(v) for k, v in six.iteritems(out)} dim = problem.domain.mesh.dim nqp = coors.shape[0] state_u = problem.equations.variables['u'] if len(state_u.field.mappings0) == 0: state_u.field.get_mapping(term.region, term.integral, term.integration) state_u.field.save_mappings() state_u.field.clear_mappings() state_u.set_data(hyperela['state']['u'].ravel()) # + state_u.data[-1][state_u.indx] mtx_f = problem.evaluate('ev_def_grad.i.Omega(u)', mode='qp').reshape(-1, dim, dim) # relative deformation gradient if hasattr(problem, 'mtx_f_prev'): rel_mtx_f = la.dot_sequences(mtx_f, nm.linalg.inv(problem.mtx_f_prev), 'AB') else: rel_mtx_f = mtx_f problem.mtx_f_prev = mtx_f.copy() macro_data = { 'mtx_e_rel': rel_mtx_f - nm.eye(dim), # relative macro strain } for ch in problem.conf.chs: plab = 'p%d' % ch state_p = problem.equations.variables[plab] state_p.set_data(hyperela['state'][plab]) macro_data['p%d_0' % ch] = \ problem.evaluate('ev_volume_integrate.i.Omega(p%d)' % ch, mode='qp').reshape(-1, 1, 1) macro_data['gp%d_0' % ch] = \ problem.evaluate('ev_grad.i.Omega(p%d)' % ch, mode='qp').reshape(-1, dim, 1) state_p.set_data(hyperela['state']['d' + plab]) macro_data['dp%d_0' % ch] = \ problem.evaluate('ev_volume_integrate.i.Omega(p%d)' % ch, mode='qp').reshape(-1, 1, 1) macro_data['gdp%d_0' % ch] = \ problem.evaluate('ev_grad.i.Omega(p%d)' % ch, mode='qp').reshape(-1, dim, 1) nel = term.region.entities[-1].shape[0] ccoors0, macro_data0 = homog_macro_map(coors, macro_data, nel) macro_data0['macro_ccoor'] = ccoors0 out0 = get_homog_coefs_nonlinear(ts, ccoors0, mode, macro_data0, term=term, problem=problem, iteration=ts.step, **kwargs) out0['C1'] += nm.eye(2) * 1e-12 # ! auxiliary permeability out0['C2'] += nm.eye(2) * 1e-12 # ! auxiliary permeability out = homog_macro_remap(out0, nqp) # Green strain out['E'] = 0.5 * (la.dot_sequences(mtx_f, mtx_f, 'ATB') - nm.eye(dim)) for ch in problem.conf.chs: out['B%d' % ch] = out['B%d' % ch].reshape((nqp, dim, dim)) out['Q'] = out['Q'].reshape((nqp, dim, dim)) hyperela['time'] = ts.step hyperela['homog_mat'] = \ {k: nm.array(v) for k, v in six.iteritems(out)} hyperela['update_materials'] = False hyperela['macro_data'] = macro_data return out def incremental_algorithm(pb): hyperela = hyperelastic_data chs = pb.conf.chs ts = pb.conf.ts hyperela['ts'] = ts hyperela['ofn_trunk'] = pb.ofn_trunk + '_%03d' pb.domain.mesh.coors_act = pb.domain.mesh.coors.copy() pbvars = pb.get_variables() he_state = hyperela['state'] out = [] out_data ={} coors0 = pbvars['u'].field.get_coor() he_state['coors0'] = coors0.copy() he_state['u'] = nm.zeros_like(coors0) he_state['du'] = nm.zeros_like(coors0) for ch in chs: plab = 'p%d' % ch press0 = pbvars[plab].field.get_coor()[:, 0].squeeze() he_state[plab] = nm.zeros_like(press0) he_state['d' + plab] = nm.zeros_like(press0) for step, time in ts: print('>>> step %d (%e):' % (step, time)) hyperela['update_materials'] = True pb.ofn_trunk = hyperela['ofn_trunk'] % step yield pb, out state = out[-1][1] result = state.get_parts() du = result['u'] he_state['u'] += du.reshape(he_state['du'].shape) he_state['du'][:] = du.reshape(he_state['du'].shape) pb.set_mesh_coors(he_state['u'] + he_state['coors0'], update_fields=True, actual=True, clear_all=False) for ch in chs: plab = 'p%d' % ch dp = result[plab] he_state[plab] += dp he_state['d' + plab][:] = dp out_data = post_process(out_data, pb, state, extend=False) filename = pb.get_output_name() pb.save_state(filename, out=out_data) yield None print('<<< step %d finished' % step) def move(ts, coor, problem=None, ramp=0.4, **kwargs): ts = problem.conf.ts nrs = round(ts.n_step * ramp) switch = 1 if (ts.step <= nrs) and (ts.step > 0) else 0 displ = nm.ones((coor.shape[0],)) * problem.conf.move_val / nrs * switch return displ def define(): chs = [1, 2] ts =
TimeStepper(0, 0.15, n_step=30)
sfepy.solvers.ts.TimeStepper
# This example implements homogenization of porous structures undergoing finite strains. # # largedef_porous_mac.py - problem at (global) macroscopic level # largedef_porous_mic.py - local subproblems, homogenized coefficients # # The mathematical model and numerical results are described in: # # <NAME>., <NAME>. # Homogenization of large deforming fluid-saturated porous structures # https://arxiv.org/abs/2012.03730 # # Run simulation: # # ./simple.py example_largedef_porous-1/largedef_porous_mac.py # # The results are stored in `example_largedef_porous-1/results` directory. # import numpy as nm import six import os.path as osp from sfepy import data_dir from sfepy.base.base import Struct, output, debug from sfepy.terms.terms_hyperelastic_ul import HyperElasticULFamilyData from sfepy.homogenization.micmac import get_homog_coefs_nonlinear import sfepy.linalg as la from sfepy.solvers.ts import TimeStepper from sfepy.discrete.state import State wdir = osp.dirname(__file__) hyperelastic_data = { 'update_materials': True, 'state': {'u': None, 'du': None, 'p': None, 'dp': None}, 'mapping0': None, 'coors0': None, 'macro_data': None, } def post_process(out, pb, state, extend=False): ts = hyperelastic_data['ts'] if isinstance(state, dict): pass else: stress = pb.evaluate('ev_volume_integrate_mat.i.Omega(solid.S, u)', mode='el_avg') out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress) ret_stress = pb.evaluate('ev_volume_integrate_mat.i.Omega(solid.Q, u)', mode='el_avg') out['retardation_stress'] = Struct(name='output_data', mode='cell', data=ret_stress) strain = pb.evaluate('ev_volume_integrate_mat.i.Omega(solid.E, u)', mode='el_avg') out['green_strain'] = Struct(name='output_data', mode='cell', data=strain) he_state = hyperelastic_data['state'] for ch in pb.conf.chs: plab = 'p%d' % ch out['p0_%d' % ch] = Struct(name='output_data', mode='vertex', data=he_state[plab][:, nm.newaxis]) dvel = pb.evaluate('ev_diffusion_velocity.i.Omega(solid.C%d, %s)' % (ch, plab), mode='el_avg') out['w%d' % ch] = Struct(name='output_data', mode='cell', data=dvel) out['u0'] = Struct(name='output_data', mode='vertex', data=he_state['u']) return out def homog_macro_map(ccoors, macro, nel): nqpe = ccoors.shape[0] // nel macro_ = {k: nm.sum(v.reshape((nel, nqpe) + v.shape[1:]), axis=1) / nqpe for k, v in macro.items()} macro_['recovery_idxs'] = [] ccoors_ = nm.sum(ccoors.reshape((nel, nqpe) + ccoors.shape[1:]), axis=1) / nqpe return ccoors_, macro_ def homog_macro_remap(homcf, ncoor): nqpe = ncoor // homcf['Volume_total'].shape[0] homcf_ = {k: nm.repeat(v, nqpe, axis=0) for k, v in homcf.items() if not k == 'Volume_total'} return homcf_ def get_homog_mat(ts, coors, mode, term=None, problem=None, **kwargs): hyperela = hyperelastic_data ts = hyperela['ts'] output('get_homog_mat: mode=%s, update=%s'\ % (mode, hyperela['update_materials'])) if not mode == 'qp': return if not hyperela['update_materials']: out = hyperela['homog_mat'] return {k: nm.array(v) for k, v in six.iteritems(out)} dim = problem.domain.mesh.dim nqp = coors.shape[0] state_u = problem.equations.variables['u'] if len(state_u.field.mappings0) == 0: state_u.field.get_mapping(term.region, term.integral, term.integration) state_u.field.save_mappings() state_u.field.clear_mappings() state_u.set_data(hyperela['state']['u'].ravel()) # + state_u.data[-1][state_u.indx] mtx_f = problem.evaluate('ev_def_grad.i.Omega(u)', mode='qp').reshape(-1, dim, dim) # relative deformation gradient if hasattr(problem, 'mtx_f_prev'): rel_mtx_f = la.dot_sequences(mtx_f, nm.linalg.inv(problem.mtx_f_prev), 'AB') else: rel_mtx_f = mtx_f problem.mtx_f_prev = mtx_f.copy() macro_data = { 'mtx_e_rel': rel_mtx_f - nm.eye(dim), # relative macro strain } for ch in problem.conf.chs: plab = 'p%d' % ch state_p = problem.equations.variables[plab] state_p.set_data(hyperela['state'][plab]) macro_data['p%d_0' % ch] = \ problem.evaluate('ev_volume_integrate.i.Omega(p%d)' % ch, mode='qp').reshape(-1, 1, 1) macro_data['gp%d_0' % ch] = \ problem.evaluate('ev_grad.i.Omega(p%d)' % ch, mode='qp').reshape(-1, dim, 1) state_p.set_data(hyperela['state']['d' + plab]) macro_data['dp%d_0' % ch] = \ problem.evaluate('ev_volume_integrate.i.Omega(p%d)' % ch, mode='qp').reshape(-1, 1, 1) macro_data['gdp%d_0' % ch] = \ problem.evaluate('ev_grad.i.Omega(p%d)' % ch, mode='qp').reshape(-1, dim, 1) nel = term.region.entities[-1].shape[0] ccoors0, macro_data0 = homog_macro_map(coors, macro_data, nel) macro_data0['macro_ccoor'] = ccoors0 out0 = get_homog_coefs_nonlinear(ts, ccoors0, mode, macro_data0, term=term, problem=problem, iteration=ts.step, **kwargs) out0['C1'] += nm.eye(2) * 1e-12 # ! auxiliary permeability out0['C2'] += nm.eye(2) * 1e-12 # ! auxiliary permeability out = homog_macro_remap(out0, nqp) # Green strain out['E'] = 0.5 * (
la.dot_sequences(mtx_f, mtx_f, 'ATB')
sfepy.linalg.dot_sequences
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 =
FEDomain('d1', m1)
sfepy.discrete.fem.FEDomain
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 =
FEDomain('d2', m2)
sfepy.discrete.fem.FEDomain
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(
transform_variables(variables)
sfepy.base.conf.transform_variables
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(
transform_variables(variables)
sfepy.base.conf.transform_variables
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 =
Mesh('source mesh', data_dir + '/meshes/3d/block.mesh')
sfepy.discrete.fem.Mesh
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 =
Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh')
sfepy.discrete.fem.Mesh
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 =
FEDomain('d1', m1)
sfepy.discrete.fem.FEDomain
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') field1 = Field.from_args('scalar_tp', nm.float64, (1,1), omega1, approx_order=1) ff1 = {field1.name : field1} d2 =
FEDomain('d2', m2)
sfepy.discrete.fem.FEDomain
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') field1 = Field.from_args('scalar_tp', nm.float64, (1,1), omega1, approx_order=1) ff1 = {field1.name : field1} d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('scalar_si', nm.float64, (1,1), omega2, approx_order=0) ff2 = {field2.name : field2} vv1 = Variables.from_conf(transform_variables(variables1), ff1) u1 = vv1['u'] u1.set_from_mesh_vertices(data) vv2 = Variables.from_conf(transform_variables(variables2), ff2) u2 = vv2['u'] # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.1) fname = in_dir(self.options.out_dir) u1.save_as_mesh(fname('test_mesh_interp_block_scalar.vtk')) u2.save_as_mesh(fname('test_mesh_interp_cube_scalar.vtk')) return True def test_invariance(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) ok = True for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] data = datas[field_name] u1, u2 = do_interpolation(m1, m1, data, field_name, force=True) self.report('max. difference:', nm.abs(u1() - u2()).max()) _ok = nm.allclose(u1(), u2(), rtol=0.0, atol=1e-12) self.report('invariance for %s field: %s' % (field_name, _ok)) ok = ok and _ok return ok def test_invariance_qp(self): from sfepy import data_dir from sfepy.discrete import Variables, Integral from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.common.mappings import get_physical_qps mesh =
Mesh('source mesh', data_dir + '/meshes/3d/block.mesh')
sfepy.discrete.fem.Mesh
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') field1 = Field.from_args('scalar_tp', nm.float64, (1,1), omega1, approx_order=1) ff1 = {field1.name : field1} d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('scalar_si', nm.float64, (1,1), omega2, approx_order=0) ff2 = {field2.name : field2} vv1 = Variables.from_conf(transform_variables(variables1), ff1) u1 = vv1['u'] u1.set_from_mesh_vertices(data) vv2 = Variables.from_conf(transform_variables(variables2), ff2) u2 = vv2['u'] # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.1) fname = in_dir(self.options.out_dir) u1.save_as_mesh(fname('test_mesh_interp_block_scalar.vtk')) u2.save_as_mesh(fname('test_mesh_interp_cube_scalar.vtk')) return True def test_invariance(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) ok = True for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] data = datas[field_name] u1, u2 = do_interpolation(m1, m1, data, field_name, force=True) self.report('max. difference:', nm.abs(u1() - u2()).max()) _ok = nm.allclose(u1(), u2(), rtol=0.0, atol=1e-12) self.report('invariance for %s field: %s' % (field_name, _ok)) ok = ok and _ok return ok def test_invariance_qp(self): from sfepy import data_dir from sfepy.discrete import Variables, Integral from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.common.mappings import get_physical_qps mesh = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') bbox = mesh.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * mesh.coors[:,1:2] / dd[1]) variables = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } domain =
FEDomain('domain', mesh)
sfepy.discrete.fem.FEDomain
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') field1 = Field.from_args('scalar_tp', nm.float64, (1,1), omega1, approx_order=1) ff1 = {field1.name : field1} d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('scalar_si', nm.float64, (1,1), omega2, approx_order=0) ff2 = {field2.name : field2} vv1 = Variables.from_conf(transform_variables(variables1), ff1) u1 = vv1['u'] u1.set_from_mesh_vertices(data) vv2 = Variables.from_conf(transform_variables(variables2), ff2) u2 = vv2['u'] # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.1) fname = in_dir(self.options.out_dir) u1.save_as_mesh(fname('test_mesh_interp_block_scalar.vtk')) u2.save_as_mesh(fname('test_mesh_interp_cube_scalar.vtk')) return True def test_invariance(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) ok = True for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] data = datas[field_name] u1, u2 = do_interpolation(m1, m1, data, field_name, force=True) self.report('max. difference:', nm.abs(u1() - u2()).max()) _ok = nm.allclose(u1(), u2(), rtol=0.0, atol=1e-12) self.report('invariance for %s field: %s' % (field_name, _ok)) ok = ok and _ok return ok def test_invariance_qp(self): from sfepy import data_dir from sfepy.discrete import Variables, Integral from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.common.mappings import get_physical_qps mesh = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') bbox = mesh.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * mesh.coors[:,1:2] / dd[1]) variables = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scalar_tp', nm.float64, 1, omega, approx_order=1) ff = {field.name : field} vv = Variables.from_conf(transform_variables(variables), ff) u = vv['u'] u.set_from_mesh_vertices(data) integral =
Integral('i', order=2)
sfepy.discrete.Integral
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') field1 = Field.from_args('scalar_tp', nm.float64, (1,1), omega1, approx_order=1) ff1 = {field1.name : field1} d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('scalar_si', nm.float64, (1,1), omega2, approx_order=0) ff2 = {field2.name : field2} vv1 = Variables.from_conf(transform_variables(variables1), ff1) u1 = vv1['u'] u1.set_from_mesh_vertices(data) vv2 = Variables.from_conf(transform_variables(variables2), ff2) u2 = vv2['u'] # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.1) fname = in_dir(self.options.out_dir) u1.save_as_mesh(fname('test_mesh_interp_block_scalar.vtk')) u2.save_as_mesh(fname('test_mesh_interp_cube_scalar.vtk')) return True def test_invariance(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) ok = True for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] data = datas[field_name] u1, u2 = do_interpolation(m1, m1, data, field_name, force=True) self.report('max. difference:', nm.abs(u1() - u2()).max()) _ok = nm.allclose(u1(), u2(), rtol=0.0, atol=1e-12) self.report('invariance for %s field: %s' % (field_name, _ok)) ok = ok and _ok return ok def test_invariance_qp(self): from sfepy import data_dir from sfepy.discrete import Variables, Integral from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.common.mappings import get_physical_qps mesh = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') bbox = mesh.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * mesh.coors[:,1:2] / dd[1]) variables = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scalar_tp', nm.float64, 1, omega, approx_order=1) ff = {field.name : field} vv = Variables.from_conf(transform_variables(variables), ff) u = vv['u'] u.set_from_mesh_vertices(data) integral = Integral('i', order=2) term =
Term.new('ev_volume_integrate(u)', integral, omega, u=u)
sfepy.terms.Term.new
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') field1 = Field.from_args('scalar_tp', nm.float64, (1,1), omega1, approx_order=1) ff1 = {field1.name : field1} d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('scalar_si', nm.float64, (1,1), omega2, approx_order=0) ff2 = {field2.name : field2} vv1 = Variables.from_conf(transform_variables(variables1), ff1) u1 = vv1['u'] u1.set_from_mesh_vertices(data) vv2 = Variables.from_conf(transform_variables(variables2), ff2) u2 = vv2['u'] # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.1) fname = in_dir(self.options.out_dir) u1.save_as_mesh(fname('test_mesh_interp_block_scalar.vtk')) u2.save_as_mesh(fname('test_mesh_interp_cube_scalar.vtk')) return True def test_invariance(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) ok = True for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] data = datas[field_name] u1, u2 = do_interpolation(m1, m1, data, field_name, force=True) self.report('max. difference:', nm.abs(u1() - u2()).max()) _ok = nm.allclose(u1(), u2(), rtol=0.0, atol=1e-12) self.report('invariance for %s field: %s' % (field_name, _ok)) ok = ok and _ok return ok def test_invariance_qp(self): from sfepy import data_dir from sfepy.discrete import Variables, Integral from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.common.mappings import get_physical_qps mesh = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') bbox = mesh.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * mesh.coors[:,1:2] / dd[1]) variables = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scalar_tp', nm.float64, 1, omega, approx_order=1) ff = {field.name : field} vv = Variables.from_conf(transform_variables(variables), ff) u = vv['u'] u.set_from_mesh_vertices(data) integral = Integral('i', order=2) term = Term.new('ev_volume_integrate(u)', integral, omega, u=u) term.setup() val1, _ = term.evaluate(mode='qp') val1 = val1.ravel() qps =
get_physical_qps(omega, integral)
sfepy.discrete.common.mappings.get_physical_qps
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' :
Mesh('original mesh', data_dir + '/meshes/3d/block.mesh')
sfepy.discrete.fem.Mesh
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' :
Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh')
sfepy.discrete.fem.Mesh
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') field1 = Field.from_args('scalar_tp', nm.float64, (1,1), omega1, approx_order=1) ff1 = {field1.name : field1} d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('scalar_si', nm.float64, (1,1), omega2, approx_order=0) ff2 = {field2.name : field2} vv1 = Variables.from_conf(
transform_variables(variables1)
sfepy.base.conf.transform_variables
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') field1 = Field.from_args('scalar_tp', nm.float64, (1,1), omega1, approx_order=1) ff1 = {field1.name : field1} d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('scalar_si', nm.float64, (1,1), omega2, approx_order=0) ff2 = {field2.name : field2} vv1 = Variables.from_conf(transform_variables(variables1), ff1) u1 = vv1['u'] u1.set_from_mesh_vertices(data) vv2 = Variables.from_conf(
transform_variables(variables2)
sfepy.base.conf.transform_variables
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') field1 = Field.from_args('scalar_tp', nm.float64, (1,1), omega1, approx_order=1) ff1 = {field1.name : field1} d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('scalar_si', nm.float64, (1,1), omega2, approx_order=0) ff2 = {field2.name : field2} vv1 = Variables.from_conf(transform_variables(variables1), ff1) u1 = vv1['u'] u1.set_from_mesh_vertices(data) vv2 = Variables.from_conf(transform_variables(variables2), ff2) u2 = vv2['u'] # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.1) fname = in_dir(self.options.out_dir) u1.save_as_mesh(fname('test_mesh_interp_block_scalar.vtk')) u2.save_as_mesh(fname('test_mesh_interp_cube_scalar.vtk')) return True def test_invariance(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh meshes = { 'tp' :
Mesh('original mesh', data_dir + '/meshes/3d/block.mesh')
sfepy.discrete.fem.Mesh
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') field1 = Field.from_args('scalar_tp', nm.float64, (1,1), omega1, approx_order=1) ff1 = {field1.name : field1} d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('scalar_si', nm.float64, (1,1), omega2, approx_order=0) ff2 = {field2.name : field2} vv1 = Variables.from_conf(transform_variables(variables1), ff1) u1 = vv1['u'] u1.set_from_mesh_vertices(data) vv2 = Variables.from_conf(transform_variables(variables2), ff2) u2 = vv2['u'] # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.1) fname = in_dir(self.options.out_dir) u1.save_as_mesh(fname('test_mesh_interp_block_scalar.vtk')) u2.save_as_mesh(fname('test_mesh_interp_cube_scalar.vtk')) return True def test_invariance(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' :
Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh')
sfepy.discrete.fem.Mesh
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx = make_axis_rotation_matrix([0, 1, 0], angle) m2 = m1.copy('rotated mesh') m2.transform_coors(mtx) data = datas[field_name] u1, u2 = do_interpolation(m2, m1, data, field_name) if ia == 0: u1.save_as_mesh(fname('test_mesh_interp_%s_u1.vtk' % field_name)) u2.save_as_mesh(fname('test_mesh_interp_%s_u2.%03d.vtk' % (field_name, ia))) return True def test_interpolation_two_meshes(self): from sfepy import data_dir from sfepy.discrete import Variables from sfepy.discrete.fem import Mesh, FEDomain, Field m1 = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') m2 = Mesh('target mesh', data_dir + '/meshes/3d/cube_medium_tetra.mesh') m2.coors *= 2.0 bbox = m1.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * m1.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * m1.coors[:,1:2] / dd[1]) variables1 = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } variables2 = { 'u' : ('unknown field', 'scalar_si', 0), 'v' : ('test field', 'scalar_si', 'u'), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') field1 = Field.from_args('scalar_tp', nm.float64, (1,1), omega1, approx_order=1) ff1 = {field1.name : field1} d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('scalar_si', nm.float64, (1,1), omega2, approx_order=0) ff2 = {field2.name : field2} vv1 = Variables.from_conf(transform_variables(variables1), ff1) u1 = vv1['u'] u1.set_from_mesh_vertices(data) vv2 = Variables.from_conf(transform_variables(variables2), ff2) u2 = vv2['u'] # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.1) fname = in_dir(self.options.out_dir) u1.save_as_mesh(fname('test_mesh_interp_block_scalar.vtk')) u2.save_as_mesh(fname('test_mesh_interp_cube_scalar.vtk')) return True def test_invariance(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) ok = True for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] data = datas[field_name] u1, u2 = do_interpolation(m1, m1, data, field_name, force=True) self.report('max. difference:', nm.abs(u1() - u2()).max()) _ok = nm.allclose(u1(), u2(), rtol=0.0, atol=1e-12) self.report('invariance for %s field: %s' % (field_name, _ok)) ok = ok and _ok return ok def test_invariance_qp(self): from sfepy import data_dir from sfepy.discrete import Variables, Integral from sfepy.discrete.fem import Mesh, FEDomain, Field from sfepy.terms import Term from sfepy.discrete.common.mappings import get_physical_qps mesh = Mesh('source mesh', data_dir + '/meshes/3d/block.mesh') bbox = mesh.get_bounding_box() dd = bbox[1,:] - bbox[0,:] data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / dd[0]) \ * nm.cos(4.0 * nm.pi * mesh.coors[:,1:2] / dd[1]) variables = { 'u' : ('unknown field', 'scalar_tp', 0), 'v' : ('test field', 'scalar_tp', 'u'), } domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') field = Field.from_args('scalar_tp', nm.float64, 1, omega, approx_order=1) ff = {field.name : field} vv = Variables.from_conf(
transform_variables(variables)
sfepy.base.conf.transform_variables
import os.path as op import numpy as nm from sfepy.base.conf import transform_variables from sfepy.base.testing import TestCommon variables = { 'u' : ('unknown field', 'f', 0), 'v' : ('test field', 'f', 'u'), } def in_dir(adir): return lambda x: op.join(adir, x) def gen_datas(meshes): datas = {} for key, mesh in meshes.iteritems(): bbox = mesh.get_bounding_box() nx = bbox[1,0] - bbox[0,0] centre = 0.5 * bbox.sum(axis=0) mesh.coors -= centre data = nm.sin(4.0 * nm.pi * mesh.coors[:,0:1] / nx) datas['scalar_' + key] = data data = nm.zeros_like(mesh.coors) data[:,0] = 0.05 * nx * nm.sin(4.0 * nm.pi * mesh.coors[:,0] / nx) data[:,2] = 0.05 * nx * nm.cos(4.0 * nm.pi * mesh.coors[:,0] / nx) datas['vector_' + key] = data return datas def do_interpolation(m2, m1, data, field_name, force=False): """Interpolate data from m1 to m2. """ from sfepy.discrete import Variables from sfepy.discrete.fem import FEDomain, Field fields = { 'scalar_si' : ((1,1), 'Omega', 2), 'vector_si' : ((3,1), 'Omega', 2), 'scalar_tp' : ((1,1), 'Omega', 1), 'vector_tp' : ((3,1), 'Omega', 1), } d1 = FEDomain('d1', m1) omega1 = d1.create_region('Omega', 'all') f = fields[field_name] field1 = Field.from_args('f', nm.float64, f[0], d1.regions[f[1]], approx_order=f[2]) ff = {field1.name : field1} vv = Variables.from_conf(transform_variables(variables), ff) u1 = vv['u'] u1.set_from_mesh_vertices(data) d2 = FEDomain('d2', m2) omega2 = d2.create_region('Omega', 'all') field2 = Field.from_args('f', nm.float64, f[0], d2.regions[f[1]], approx_order=f[2]) ff2 = {field2.name : field2} vv2 = Variables.from_conf(transform_variables(variables), ff2) u2 = vv2['u'] if not force: # Performs interpolation, if other field differs from self.field # or, in particular, is defined on a different mesh. u2.set_from_other(u1, strategy='interpolation', close_limit=0.5) else: coors = u2.field.get_coor() vals = u1.evaluate_at(coors, close_limit=0.5) u2.set_data(vals) return u1, u2 class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_interpolation(self): from sfepy import data_dir from sfepy.discrete.fem import Mesh from sfepy.linalg import make_axis_rotation_matrix fname = in_dir(self.options.out_dir) meshes = { 'tp' : Mesh('original mesh', data_dir + '/meshes/3d/block.mesh'), 'si' : Mesh('original mesh', data_dir + '/meshes/3d/cylinder.mesh'), } datas = gen_datas(meshes) for field_name in ['scalar_si', 'vector_si', 'scalar_tp', 'vector_tp']: m1 = meshes[field_name[-2:]] for ia, angle in enumerate(nm.linspace(0.0, nm.pi, 11)): self.report('%s: %d. angle: %f' % (field_name, ia, angle)) shift = [0.0, 0.0, 0.0] mtx =
make_axis_rotation_matrix([0, 1, 0], angle)
sfepy.linalg.make_axis_rotation_matrix
""" Functions to visualize the geometry elements and numbering and orientation of their facets (edges and faces). The standard geometry elements can be plotted by running:: $ python sfepy/postprocess/plot_facets.py """ import numpy as nm import matplotlib.pyplot as plt from sfepy.linalg import (get_perpendiculars, normalize_vectors, make_axis_rotation_matrix) from sfepy.postprocess.plot_dofs import _get_axes, plot_mesh, plot_global_dofs def plot_geometry(ax, gel, show=False): """ Plot a geometry element as a wireframe. """ ax =
plot_mesh(ax, gel.coors, [gel.conn], gel.edges, show=False)
sfepy.postprocess.plot_dofs.plot_mesh
""" Functions to visualize the geometry elements and numbering and orientation of their facets (edges and faces). The standard geometry elements can be plotted by running:: $ python sfepy/postprocess/plot_facets.py """ import numpy as nm import matplotlib.pyplot as plt from sfepy.linalg import (get_perpendiculars, normalize_vectors, make_axis_rotation_matrix) from sfepy.postprocess.plot_dofs import _get_axes, plot_mesh, plot_global_dofs def plot_geometry(ax, gel, show=False): """ Plot a geometry element as a wireframe. """ ax = plot_mesh(ax, gel.coors, [gel.conn], gel.edges, show=False) ax =
plot_global_dofs(ax, gel.coors, [gel.conn], show=show)
sfepy.postprocess.plot_dofs.plot_global_dofs
""" Functions to visualize the geometry elements and numbering and orientation of their facets (edges and faces). The standard geometry elements can be plotted by running:: $ python sfepy/postprocess/plot_facets.py """ import numpy as nm import matplotlib.pyplot as plt from sfepy.linalg import (get_perpendiculars, normalize_vectors, make_axis_rotation_matrix) from sfepy.postprocess.plot_dofs import _get_axes, plot_mesh, plot_global_dofs def plot_geometry(ax, gel, show=False): """ Plot a geometry element as a wireframe. """ ax = plot_mesh(ax, gel.coors, [gel.conn], gel.edges, show=False) ax = plot_global_dofs(ax, gel.coors, [gel.conn], show=show) return ax def plot_edges(ax, gel, length, show=False): """ Plot edges of a geometry element as numbered arrows. """ dim = gel.dim ax =
_get_axes(ax, dim)
sfepy.postprocess.plot_dofs._get_axes
""" Functions to visualize the geometry elements and numbering and orientation of their facets (edges and faces). The standard geometry elements can be plotted by running:: $ python sfepy/postprocess/plot_facets.py """ import numpy as nm import matplotlib.pyplot as plt from sfepy.linalg import (get_perpendiculars, normalize_vectors, make_axis_rotation_matrix) from sfepy.postprocess.plot_dofs import _get_axes, plot_mesh, plot_global_dofs def plot_geometry(ax, gel, show=False): """ Plot a geometry element as a wireframe. """ ax = plot_mesh(ax, gel.coors, [gel.conn], gel.edges, show=False) ax = plot_global_dofs(ax, gel.coors, [gel.conn], show=show) return ax def plot_edges(ax, gel, length, show=False): """ Plot edges of a geometry element as numbered arrows. """ dim = gel.dim ax = _get_axes(ax, dim) l2 = 0.5 * length for ii, edge in enumerate(gel.edges): cc = gel.coors[edge] centre = 0.5 * cc.sum(axis=0) vdir = (cc - centre) normalize_vectors(vdir) cc = l2 * vdir + centre draw_arrow(ax, cc, length=0.3*length, linewidth=3, color='b') if dim == 3: cx, cy, cz = centre ax.text(cx, cy, cz, ii, color='b', fontsize=10, weight='light') else: cx, cy = centre ax.text(cx, cy, ii, color='b', fontsize=10, weight='light') return ax def plot_faces(ax, gel, radius, n_point, show=False): """ Plot faces of a 3D geometry element as numbered oriented arcs. An arc centre corresponds to the first node of a face. It points from the first edge towards the last edge of the face. """ dim = gel.dim ax =
_get_axes(ax, dim)
sfepy.postprocess.plot_dofs._get_axes
""" Functions to visualize the geometry elements and numbering and orientation of their facets (edges and faces). The standard geometry elements can be plotted by running:: $ python sfepy/postprocess/plot_facets.py """ import numpy as nm import matplotlib.pyplot as plt from sfepy.linalg import (get_perpendiculars, normalize_vectors, make_axis_rotation_matrix) from sfepy.postprocess.plot_dofs import _get_axes, plot_mesh, plot_global_dofs def plot_geometry(ax, gel, show=False): """ Plot a geometry element as a wireframe. """ ax = plot_mesh(ax, gel.coors, [gel.conn], gel.edges, show=False) ax = plot_global_dofs(ax, gel.coors, [gel.conn], show=show) return ax def plot_edges(ax, gel, length, show=False): """ Plot edges of a geometry element as numbered arrows. """ dim = gel.dim ax = _get_axes(ax, dim) l2 = 0.5 * length for ii, edge in enumerate(gel.edges): cc = gel.coors[edge] centre = 0.5 * cc.sum(axis=0) vdir = (cc - centre) normalize_vectors(vdir) cc = l2 * vdir + centre draw_arrow(ax, cc, length=0.3*length, linewidth=3, color='b') if dim == 3: cx, cy, cz = centre ax.text(cx, cy, cz, ii, color='b', fontsize=10, weight='light') else: cx, cy = centre ax.text(cx, cy, ii, color='b', fontsize=10, weight='light') return ax def plot_faces(ax, gel, radius, n_point, show=False): """ Plot faces of a 3D geometry element as numbered oriented arcs. An arc centre corresponds to the first node of a face. It points from the first edge towards the last edge of the face. """ dim = gel.dim ax = _get_axes(ax, dim) if dim < 3: return ax for ii, face in enumerate(gel.faces): cc = gel.coors[face] t1 = cc[1, :] - cc[0, :] t2 = cc[-1, :] - cc[0, :] n = nm.cross(t1, t2) nt1 = nm.linalg.norm(t1) nt2 = nm.linalg.norm(t2) angle = nm.arccos(nm.dot(t1, t2) / (nt1 * nt2)) da = angle / (n_point - 1) mtx = make_axis_rotation_matrix(n, da) rt = cc[0] + radius * t1 / nt1 coors = [rt] for ip in range(n_point - 1): rt = nm.dot(mtx.T, (rt - cc[0])) + cc[0] coors.append(rt) coors = nm.array(coors, dtype=nm.float64) centre = coors.sum(axis=0) / coors.shape[0] draw_arrow(ax, coors, length=0.3*radius, linewidth=3, color='r') if dim == 3: cx, cy, cz = centre ax.text(cx, cy, cz, ii, color='r', fontsize=10, weight='light') else: cx, cy = centre ax.text(cx, cy, ii, color='r', fontsize=10, weight='light') return ax def draw_arrow(ax, coors, angle=20.0, length=0.3, **kwargs): """ Draw a line ended with an arrow head, in 2D or 3D. """ color = kwargs.get('color', 'b') c0 = coors[-2] c1 = coors[-1] vd = c1 - c0 nvd = nm.linalg.norm(vd) vd /= nvd c0 = c1 - length * vd ps =
get_perpendiculars(vd)
sfepy.linalg.get_perpendiculars
""" Functions to visualize the geometry elements and numbering and orientation of their facets (edges and faces). The standard geometry elements can be plotted by running:: $ python sfepy/postprocess/plot_facets.py """ import numpy as nm import matplotlib.pyplot as plt from sfepy.linalg import (get_perpendiculars, normalize_vectors, make_axis_rotation_matrix) from sfepy.postprocess.plot_dofs import _get_axes, plot_mesh, plot_global_dofs def plot_geometry(ax, gel, show=False): """ Plot a geometry element as a wireframe. """ ax = plot_mesh(ax, gel.coors, [gel.conn], gel.edges, show=False) ax = plot_global_dofs(ax, gel.coors, [gel.conn], show=show) return ax def plot_edges(ax, gel, length, show=False): """ Plot edges of a geometry element as numbered arrows. """ dim = gel.dim ax = _get_axes(ax, dim) l2 = 0.5 * length for ii, edge in enumerate(gel.edges): cc = gel.coors[edge] centre = 0.5 * cc.sum(axis=0) vdir = (cc - centre) normalize_vectors(vdir) cc = l2 * vdir + centre draw_arrow(ax, cc, length=0.3*length, linewidth=3, color='b') if dim == 3: cx, cy, cz = centre ax.text(cx, cy, cz, ii, color='b', fontsize=10, weight='light') else: cx, cy = centre ax.text(cx, cy, ii, color='b', fontsize=10, weight='light') return ax def plot_faces(ax, gel, radius, n_point, show=False): """ Plot faces of a 3D geometry element as numbered oriented arcs. An arc centre corresponds to the first node of a face. It points from the first edge towards the last edge of the face. """ dim = gel.dim ax = _get_axes(ax, dim) if dim < 3: return ax for ii, face in enumerate(gel.faces): cc = gel.coors[face] t1 = cc[1, :] - cc[0, :] t2 = cc[-1, :] - cc[0, :] n = nm.cross(t1, t2) nt1 = nm.linalg.norm(t1) nt2 = nm.linalg.norm(t2) angle = nm.arccos(nm.dot(t1, t2) / (nt1 * nt2)) da = angle / (n_point - 1) mtx = make_axis_rotation_matrix(n, da) rt = cc[0] + radius * t1 / nt1 coors = [rt] for ip in range(n_point - 1): rt = nm.dot(mtx.T, (rt - cc[0])) + cc[0] coors.append(rt) coors = nm.array(coors, dtype=nm.float64) centre = coors.sum(axis=0) / coors.shape[0] draw_arrow(ax, coors, length=0.3*radius, linewidth=3, color='r') if dim == 3: cx, cy, cz = centre ax.text(cx, cy, cz, ii, color='r', fontsize=10, weight='light') else: cx, cy = centre ax.text(cx, cy, ii, color='r', fontsize=10, weight='light') return ax def draw_arrow(ax, coors, angle=20.0, length=0.3, **kwargs): """ Draw a line ended with an arrow head, in 2D or 3D. """ color = kwargs.get('color', 'b') c0 = coors[-2] c1 = coors[-1] vd = c1 - c0 nvd = nm.linalg.norm(vd) vd /= nvd c0 = c1 - length * vd ps = get_perpendiculars(vd) rangle = nm.deg2rad(min(angle, 60.0)) plength = length * nm.arctan(rangle) if coors.shape[1] == 2: from matplotlib.patches import Polygon cx, cy = coors[:, 0], coors[:, 1] ax.plot(cx, cy, **kwargs) p0 = c0 + plength * ps p1 = c0 - plength * ps pol = Polygon([p0, p1, c1], color=color) ax.add_artist(pol) else: import mpl_toolkits.mplot3d as plt3 cx, cy, cz = coors[:, 0], coors[:, 1], coors[:, 2] ax.plot(cx, cy, cz, **kwargs) p00 = c0 + plength * ps[0] p01 = c0 - plength * ps[0] p10 = c0 + plength * ps[1] p11 = c0 - plength * ps[1] arr = plt3.art3d.Poly3DCollection([[p00, p01, c1], [p10, p11, c1]], color=color) ax.add_collection3d(arr) if __name__ == '__main__': from sfepy.discrete.fem.geometry_element import GeometryElement, geometry_data for key, gd in
geometry_data.iteritems()
sfepy.discrete.fem.geometry_element.geometry_data.iteritems
""" Functions to visualize the geometry elements and numbering and orientation of their facets (edges and faces). The standard geometry elements can be plotted by running:: $ python sfepy/postprocess/plot_facets.py """ import numpy as nm import matplotlib.pyplot as plt from sfepy.linalg import (get_perpendiculars, normalize_vectors, make_axis_rotation_matrix) from sfepy.postprocess.plot_dofs import _get_axes, plot_mesh, plot_global_dofs def plot_geometry(ax, gel, show=False): """ Plot a geometry element as a wireframe. """ ax = plot_mesh(ax, gel.coors, [gel.conn], gel.edges, show=False) ax = plot_global_dofs(ax, gel.coors, [gel.conn], show=show) return ax def plot_edges(ax, gel, length, show=False): """ Plot edges of a geometry element as numbered arrows. """ dim = gel.dim ax = _get_axes(ax, dim) l2 = 0.5 * length for ii, edge in enumerate(gel.edges): cc = gel.coors[edge] centre = 0.5 * cc.sum(axis=0) vdir = (cc - centre)
normalize_vectors(vdir)
sfepy.linalg.normalize_vectors