prompt
stringlengths
174
59.5k
completion
stringlengths
7
228
api
stringlengths
12
64
#!/usr/bin/env python # This code was adapted from http://sfepy.org/doc-devel/mat_optim.html. """ Compare various elastic materials w.r.t. uniaxial tension/compression test. Requires Matplotlib. """ from __future__ import absolute_import from argparse import ArgumentParser, RawDescriptionHelpFormatter import sys import six sys.path.append('.') from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.discrete import Problem from sfepy.base.plotutils import plt from matplotlib.collections import PolyCollection from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import numpy as np from functools import partial def define( K=8.333, mu_nh=3.846, mu_mr=1.923, kappa=1.923, lam=5.769, mu=3.846 ): """Define the problem to solve.""" from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import stiffness_from_lame def mesh_hook(mesh, mode): """ Generate the block mesh. """ if mode == 'read': mesh = gen_block_mesh([2, 2, 3], [2, 2, 4], [0, 0, 1.5], name='el3', verbose=False) return mesh elif mode == 'write': pass filename_mesh = UserMeshIO(mesh_hook) options = { 'nls' : 'newton', 'ls' : 'ls', 'ts' : 'ts', 'save_times' : 'all', } functions = { 'linear_pressure' : (linear_pressure,), 'empty' : (lambda ts, coor, mode, region, ig: None,), } fields = { 'displacement' : ('real', 3, 'Omega', 1), } # Coefficients are chosen so that the tangent stiffness is the same for all # material for zero strains. materials = { 'solid' : ({ 'K' : K, # bulk modulus 'mu_nh' : mu_nh, # shear modulus of neoHookean term 'mu_mr' : mu_mr, # shear modulus of Mooney-Rivlin term 'kappa' : kappa, # second modulus of Mooney-Rivlin term # elasticity for LE term 'D' : stiffness_from_lame(dim=3, lam=lam, mu=mu), },), 'load' : 'empty', } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Bottom' : ('vertices in (z < 0.1)', 'facet'), 'Top' : ('vertices in (z > 2.9)', 'facet'), } ebcs = { 'fixb' : ('Bottom', {'u.all' : 0.0}), 'fixt' : ('Top', {'u.[0,1]' : 0.0}), } integrals = { 'i' : 1, 'isurf' : 2, } equations = { 'linear' : """dw_lin_elastic.i.Omega(solid.D, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'neo-Hookean' : """dw_tl_he_neohook.i.Omega(solid.mu_nh, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'Mooney-Rivlin' : """dw_tl_he_neohook.i.Omega(solid.mu_mr, v, u) + dw_tl_he_mooney_rivlin.i.Omega(solid.kappa, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", } solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 5, 'eps_a' : 1e-10, 'eps_r' : 1.0, }), 'ts' : ('ts.simple', { 't0' : 0, 't1' : 1, 'dt' : None, 'n_step' : 26, # has precedence over dt! 'verbose' : 1, }), } return locals() ## # Pressure tractions. def linear_pressure(ts, coor, mode=None, coef=1, **kwargs): if mode == 'qp': val = np.tile(coef * ts.step, (coor.shape[0], 1, 1)) return {'val' : val} def store_top_u(displacements): """Function _store() will be called at the end of each loading step. Top displacements will be stored into `displacements`.""" def _store(problem, ts, state): top = problem.domain.regions['Top'] top_u = problem.get_variables()['u'].get_state_in_region(top) displacements.append(np.mean(top_u[:,-1])) return _store def solve_branch(problem, branch_function, material_type): eq = problem.conf.equations[material_type] problem.set_equations({material_type : eq}) load = problem.get_materials()['load'] load.set_function(branch_function) out = [] problem.solve(save_results=False, step_hook=store_top_u(out)) displacements = np.array(out, dtype=np.float64) return displacements helps = { 'no_plot' : 'do not show plot window', } def plot_mesh(pb): # plot mesh for macro problem coors = pb.domain.mesh.coors graph = pb.domain.mesh.get_conn(pb.domain.mesh.descs[0]) fig2 = plt.figure(figsize=(5,6)) ax = fig2.add_subplot(111, projection='3d') for e in range(graph.shape[0]): tupleList = coors[graph[e,:],:] vertices = [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]] verts = [[tupleList[vertices[ix][iy]] for iy in range(len(vertices[0]))] for ix in range(len(vertices))] pc3d = Poly3DCollection(verts=verts, facecolors='white', edgecolors='black', linewidths=1, alpha=0.5) ax.add_collection3d(pc3d) ax.set_xlim3d(-1.2, 1.2) ax.set_ylim3d(-1.2, 1.2) ax.set_zlim3d(-0.01, 3.2) ax.set_title('3D plot of macro system')
plt.show(fig2)
sfepy.base.plotutils.plt.show
#!/usr/bin/env python # This code was adapted from http://sfepy.org/doc-devel/mat_optim.html. """ Compare various elastic materials w.r.t. uniaxial tension/compression test. Requires Matplotlib. """ from __future__ import absolute_import from argparse import ArgumentParser, RawDescriptionHelpFormatter import sys import six sys.path.append('.') from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.discrete import Problem from sfepy.base.plotutils import plt from matplotlib.collections import PolyCollection from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import numpy as np from functools import partial def define( K=8.333, mu_nh=3.846, mu_mr=1.923, kappa=1.923, lam=5.769, mu=3.846 ): """Define the problem to solve.""" from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import stiffness_from_lame def mesh_hook(mesh, mode): """ Generate the block mesh. """ if mode == 'read': mesh = gen_block_mesh([2, 2, 3], [2, 2, 4], [0, 0, 1.5], name='el3', verbose=False) return mesh elif mode == 'write': pass filename_mesh = UserMeshIO(mesh_hook) options = { 'nls' : 'newton', 'ls' : 'ls', 'ts' : 'ts', 'save_times' : 'all', } functions = { 'linear_pressure' : (linear_pressure,), 'empty' : (lambda ts, coor, mode, region, ig: None,), } fields = { 'displacement' : ('real', 3, 'Omega', 1), } # Coefficients are chosen so that the tangent stiffness is the same for all # material for zero strains. materials = { 'solid' : ({ 'K' : K, # bulk modulus 'mu_nh' : mu_nh, # shear modulus of neoHookean term 'mu_mr' : mu_mr, # shear modulus of Mooney-Rivlin term 'kappa' : kappa, # second modulus of Mooney-Rivlin term # elasticity for LE term 'D' : stiffness_from_lame(dim=3, lam=lam, mu=mu), },), 'load' : 'empty', } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Bottom' : ('vertices in (z < 0.1)', 'facet'), 'Top' : ('vertices in (z > 2.9)', 'facet'), } ebcs = { 'fixb' : ('Bottom', {'u.all' : 0.0}), 'fixt' : ('Top', {'u.[0,1]' : 0.0}), } integrals = { 'i' : 1, 'isurf' : 2, } equations = { 'linear' : """dw_lin_elastic.i.Omega(solid.D, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'neo-Hookean' : """dw_tl_he_neohook.i.Omega(solid.mu_nh, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'Mooney-Rivlin' : """dw_tl_he_neohook.i.Omega(solid.mu_mr, v, u) + dw_tl_he_mooney_rivlin.i.Omega(solid.kappa, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", } solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 5, 'eps_a' : 1e-10, 'eps_r' : 1.0, }), 'ts' : ('ts.simple', { 't0' : 0, 't1' : 1, 'dt' : None, 'n_step' : 26, # has precedence over dt! 'verbose' : 1, }), } return locals() ## # Pressure tractions. def linear_pressure(ts, coor, mode=None, coef=1, **kwargs): if mode == 'qp': val = np.tile(coef * ts.step, (coor.shape[0], 1, 1)) return {'val' : val} def store_top_u(displacements): """Function _store() will be called at the end of each loading step. Top displacements will be stored into `displacements`.""" def _store(problem, ts, state): top = problem.domain.regions['Top'] top_u = problem.get_variables()['u'].get_state_in_region(top) displacements.append(np.mean(top_u[:,-1])) return _store def solve_branch(problem, branch_function, material_type): eq = problem.conf.equations[material_type] problem.set_equations({material_type : eq}) load = problem.get_materials()['load'] load.set_function(branch_function) out = [] problem.solve(save_results=False, step_hook=store_top_u(out)) displacements = np.array(out, dtype=np.float64) return displacements helps = { 'no_plot' : 'do not show plot window', } def plot_mesh(pb): # plot mesh for macro problem coors = pb.domain.mesh.coors graph = pb.domain.mesh.get_conn(pb.domain.mesh.descs[0]) fig2 = plt.figure(figsize=(5,6)) ax = fig2.add_subplot(111, projection='3d') for e in range(graph.shape[0]): tupleList = coors[graph[e,:],:] vertices = [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]] verts = [[tupleList[vertices[ix][iy]] for iy in range(len(vertices[0]))] for ix in range(len(vertices))] pc3d = Poly3DCollection(verts=verts, facecolors='white', edgecolors='black', linewidths=1, alpha=0.5) ax.add_collection3d(pc3d) ax.set_xlim3d(-1.2, 1.2) ax.set_ylim3d(-1.2, 1.2) ax.set_zlim3d(-0.01, 3.2) ax.set_title('3D plot of macro system') plt.show(fig2) return None def one_simulation(material_type, define_args, coef_tension=0.25, coef_compression=-0.25, plot_mesh_bool=False, return_load=False): #parser = ArgumentParser(description=__doc__, # formatter_class=RawDescriptionHelpFormatter) #parser.add_argument('--version', action='version', version='%(prog)s') #options = parser.parse_args()
output.set_output(filename='sfepy_log.txt', quiet=True)
sfepy.base.base.output.set_output
#!/usr/bin/env python # This code was adapted from http://sfepy.org/doc-devel/mat_optim.html. """ Compare various elastic materials w.r.t. uniaxial tension/compression test. Requires Matplotlib. """ from __future__ import absolute_import from argparse import ArgumentParser, RawDescriptionHelpFormatter import sys import six sys.path.append('.') from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.discrete import Problem from sfepy.base.plotutils import plt from matplotlib.collections import PolyCollection from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import numpy as np from functools import partial def define( K=8.333, mu_nh=3.846, mu_mr=1.923, kappa=1.923, lam=5.769, mu=3.846 ): """Define the problem to solve.""" from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import stiffness_from_lame def mesh_hook(mesh, mode): """ Generate the block mesh. """ if mode == 'read': mesh = gen_block_mesh([2, 2, 3], [2, 2, 4], [0, 0, 1.5], name='el3', verbose=False) return mesh elif mode == 'write': pass filename_mesh = UserMeshIO(mesh_hook) options = { 'nls' : 'newton', 'ls' : 'ls', 'ts' : 'ts', 'save_times' : 'all', } functions = { 'linear_pressure' : (linear_pressure,), 'empty' : (lambda ts, coor, mode, region, ig: None,), } fields = { 'displacement' : ('real', 3, 'Omega', 1), } # Coefficients are chosen so that the tangent stiffness is the same for all # material for zero strains. materials = { 'solid' : ({ 'K' : K, # bulk modulus 'mu_nh' : mu_nh, # shear modulus of neoHookean term 'mu_mr' : mu_mr, # shear modulus of Mooney-Rivlin term 'kappa' : kappa, # second modulus of Mooney-Rivlin term # elasticity for LE term 'D' : stiffness_from_lame(dim=3, lam=lam, mu=mu), },), 'load' : 'empty', } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Bottom' : ('vertices in (z < 0.1)', 'facet'), 'Top' : ('vertices in (z > 2.9)', 'facet'), } ebcs = { 'fixb' : ('Bottom', {'u.all' : 0.0}), 'fixt' : ('Top', {'u.[0,1]' : 0.0}), } integrals = { 'i' : 1, 'isurf' : 2, } equations = { 'linear' : """dw_lin_elastic.i.Omega(solid.D, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'neo-Hookean' : """dw_tl_he_neohook.i.Omega(solid.mu_nh, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'Mooney-Rivlin' : """dw_tl_he_neohook.i.Omega(solid.mu_mr, v, u) + dw_tl_he_mooney_rivlin.i.Omega(solid.kappa, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", } solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 5, 'eps_a' : 1e-10, 'eps_r' : 1.0, }), 'ts' : ('ts.simple', { 't0' : 0, 't1' : 1, 'dt' : None, 'n_step' : 26, # has precedence over dt! 'verbose' : 1, }), } return locals() ## # Pressure tractions. def linear_pressure(ts, coor, mode=None, coef=1, **kwargs): if mode == 'qp': val = np.tile(coef * ts.step, (coor.shape[0], 1, 1)) return {'val' : val} def store_top_u(displacements): """Function _store() will be called at the end of each loading step. Top displacements will be stored into `displacements`.""" def _store(problem, ts, state): top = problem.domain.regions['Top'] top_u = problem.get_variables()['u'].get_state_in_region(top) displacements.append(np.mean(top_u[:,-1])) return _store def solve_branch(problem, branch_function, material_type): eq = problem.conf.equations[material_type] problem.set_equations({material_type : eq}) load = problem.get_materials()['load'] load.set_function(branch_function) out = [] problem.solve(save_results=False, step_hook=store_top_u(out)) displacements = np.array(out, dtype=np.float64) return displacements helps = { 'no_plot' : 'do not show plot window', } def plot_mesh(pb): # plot mesh for macro problem coors = pb.domain.mesh.coors graph = pb.domain.mesh.get_conn(pb.domain.mesh.descs[0]) fig2 = plt.figure(figsize=(5,6)) ax = fig2.add_subplot(111, projection='3d') for e in range(graph.shape[0]): tupleList = coors[graph[e,:],:] vertices = [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]] verts = [[tupleList[vertices[ix][iy]] for iy in range(len(vertices[0]))] for ix in range(len(vertices))] pc3d = Poly3DCollection(verts=verts, facecolors='white', edgecolors='black', linewidths=1, alpha=0.5) ax.add_collection3d(pc3d) ax.set_xlim3d(-1.2, 1.2) ax.set_ylim3d(-1.2, 1.2) ax.set_zlim3d(-0.01, 3.2) ax.set_title('3D plot of macro system') plt.show(fig2) return None def one_simulation(material_type, define_args, coef_tension=0.25, coef_compression=-0.25, plot_mesh_bool=False, return_load=False): #parser = ArgumentParser(description=__doc__, # formatter_class=RawDescriptionHelpFormatter) #parser.add_argument('--version', action='version', version='%(prog)s') #options = parser.parse_args() output.set_output(filename='sfepy_log.txt', quiet=True) required, other =
get_standard_keywords()
sfepy.base.conf.get_standard_keywords
#!/usr/bin/env python # This code was adapted from http://sfepy.org/doc-devel/mat_optim.html. """ Compare various elastic materials w.r.t. uniaxial tension/compression test. Requires Matplotlib. """ from __future__ import absolute_import from argparse import ArgumentParser, RawDescriptionHelpFormatter import sys import six sys.path.append('.') from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.discrete import Problem from sfepy.base.plotutils import plt from matplotlib.collections import PolyCollection from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import numpy as np from functools import partial def define( K=8.333, mu_nh=3.846, mu_mr=1.923, kappa=1.923, lam=5.769, mu=3.846 ): """Define the problem to solve.""" from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import stiffness_from_lame def mesh_hook(mesh, mode): """ Generate the block mesh. """ if mode == 'read': mesh = gen_block_mesh([2, 2, 3], [2, 2, 4], [0, 0, 1.5], name='el3', verbose=False) return mesh elif mode == 'write': pass filename_mesh = UserMeshIO(mesh_hook) options = { 'nls' : 'newton', 'ls' : 'ls', 'ts' : 'ts', 'save_times' : 'all', } functions = { 'linear_pressure' : (linear_pressure,), 'empty' : (lambda ts, coor, mode, region, ig: None,), } fields = { 'displacement' : ('real', 3, 'Omega', 1), } # Coefficients are chosen so that the tangent stiffness is the same for all # material for zero strains. materials = { 'solid' : ({ 'K' : K, # bulk modulus 'mu_nh' : mu_nh, # shear modulus of neoHookean term 'mu_mr' : mu_mr, # shear modulus of Mooney-Rivlin term 'kappa' : kappa, # second modulus of Mooney-Rivlin term # elasticity for LE term 'D' : stiffness_from_lame(dim=3, lam=lam, mu=mu), },), 'load' : 'empty', } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Bottom' : ('vertices in (z < 0.1)', 'facet'), 'Top' : ('vertices in (z > 2.9)', 'facet'), } ebcs = { 'fixb' : ('Bottom', {'u.all' : 0.0}), 'fixt' : ('Top', {'u.[0,1]' : 0.0}), } integrals = { 'i' : 1, 'isurf' : 2, } equations = { 'linear' : """dw_lin_elastic.i.Omega(solid.D, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'neo-Hookean' : """dw_tl_he_neohook.i.Omega(solid.mu_nh, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", 'Mooney-Rivlin' : """dw_tl_he_neohook.i.Omega(solid.mu_mr, v, u) + dw_tl_he_mooney_rivlin.i.Omega(solid.kappa, v, u) + dw_tl_bulk_penalty.i.Omega(solid.K, v, u) = dw_surface_ltr.isurf.Top(load.val, v)""", } solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 5, 'eps_a' : 1e-10, 'eps_r' : 1.0, }), 'ts' : ('ts.simple', { 't0' : 0, 't1' : 1, 'dt' : None, 'n_step' : 26, # has precedence over dt! 'verbose' : 1, }), } return locals() ## # Pressure tractions. def linear_pressure(ts, coor, mode=None, coef=1, **kwargs): if mode == 'qp': val = np.tile(coef * ts.step, (coor.shape[0], 1, 1)) return {'val' : val} def store_top_u(displacements): """Function _store() will be called at the end of each loading step. Top displacements will be stored into `displacements`.""" def _store(problem, ts, state): top = problem.domain.regions['Top'] top_u = problem.get_variables()['u'].get_state_in_region(top) displacements.append(np.mean(top_u[:,-1])) return _store def solve_branch(problem, branch_function, material_type): eq = problem.conf.equations[material_type] problem.set_equations({material_type : eq}) load = problem.get_materials()['load'] load.set_function(branch_function) out = [] problem.solve(save_results=False, step_hook=store_top_u(out)) displacements = np.array(out, dtype=np.float64) return displacements helps = { 'no_plot' : 'do not show plot window', } def plot_mesh(pb): # plot mesh for macro problem coors = pb.domain.mesh.coors graph = pb.domain.mesh.get_conn(pb.domain.mesh.descs[0]) fig2 = plt.figure(figsize=(5,6)) ax = fig2.add_subplot(111, projection='3d') for e in range(graph.shape[0]): tupleList = coors[graph[e,:],:] vertices = [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]] verts = [[tupleList[vertices[ix][iy]] for iy in range(len(vertices[0]))] for ix in range(len(vertices))] pc3d = Poly3DCollection(verts=verts, facecolors='white', edgecolors='black', linewidths=1, alpha=0.5) ax.add_collection3d(pc3d) ax.set_xlim3d(-1.2, 1.2) ax.set_ylim3d(-1.2, 1.2) ax.set_zlim3d(-0.01, 3.2) ax.set_title('3D plot of macro system') plt.show(fig2) return None def one_simulation(material_type, define_args, coef_tension=0.25, coef_compression=-0.25, plot_mesh_bool=False, return_load=False): #parser = ArgumentParser(description=__doc__, # formatter_class=RawDescriptionHelpFormatter) #parser.add_argument('--version', action='version', version='%(prog)s') #options = parser.parse_args() output.set_output(filename='sfepy_log.txt', quiet=True) required, other = get_standard_keywords() # Use this file as the input file. conf = ProblemConf.from_file(__file__, required, other, define_args=define_args) # Create problem instance, but do not set equations. problem =
Problem.from_conf(conf, init_equations=False)
sfepy.discrete.Problem.from_conf
#!/usr/bin/env python # This code was adapted from http://sfepy.org/doc-devel/mat_optim.html. """ Compare various elastic materials w.r.t. uniaxial tension/compression test. Requires Matplotlib. """ from __future__ import absolute_import from argparse import ArgumentParser, RawDescriptionHelpFormatter import sys import six sys.path.append('.') from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.discrete import Problem from sfepy.base.plotutils import plt from matplotlib.collections import PolyCollection from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import numpy as np from functools import partial def define( K=8.333, mu_nh=3.846, mu_mr=1.923, kappa=1.923, lam=5.769, mu=3.846 ): """Define the problem to solve.""" from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import stiffness_from_lame def mesh_hook(mesh, mode): """ Generate the block mesh. """ if mode == 'read': mesh = gen_block_mesh([2, 2, 3], [2, 2, 4], [0, 0, 1.5], name='el3', verbose=False) return mesh elif mode == 'write': pass filename_mesh = UserMeshIO(mesh_hook) options = { 'nls' : 'newton', 'ls' : 'ls', 'ts' : 'ts', 'save_times' : 'all', } functions = { 'linear_pressure' : (linear_pressure,), 'empty' : (lambda ts, coor, mode, region, ig: None,), } fields = { 'displacement' : ('real', 3, 'Omega', 1), } # Coefficients are chosen so that the tangent stiffness is the same for all # material for zero strains. materials = { 'solid' : ({ 'K' : K, # bulk modulus 'mu_nh' : mu_nh, # shear modulus of neoHookean term 'mu_mr' : mu_mr, # shear modulus of Mooney-Rivlin term 'kappa' : kappa, # second modulus of Mooney-Rivlin term # elasticity for LE term 'D' :
stiffness_from_lame(dim=3, lam=lam, mu=mu)
sfepy.mechanics.matcoefs.stiffness_from_lame
import numpy as nm from sfepy.base.base import output, get_default, assert_, Struct def get_print_info(n_step): if n_step > 1: n_digit = int(nm.log10(n_step - 1) + 1) else: n_digit = 1 format = '%%%dd of %%%dd' % (n_digit, n_digit) suffix = '%%0%dd' % n_digit return n_digit, format, suffix class TimeStepper(Struct): """ Time stepper class. """ @staticmethod def from_conf(conf): return TimeStepper(conf.t0, conf.t1, dt=conf.dt, n_step=conf.n_step, is_quasistatic=conf.quasistatic) def __init__(self, t0, t1, dt=None, n_step=None, step=None, is_quasistatic=False): self.set_from_data(t0, t1, dt=dt, n_step=n_step, step=step) self.is_quasistatic = is_quasistatic self.step_start_time = None def _get_n_step(self, t0, t1, dt): n_step = int(round(nm.floor(((t1 - t0) / dt) + 0.5) + 1.0)) return n_step def set_from_data(self, t0, t1, dt=None, n_step=None, step=None): self.t0, self.t1 = t0, t1 dt =
get_default(dt, t1 - t0)
sfepy.base.base.get_default
import numpy as nm from sfepy.base.base import output, get_default, assert_, Struct def get_print_info(n_step): if n_step > 1: n_digit = int(nm.log10(n_step - 1) + 1) else: n_digit = 1 format = '%%%dd of %%%dd' % (n_digit, n_digit) suffix = '%%0%dd' % n_digit return n_digit, format, suffix class TimeStepper(Struct): """ Time stepper class. """ @staticmethod def from_conf(conf): return TimeStepper(conf.t0, conf.t1, dt=conf.dt, n_step=conf.n_step, is_quasistatic=conf.quasistatic) def __init__(self, t0, t1, dt=None, n_step=None, step=None, is_quasistatic=False): self.set_from_data(t0, t1, dt=dt, n_step=n_step, step=step) self.is_quasistatic = is_quasistatic self.step_start_time = None def _get_n_step(self, t0, t1, dt): n_step = int(round(nm.floor(((t1 - t0) / dt) + 0.5) + 1.0)) return n_step def set_from_data(self, t0, t1, dt=None, n_step=None, step=None): self.t0, self.t1 = t0, t1 dt = get_default(dt, t1 - t0) self.n_step = get_default(n_step, self._get_n_step(self.t0, self.t1, dt)) if self.n_step > 1: self.times, self.dt = nm.linspace(self.t0, self.t1, self.n_step, endpoint=True, retstep=True) else: self.times = nm.array((self.t0,), dtype=nm.float64) self.dt = self.t1 - self.t0 self.n_digit, self.format, self.suffix = get_print_info(self.n_step) self.set_step(step) def set_from_ts(self, ts, step=None): step =
get_default(step, ts.step)
sfepy.base.base.get_default
import numpy as nm from sfepy.base.base import output, get_default, assert_, Struct def get_print_info(n_step): if n_step > 1: n_digit = int(nm.log10(n_step - 1) + 1) else: n_digit = 1 format = '%%%dd of %%%dd' % (n_digit, n_digit) suffix = '%%0%dd' % n_digit return n_digit, format, suffix class TimeStepper(Struct): """ Time stepper class. """ @staticmethod def from_conf(conf): return TimeStepper(conf.t0, conf.t1, dt=conf.dt, n_step=conf.n_step, is_quasistatic=conf.quasistatic) def __init__(self, t0, t1, dt=None, n_step=None, step=None, is_quasistatic=False): self.set_from_data(t0, t1, dt=dt, n_step=n_step, step=step) self.is_quasistatic = is_quasistatic self.step_start_time = None def _get_n_step(self, t0, t1, dt): n_step = int(round(nm.floor(((t1 - t0) / dt) + 0.5) + 1.0)) return n_step def set_from_data(self, t0, t1, dt=None, n_step=None, step=None): self.t0, self.t1 = t0, t1 dt = get_default(dt, t1 - t0) self.n_step = get_default(n_step, self._get_n_step(self.t0, self.t1, dt)) if self.n_step > 1: self.times, self.dt = nm.linspace(self.t0, self.t1, self.n_step, endpoint=True, retstep=True) else: self.times = nm.array((self.t0,), dtype=nm.float64) self.dt = self.t1 - self.t0 self.n_digit, self.format, self.suffix = get_print_info(self.n_step) self.set_step(step) def set_from_ts(self, ts, step=None): step = get_default(step, ts.step) self.set_from_data(ts.t0, ts.t1, ts.dt, ts.n_step, step=step) def get_state(self): return {'step' : self.step} def set_state(self, step=0, **kwargs): self.set_step(step=step) def set_substep_time(self, sub_dt): self.step_start_time = self.time self.time += sub_dt def restore_step_time(self): if self.step_start_time is not None: self.time = self.step_start_time self.step_start_time = None def advance(self): if self.step < (self.n_step - 1): self.step += 1 self.time = self.times[self.step] self.normalize_time() def __iter__(self): """ts.step, ts.time is consistent with step, time returned here ts.nt is normalized time in [0, 1]""" return self.iter_from(0) def iter_from(self, step): self.set_step(step=step) for time in self.times[step:]: yield self.step, self.time self.advance() def normalize_time(self): self.nt = (self.time - self.t0) / (self.t1 - self.t0) def set_step(self, step=0, nt=0.0): nm1 = self.n_step - 1 if step is None: step = int(round(nt * nm1)) if step < 0: step = self.n_step + step if (step >= self.n_step) or (step < 0): output('time step must be in [%d, %d]' % (-nm1, nm1) ) raise ValueError self.step = step self.time = self.times[step] self.normalize_time() def __eq__(self, other): if type(other) == type(self): return (abs(self.t0 == other.t0) < 1e-15) and \ (abs(self.t1 == other.t1) < 1e-15) and \ (self.n_step == other.n_step) else: raise ValueError class VariableTimeStepper(TimeStepper): """ Time stepper class with a variable time step. """ @staticmethod def from_conf(conf): return VariableTimeStepper(conf.t0, conf.t1, dt=conf.dt, n_step=conf.n_step, is_quasistatic=conf.quasistatic) def set_from_data(self, t0, t1, dt=None, n_step=None, step=None): self.t0, self.t1 = t0, t1 self.dtime = self.t1 - self.t0 dt =
get_default(dt, self.dtime)
sfepy.base.base.get_default
r""" Elastic contact sphere simulating an indentation test. Find :math:`\ul{u}` such that: .. math:: \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) + \int_{\Gamma} \ul{v} \cdot f(d(\ul{u})) \ul{n}(\ul{u}) = 0 \;, where .. math:: D_{ijkl} = \mu (\delta_{ik} \delta_{jl} + \delta_{il} \delta_{jk}) + \lambda \ \delta_{ij} \delta_{kl} \;. Notes ----- Even though the material is linear elastic and small deformations are used, the problem is highly nonlinear due to contacts with the sphere. See also elastic_contact_planes.py example. """ from sfepy import data_dir filename_mesh = data_dir + '/meshes/3d/cube_medium_hexa.mesh' k = 1e5 # Elastic sphere stiffness for positive penetration. f0 = 1e-2 # Force at zero penetration. options = { 'nls' : 'newton', 'ls' : 'ls', 'output_format': 'vtk', } fields = { 'displacement': ('real', 3, 'Omega', 1), } materials = { 'solid' : ({ 'lam' : 5.769, 'mu' : 3.846, },), 'cs' : ({ 'f' : [k, f0], '.c' : [0.0, 0.0, 1.2], '.r' : 0.8, },), } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Bottom' : ('vertices in (z < -0.499)', 'facet'), 'Top' : ('vertices in (z > 0.499)', 'facet'), } ebcs = { 'fixed' : ('Bottom', {'u.all' : 0.0}), } equations = { 'elasticity' : """dw_lin_elastic_iso.2.Omega(solid.lam, solid.mu, v, u) + dw_contact_sphere.2.Top(cs.f, cs.c, cs.r, v, u) = 0""", } solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 20, 'eps_a' : 1e-1, 'ls_on' : 2.0, 'problem' : 'nonlinear', 'check' : 0, 'delta' : 1e-6, }), } def main(): import os import numpy as nm import matplotlib.pyplot as plt from sfepy.discrete.fem import MeshIO import sfepy.linalg as la from sfepy.mechanics.contact_bodies import ContactSphere, plot_points conf_dir = os.path.dirname(__file__) io =
MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir)
sfepy.discrete.fem.MeshIO.any_from_filename
r""" Elastic contact sphere simulating an indentation test. Find :math:`\ul{u}` such that: .. math:: \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) + \int_{\Gamma} \ul{v} \cdot f(d(\ul{u})) \ul{n}(\ul{u}) = 0 \;, where .. math:: D_{ijkl} = \mu (\delta_{ik} \delta_{jl} + \delta_{il} \delta_{jk}) + \lambda \ \delta_{ij} \delta_{kl} \;. Notes ----- Even though the material is linear elastic and small deformations are used, the problem is highly nonlinear due to contacts with the sphere. See also elastic_contact_planes.py example. """ from sfepy import data_dir filename_mesh = data_dir + '/meshes/3d/cube_medium_hexa.mesh' k = 1e5 # Elastic sphere stiffness for positive penetration. f0 = 1e-2 # Force at zero penetration. options = { 'nls' : 'newton', 'ls' : 'ls', 'output_format': 'vtk', } fields = { 'displacement': ('real', 3, 'Omega', 1), } materials = { 'solid' : ({ 'lam' : 5.769, 'mu' : 3.846, },), 'cs' : ({ 'f' : [k, f0], '.c' : [0.0, 0.0, 1.2], '.r' : 0.8, },), } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Bottom' : ('vertices in (z < -0.499)', 'facet'), 'Top' : ('vertices in (z > 0.499)', 'facet'), } ebcs = { 'fixed' : ('Bottom', {'u.all' : 0.0}), } equations = { 'elasticity' : """dw_lin_elastic_iso.2.Omega(solid.lam, solid.mu, v, u) + dw_contact_sphere.2.Top(cs.f, cs.c, cs.r, v, u) = 0""", } solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 20, 'eps_a' : 1e-1, 'ls_on' : 2.0, 'problem' : 'nonlinear', 'check' : 0, 'delta' : 1e-6, }), } def main(): import os import numpy as nm import matplotlib.pyplot as plt from sfepy.discrete.fem import MeshIO import sfepy.linalg as la from sfepy.mechanics.contact_bodies import ContactSphere, plot_points conf_dir = os.path.dirname(__file__) io = MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir) bb = io.read_bounding_box() outline = [vv for vv in la.combine(zip(*bb))] ax = plot_points(None, nm.array(outline), 'r*') csc = materials['cs'][0] cs =
ContactSphere(csc['.c'], csc['.r'])
sfepy.mechanics.contact_bodies.ContactSphere
r""" Elastic contact sphere simulating an indentation test. Find :math:`\ul{u}` such that: .. math:: \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) + \int_{\Gamma} \ul{v} \cdot f(d(\ul{u})) \ul{n}(\ul{u}) = 0 \;, where .. math:: D_{ijkl} = \mu (\delta_{ik} \delta_{jl} + \delta_{il} \delta_{jk}) + \lambda \ \delta_{ij} \delta_{kl} \;. Notes ----- Even though the material is linear elastic and small deformations are used, the problem is highly nonlinear due to contacts with the sphere. See also elastic_contact_planes.py example. """ from sfepy import data_dir filename_mesh = data_dir + '/meshes/3d/cube_medium_hexa.mesh' k = 1e5 # Elastic sphere stiffness for positive penetration. f0 = 1e-2 # Force at zero penetration. options = { 'nls' : 'newton', 'ls' : 'ls', 'output_format': 'vtk', } fields = { 'displacement': ('real', 3, 'Omega', 1), } materials = { 'solid' : ({ 'lam' : 5.769, 'mu' : 3.846, },), 'cs' : ({ 'f' : [k, f0], '.c' : [0.0, 0.0, 1.2], '.r' : 0.8, },), } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Bottom' : ('vertices in (z < -0.499)', 'facet'), 'Top' : ('vertices in (z > 0.499)', 'facet'), } ebcs = { 'fixed' : ('Bottom', {'u.all' : 0.0}), } equations = { 'elasticity' : """dw_lin_elastic_iso.2.Omega(solid.lam, solid.mu, v, u) + dw_contact_sphere.2.Top(cs.f, cs.c, cs.r, v, u) = 0""", } solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 20, 'eps_a' : 1e-1, 'ls_on' : 2.0, 'problem' : 'nonlinear', 'check' : 0, 'delta' : 1e-6, }), } def main(): import os import numpy as nm import matplotlib.pyplot as plt from sfepy.discrete.fem import MeshIO import sfepy.linalg as la from sfepy.mechanics.contact_bodies import ContactSphere, plot_points conf_dir = os.path.dirname(__file__) io = MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir) bb = io.read_bounding_box() outline = [vv for vv in la.combine(zip(*bb))] ax = plot_points(None, nm.array(outline), 'r*') csc = materials['cs'][0] cs = ContactSphere(csc['.c'], csc['.r']) pps = (bb[1] - bb[0]) * nm.random.rand(5000, 3) + bb[0] mask = cs.mask_points(pps, 0.0) ax =
plot_points(ax, cs.centre[None, :], 'b*', ms=30)
sfepy.mechanics.contact_bodies.plot_points
r""" Elastic contact sphere simulating an indentation test. Find :math:`\ul{u}` such that: .. math:: \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) + \int_{\Gamma} \ul{v} \cdot f(d(\ul{u})) \ul{n}(\ul{u}) = 0 \;, where .. math:: D_{ijkl} = \mu (\delta_{ik} \delta_{jl} + \delta_{il} \delta_{jk}) + \lambda \ \delta_{ij} \delta_{kl} \;. Notes ----- Even though the material is linear elastic and small deformations are used, the problem is highly nonlinear due to contacts with the sphere. See also elastic_contact_planes.py example. """ from sfepy import data_dir filename_mesh = data_dir + '/meshes/3d/cube_medium_hexa.mesh' k = 1e5 # Elastic sphere stiffness for positive penetration. f0 = 1e-2 # Force at zero penetration. options = { 'nls' : 'newton', 'ls' : 'ls', 'output_format': 'vtk', } fields = { 'displacement': ('real', 3, 'Omega', 1), } materials = { 'solid' : ({ 'lam' : 5.769, 'mu' : 3.846, },), 'cs' : ({ 'f' : [k, f0], '.c' : [0.0, 0.0, 1.2], '.r' : 0.8, },), } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Bottom' : ('vertices in (z < -0.499)', 'facet'), 'Top' : ('vertices in (z > 0.499)', 'facet'), } ebcs = { 'fixed' : ('Bottom', {'u.all' : 0.0}), } equations = { 'elasticity' : """dw_lin_elastic_iso.2.Omega(solid.lam, solid.mu, v, u) + dw_contact_sphere.2.Top(cs.f, cs.c, cs.r, v, u) = 0""", } solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 20, 'eps_a' : 1e-1, 'ls_on' : 2.0, 'problem' : 'nonlinear', 'check' : 0, 'delta' : 1e-6, }), } def main(): import os import numpy as nm import matplotlib.pyplot as plt from sfepy.discrete.fem import MeshIO import sfepy.linalg as la from sfepy.mechanics.contact_bodies import ContactSphere, plot_points conf_dir = os.path.dirname(__file__) io = MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir) bb = io.read_bounding_box() outline = [vv for vv in la.combine(zip(*bb))] ax = plot_points(None, nm.array(outline), 'r*') csc = materials['cs'][0] cs = ContactSphere(csc['.c'], csc['.r']) pps = (bb[1] - bb[0]) * nm.random.rand(5000, 3) + bb[0] mask = cs.mask_points(pps, 0.0) ax = plot_points(ax, cs.centre[None, :], 'b*', ms=30) ax =
plot_points(ax, pps[mask], 'kv')
sfepy.mechanics.contact_bodies.plot_points
r""" Elastic contact sphere simulating an indentation test. Find :math:`\ul{u}` such that: .. math:: \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) + \int_{\Gamma} \ul{v} \cdot f(d(\ul{u})) \ul{n}(\ul{u}) = 0 \;, where .. math:: D_{ijkl} = \mu (\delta_{ik} \delta_{jl} + \delta_{il} \delta_{jk}) + \lambda \ \delta_{ij} \delta_{kl} \;. Notes ----- Even though the material is linear elastic and small deformations are used, the problem is highly nonlinear due to contacts with the sphere. See also elastic_contact_planes.py example. """ from sfepy import data_dir filename_mesh = data_dir + '/meshes/3d/cube_medium_hexa.mesh' k = 1e5 # Elastic sphere stiffness for positive penetration. f0 = 1e-2 # Force at zero penetration. options = { 'nls' : 'newton', 'ls' : 'ls', 'output_format': 'vtk', } fields = { 'displacement': ('real', 3, 'Omega', 1), } materials = { 'solid' : ({ 'lam' : 5.769, 'mu' : 3.846, },), 'cs' : ({ 'f' : [k, f0], '.c' : [0.0, 0.0, 1.2], '.r' : 0.8, },), } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), } regions = { 'Omega' : 'all', 'Bottom' : ('vertices in (z < -0.499)', 'facet'), 'Top' : ('vertices in (z > 0.499)', 'facet'), } ebcs = { 'fixed' : ('Bottom', {'u.all' : 0.0}), } equations = { 'elasticity' : """dw_lin_elastic_iso.2.Omega(solid.lam, solid.mu, v, u) + dw_contact_sphere.2.Top(cs.f, cs.c, cs.r, v, u) = 0""", } solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 20, 'eps_a' : 1e-1, 'ls_on' : 2.0, 'problem' : 'nonlinear', 'check' : 0, 'delta' : 1e-6, }), } def main(): import os import numpy as nm import matplotlib.pyplot as plt from sfepy.discrete.fem import MeshIO import sfepy.linalg as la from sfepy.mechanics.contact_bodies import ContactSphere, plot_points conf_dir = os.path.dirname(__file__) io = MeshIO.any_from_filename(filename_mesh, prefix_dir=conf_dir) bb = io.read_bounding_box() outline = [vv for vv in la.combine(zip(*bb))] ax = plot_points(None, nm.array(outline), 'r*') csc = materials['cs'][0] cs = ContactSphere(csc['.c'], csc['.r']) pps = (bb[1] - bb[0]) * nm.random.rand(5000, 3) + bb[0] mask = cs.mask_points(pps, 0.0) ax = plot_points(ax, cs.centre[None, :], 'b*', ms=30) ax = plot_points(ax, pps[mask], 'kv') ax =
plot_points(ax, pps[~mask], 'r.')
sfepy.mechanics.contact_bodies.plot_points
""" Global interpolation functions. """ import time import numpy as nm from sfepy.base.base import output, get_default_attr from sfepy.discrete.fem.mesh import make_inverse_connectivity from sfepy.discrete.fem.extmods.bases import find_ref_coors def get_ref_coors(field, coors, strategy='kdtree', close_limit=0.1, cache=None, verbose=True): """ Get reference element coordinates and elements corresponding to given physical coordinates. Parameters ---------- field : Field instance The field defining the approximation. coors : array The physical coordinates. strategy : str, optional The strategy for finding the elements that contain the coordinates. Only 'kdtree' is supported for the moment. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh, the inverse connectivity of the field mesh and the KDTree instance can be cached as `cache.mesh`, `cache.offsets`, `cache.iconn` and `cache.kdtree`. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the KDTree related data are ignored. verbose : bool If False, reduce verbosity. Returns ------- ref_coors : array The reference coordinates. cells : array The cell indices corresponding to the reference coordinates. status : array The status: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure. """ ref_coors =
get_default_attr(cache, 'ref_coors', None)
sfepy.base.base.get_default_attr
""" Global interpolation functions. """ import time import numpy as nm from sfepy.base.base import output, get_default_attr from sfepy.discrete.fem.mesh import make_inverse_connectivity from sfepy.discrete.fem.extmods.bases import find_ref_coors def get_ref_coors(field, coors, strategy='kdtree', close_limit=0.1, cache=None, verbose=True): """ Get reference element coordinates and elements corresponding to given physical coordinates. Parameters ---------- field : Field instance The field defining the approximation. coors : array The physical coordinates. strategy : str, optional The strategy for finding the elements that contain the coordinates. Only 'kdtree' is supported for the moment. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh, the inverse connectivity of the field mesh and the KDTree instance can be cached as `cache.mesh`, `cache.offsets`, `cache.iconn` and `cache.kdtree`. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the KDTree related data are ignored. verbose : bool If False, reduce verbosity. Returns ------- ref_coors : array The reference coordinates. cells : array The cell indices corresponding to the reference coordinates. status : array The status: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure. """ ref_coors = get_default_attr(cache, 'ref_coors', None) if ref_coors is None: mesh =
get_default_attr(cache, 'mesh', None)
sfepy.base.base.get_default_attr
""" Global interpolation functions. """ import time import numpy as nm from sfepy.base.base import output, get_default_attr from sfepy.discrete.fem.mesh import make_inverse_connectivity from sfepy.discrete.fem.extmods.bases import find_ref_coors def get_ref_coors(field, coors, strategy='kdtree', close_limit=0.1, cache=None, verbose=True): """ Get reference element coordinates and elements corresponding to given physical coordinates. Parameters ---------- field : Field instance The field defining the approximation. coors : array The physical coordinates. strategy : str, optional The strategy for finding the elements that contain the coordinates. Only 'kdtree' is supported for the moment. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh, the inverse connectivity of the field mesh and the KDTree instance can be cached as `cache.mesh`, `cache.offsets`, `cache.iconn` and `cache.kdtree`. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the KDTree related data are ignored. verbose : bool If False, reduce verbosity. Returns ------- ref_coors : array The reference coordinates. cells : array The cell indices corresponding to the reference coordinates. status : array The status: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure. """ ref_coors = get_default_attr(cache, 'ref_coors', None) if ref_coors is None: mesh = get_default_attr(cache, 'mesh', None) if mesh is None: mesh = field.create_mesh(extra_nodes=False) scoors = mesh.coors output('reference field: %d vertices' % scoors.shape[0], verbose=verbose) iconn =
get_default_attr(cache, 'iconn', None)
sfepy.base.base.get_default_attr
""" Global interpolation functions. """ import time import numpy as nm from sfepy.base.base import output, get_default_attr from sfepy.discrete.fem.mesh import make_inverse_connectivity from sfepy.discrete.fem.extmods.bases import find_ref_coors def get_ref_coors(field, coors, strategy='kdtree', close_limit=0.1, cache=None, verbose=True): """ Get reference element coordinates and elements corresponding to given physical coordinates. Parameters ---------- field : Field instance The field defining the approximation. coors : array The physical coordinates. strategy : str, optional The strategy for finding the elements that contain the coordinates. Only 'kdtree' is supported for the moment. close_limit : float, optional The maximum limit distance of a point from the closest element allowed for extrapolation. cache : Struct, optional To speed up a sequence of evaluations, the field mesh, the inverse connectivity of the field mesh and the KDTree instance can be cached as `cache.mesh`, `cache.offsets`, `cache.iconn` and `cache.kdtree`. Optionally, the cache can also contain the reference element coordinates as `cache.ref_coors`, `cache.cells` and `cache.status`, if the evaluation occurs in the same coordinates repeatedly. In that case the KDTree related data are ignored. verbose : bool If False, reduce verbosity. Returns ------- ref_coors : array The reference coordinates. cells : array The cell indices corresponding to the reference coordinates. status : array The status: 0 is success, 1 is extrapolation within `close_limit`, 2 is extrapolation outside `close_limit`, 3 is failure. """ ref_coors = get_default_attr(cache, 'ref_coors', None) if ref_coors is None: mesh = get_default_attr(cache, 'mesh', None) if mesh is None: mesh = field.create_mesh(extra_nodes=False) scoors = mesh.coors output('reference field: %d vertices' % scoors.shape[0], verbose=verbose) iconn = get_default_attr(cache, 'iconn', None) if iconn is None: offsets, iconn = make_inverse_connectivity(mesh.conns, mesh.n_nod, ret_offsets=True) ii = nm.where(offsets[1:] == offsets[:-1])[0] if len(ii): raise ValueError('some vertices not in any element! (%s)' % ii) else: offsets = cache.offsets if strategy == 'kdtree': kdtree =
get_default_attr(cache, 'kdtree', None)
sfepy.base.base.get_default_attr
r""" Thermo-elasticity with a given temperature distribution. Uses `dw_biot` term with an isotropic coefficient for thermo-elastic coupling. For given body temperature :math:`T` and background temperature :math:`T_0` find :math:`\ul{u}` such that: .. math:: \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) - \int_{\Omega} (T - T_0)\ \alpha_{ij} e_{ij}(\ul{v}) = 0 \;, \quad \forall \ul{v} \;, where .. math:: D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) + \lambda \ \delta_{ij} \delta_{kl} \;, \\ \alpha_{ij} = (3 \lambda + 2 \mu) \alpha \delta_{ij} and :math:`\alpha` is the thermal expansion coefficient. """ from __future__ import absolute_import import numpy as np from sfepy.base.base import Struct from sfepy.mechanics.matcoefs import stiffness_from_lame from sfepy.mechanics.tensors import get_von_mises_stress from sfepy import data_dir # Material parameters. lam = 10.0 mu = 5.0 thermal_expandability = 1.25e-5 T0 = 20.0 # Background temperature. filename_mesh = data_dir + '/meshes/3d/block.mesh' def get_temperature_load(ts, coors, region=None): """ Temperature load depends on the `x` coordinate. """ x = coors[:, 0] return (x - x.min())**2 - T0 def post_process(out, pb, state, extend=False): """ Compute derived quantities: strain, stresses. Store also the loading temperature. """ ev = pb.evaluate strain = ev('ev_cauchy_strain.2.Omega( u )', mode='el_avg') out['cauchy_strain'] = Struct(name='output_data', mode='cell', data=strain, dofs=None) e_stress = ev('ev_cauchy_stress.2.Omega( solid.D, u )', mode='el_avg') out['elastic_stress'] = Struct(name='output_data', mode='cell', data=e_stress, dofs=None) t_stress = ev('ev_biot_stress.2.Omega( solid.alpha, T )', mode='el_avg') out['thermal_stress'] = Struct(name='output_data', mode='cell', data=t_stress, dofs=None) out['total_stress'] = Struct(name='output_data', mode='cell', data=e_stress + t_stress, dofs=None) out['von_mises_stress'] = aux = out['total_stress'].copy() vms = get_von_mises_stress(aux.data.squeeze()) vms.shape = (vms.shape[0], 1, 1, 1) out['von_mises_stress'].data = vms val = pb.get_variables()['T']() val.shape = (val.shape[0], 1) out['T'] = Struct(name='output_data', mode='vertex', data=val + T0, dofs=None) return out options = { 'post_process_hook' : 'post_process', 'nls' : 'newton', 'ls' : 'ls', } functions = { 'get_temperature_load' : (get_temperature_load,), } regions = { 'Omega' : 'all', 'Left' : ('vertices in (x < -4.99)', 'facet'), } fields = { 'displacement': ('real', 3, 'Omega', 1), 'temperature': ('real', 1, 'Omega', 1), } variables = { 'u' : ('unknown field', 'displacement', 0), 'v' : ('test field', 'displacement', 'u'), 'T' : ('parameter field', 'temperature', {'setter' : 'get_temperature_load'}), } ebcs = { 'fix_u' : ('Left', {'u.all' : 0.0}), } eye_sym = np.array([[1], [1], [1], [0], [0], [0]], dtype=np.float64) materials = { 'solid' : ({ 'D' :
stiffness_from_lame(3, lam=lam, mu=mu)
sfepy.mechanics.matcoefs.stiffness_from_lame
import numpy as nm from sfepy.linalg import dot_sequences from sfepy.terms.terms import Term, terms class PiezoCouplingTerm(Term): r""" Piezoelectric coupling term. Can be evaluated. :Definition: .. math:: \int_{\Omega} g_{kij}\ e_{ij}(\ul{v}) \nabla_k p \mbox{ , } \int_{\Omega} g_{kij}\ e_{ij}(\ul{u}) \nabla_k q :Arguments 1: - material : :math:`g_{kij}` - virtual : :math:`\ul{v}` - state : :math:`p` :Arguments 2: - material : :math:`g_{kij}` - state : :math:`\ul{u}` - virtual : :math:`q` :Arguments 3: - material : :math:`g_{kij}` - parameter_v : :math:`\ul{u}` - parameter_s : :math:`p` """ name = 'dw_piezo_coupling' arg_types = (('material', 'virtual', 'state'), ('material', 'state', 'virtual'), ('material', 'parameter_v', 'parameter_s')) arg_shapes = {'material' : 'D, S', 'virtual/grad' : ('D', None), 'state/grad' : 1, 'virtual/div' : (1, None), 'state/div' : 'D', 'parameter_v' : 'D', 'parameter_s' : 1} modes = ('grad', 'div', 'eval') def get_fargs(self, mat, vvar, svar, mode=None, term_mode=None, diff_var=None, **kwargs): if self.mode == 'grad': qp_var, qp_name = svar, 'grad' else: qp_var, qp_name = vvar, 'cauchy_strain' vvg, _ = self.get_mapping(vvar) if mode == 'weak': aux = nm.array([0], ndmin=4, dtype=nm.float64) if diff_var is None: # grad or strain according to mode. val_qp = self.get(qp_var, qp_name) fmode = 0 else: val_qp = aux fmode = 1 if self.mode == 'grad': strain, grad = aux, val_qp else: strain, grad = val_qp, aux fmode += 2 return strain, grad, mat, vvg, fmode elif mode == 'eval': strain = self.get(vvar, 'cauchy_strain') grad = self.get(svar, 'grad') return strain, grad, mat, vvg else: raise ValueError('unsupported evaluation mode in %s! (%s)' % (self.name, mode)) def get_eval_shape(self, mat, vvar, svar, mode=None, term_mode=None, diff_var=None, **kwargs): n_el, n_qp, dim, n_en, n_c = self.get_data_shape(vvar) return (n_el, 1, 1, 1), vvar.dtype def set_arg_types( self ): self.function = { 'grad' : terms.dw_piezo_coupling, 'div' : terms.dw_piezo_coupling, 'eval' : terms.d_piezo_coupling, }[self.mode] class PiezoStressTerm(Term): r""" Evaluate piezoelectric stress tensor. It is given in the usual vector form exploiting symmetry: in 3D it has 6 components with the indices ordered as :math:`[11, 22, 33, 12, 13, 23]`, in 2D it has 3 components with the indices ordered as :math:`[11, 22, 12]`. Supports 'eval', 'el_avg' and 'qp' evaluation modes. :Definition: .. math:: \int_{\Omega} g_{kij} \nabla_k p :Arguments: - material : :math:`g_{kij}` - parameter : :math:`p` """ name = 'ev_piezo_stress' arg_types = ('material', 'parameter') arg_shapes = {'material' : 'D, S', 'parameter' : '1'} @staticmethod def function(out, val_qp, vg, fmode): if fmode == 2: out[:] = val_qp status = 0 else: status = vg.integrate(out, val_qp, fmode) return status def get_fargs(self, mat, parameter, mode=None, term_mode=None, diff_var=None, **kwargs): vg, _ = self.get_mapping(parameter) grad = self.get(parameter, 'grad') val_qp =
dot_sequences(mat, grad, mode='ATB')
sfepy.linalg.dot_sequences
#!/usr/bin/env python # This code was adapted from http://sfepy.org/doc-devel/mat_optim.html. from __future__ import print_function from __future__ import absolute_import import sys sys.path.append('.') import matplotlib as mlp import matplotlib.pyplot as plt from matplotlib.collections import PolyCollection from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import numpy as np from sfepy.base.base import Struct, output from sfepy.base.log import Log from sfepy import data_dir class MaterialSimulator(object): @staticmethod def create_app(filename, is_homog=False, **kwargs): from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.applications import PDESolverApp required, other =
get_standard_keywords()
sfepy.base.conf.get_standard_keywords
#!/usr/bin/env python # This code was adapted from http://sfepy.org/doc-devel/mat_optim.html. from __future__ import print_function from __future__ import absolute_import import sys sys.path.append('.') import matplotlib as mlp import matplotlib.pyplot as plt from matplotlib.collections import PolyCollection from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import numpy as np from sfepy.base.base import Struct, output from sfepy.base.log import Log from sfepy import data_dir class MaterialSimulator(object): @staticmethod def create_app(filename, is_homog=False, **kwargs): from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.applications import PDESolverApp required, other = get_standard_keywords() if is_homog: required.remove('equations') conf = ProblemConf.from_file(filename, required, other, define_args=kwargs) options = Struct(output_filename_trunk=None, save_ebc=False, save_ebc_nodes=False, save_regions=False, save_regions_as_groups=False, save_field_meshes=False, solve_not=False, )
output.set_output(filename='sfepy_log.txt', quiet=True)
sfepy.base.base.output.set_output
#!/usr/bin/env python # This code was adapted from http://sfepy.org/doc-devel/mat_optim.html. from __future__ import print_function from __future__ import absolute_import import sys sys.path.append('.') import matplotlib as mlp import matplotlib.pyplot as plt from matplotlib.collections import PolyCollection from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import numpy as np from sfepy.base.base import Struct, output from sfepy.base.log import Log from sfepy import data_dir class MaterialSimulator(object): @staticmethod def create_app(filename, is_homog=False, **kwargs): from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.applications import PDESolverApp required, other = get_standard_keywords() if is_homog: required.remove('equations') conf = ProblemConf.from_file(filename, required, other, define_args=kwargs) options = Struct(output_filename_trunk=None, save_ebc=False, save_ebc_nodes=False, save_regions=False, save_regions_as_groups=False, save_field_meshes=False, solve_not=False, ) output.set_output(filename='sfepy_log.txt', quiet=True) if is_homog: app =
HomogenizationApp(conf, options, 'material_opt_micro:')
sfepy.homogenization.homogen_app.HomogenizationApp
#!/usr/bin/env python # This code was adapted from http://sfepy.org/doc-devel/mat_optim.html. from __future__ import print_function from __future__ import absolute_import import sys sys.path.append('.') import matplotlib as mlp import matplotlib.pyplot as plt from matplotlib.collections import PolyCollection from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection import numpy as np from sfepy.base.base import Struct, output from sfepy.base.log import Log from sfepy import data_dir class MaterialSimulator(object): @staticmethod def create_app(filename, is_homog=False, **kwargs): from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.applications import PDESolverApp required, other = get_standard_keywords() if is_homog: required.remove('equations') conf = ProblemConf.from_file(filename, required, other, define_args=kwargs) options = Struct(output_filename_trunk=None, save_ebc=False, save_ebc_nodes=False, save_regions=False, save_regions_as_groups=False, save_field_meshes=False, solve_not=False, ) output.set_output(filename='sfepy_log.txt', quiet=True) if is_homog: app = HomogenizationApp(conf, options, 'material_opt_micro:') else: app =
PDESolverApp(conf, options, 'material_opt_macro:')
sfepy.applications.PDESolverApp
""" Linearization of higher order solutions for the purposes of visualization. """ from __future__ import absolute_import import numpy as nm from sfepy.linalg import dot_sequences from sfepy.discrete.fem.refine import refine_reference from six.moves import range def get_eval_dofs(dofs, dof_conn, ps, ori=None): """ Get default function for evaluating field DOFs given a list of elements and reference element coordinates. """ def _eval(iels, rx): edofs = dofs[dof_conn[iels]] if ori is not None: eori = ori[iels] else: eori = None bf = ps.eval_base(rx, ori=eori, force_axis=True)[...,0,:] rvals = dot_sequences(bf, edofs) return rvals return _eval def get_eval_coors(coors, conn, ps): """ Get default function for evaluating physical coordinates given a list of elements and reference element coordinates. """ def _eval(iels, rx): ecoors = coors[conn[iels]] aux = ecoors.transpose((0, 2, 1)) bf = ps.eval_base(rx).squeeze() phys_coors = nm.dot(aux, bf.T).transpose((0, 2, 1)) return phys_coors return _eval def create_output(eval_dofs, eval_coors, n_el, ps, min_level=0, max_level=2, eps=1e-4): """ Create mesh with linear elements that approximates DOFs returned by `eval_dofs()` corresponding to a higher order approximation with a relative precision given by `eps`. The DOFs are evaluated in physical coordinates returned by `eval_coors()`. """ def _get_msd(iels, rx, ree): rvals = eval_dofs(iels, rx) rng = rvals.max() - rvals.min() n_components = rvals.shape[-1] msd = 0.0 for ic in range(n_components): rval = rvals[..., ic] sd = rval[:, ree] # ~ max. second derivative. msd += nm.abs(sd[..., 0] + sd[..., 2] - 2.0 * sd[..., 1]).max(axis=-1) msd /= n_components return msd, rng rx0 = ps.geometry.coors rc0 = ps.geometry.conn[None, :] rx, rc, ree =
refine_reference(ps.geometry, 1)
sfepy.discrete.fem.refine.refine_reference
""" Linearization of higher order solutions for the purposes of visualization. """ from __future__ import absolute_import import numpy as nm from sfepy.linalg import dot_sequences from sfepy.discrete.fem.refine import refine_reference from six.moves import range def get_eval_dofs(dofs, dof_conn, ps, ori=None): """ Get default function for evaluating field DOFs given a list of elements and reference element coordinates. """ def _eval(iels, rx): edofs = dofs[dof_conn[iels]] if ori is not None: eori = ori[iels] else: eori = None bf = ps.eval_base(rx, ori=eori, force_axis=True)[...,0,:] rvals =
dot_sequences(bf, edofs)
sfepy.linalg.dot_sequences
""" Linearization of higher order solutions for the purposes of visualization. """ from __future__ import absolute_import import numpy as nm from sfepy.linalg import dot_sequences from sfepy.discrete.fem.refine import refine_reference from six.moves import range def get_eval_dofs(dofs, dof_conn, ps, ori=None): """ Get default function for evaluating field DOFs given a list of elements and reference element coordinates. """ def _eval(iels, rx): edofs = dofs[dof_conn[iels]] if ori is not None: eori = ori[iels] else: eori = None bf = ps.eval_base(rx, ori=eori, force_axis=True)[...,0,:] rvals = dot_sequences(bf, edofs) return rvals return _eval def get_eval_coors(coors, conn, ps): """ Get default function for evaluating physical coordinates given a list of elements and reference element coordinates. """ def _eval(iels, rx): ecoors = coors[conn[iels]] aux = ecoors.transpose((0, 2, 1)) bf = ps.eval_base(rx).squeeze() phys_coors = nm.dot(aux, bf.T).transpose((0, 2, 1)) return phys_coors return _eval def create_output(eval_dofs, eval_coors, n_el, ps, min_level=0, max_level=2, eps=1e-4): """ Create mesh with linear elements that approximates DOFs returned by `eval_dofs()` corresponding to a higher order approximation with a relative precision given by `eps`. The DOFs are evaluated in physical coordinates returned by `eval_coors()`. """ def _get_msd(iels, rx, ree): rvals = eval_dofs(iels, rx) rng = rvals.max() - rvals.min() n_components = rvals.shape[-1] msd = 0.0 for ic in range(n_components): rval = rvals[..., ic] sd = rval[:, ree] # ~ max. second derivative. msd += nm.abs(sd[..., 0] + sd[..., 2] - 2.0 * sd[..., 1]).max(axis=-1) msd /= n_components return msd, rng rx0 = ps.geometry.coors rc0 = ps.geometry.conn[None, :] rx, rc, ree = refine_reference(ps.geometry, 1) factor = rc.shape[0] / rc0.shape[0] iels = nm.arange(n_el) msd, rng = _get_msd(iels, rx, ree) eps_r = rng * eps flag = msd > eps_r iels0 = flag0 = None coors = [] conns = [] vdofs = [] inod = 0 for level in range(max_level + 1): if level < min_level: flag.fill(True) # Force refinement everywhere. elif level == max_level: # Last level - take everything. flag.fill(False) # Deal with finished elements. if flag0 is not None: ii = nm.searchsorted(iels0, iels) expand_flag0 = flag0[ii].repeat(factor, axis=1) else: expand_flag0 = nm.ones_like(flag) ie, ir = nm.where((flag == False) & (expand_flag0 == True)) if len(ie): uie, iies = nm.unique(ie, return_inverse=True) # Each (sub-)element has own coordinates - no shared vertices. xes = eval_coors(iels[uie], rx0) des = eval_dofs(iels[uie], rx0) # Vectorize (how??) or use cython? cc = [] vd = [] for ii, iie in enumerate(iies): ce = rc0[ir[ii]] xe = xes[iie] cc.append(xe[ce]) de = des[iie] vd.append(de[ce]) cc = nm.vstack(cc) vd = nm.vstack(vd) nc = cc.shape[0] np = rc0.shape[1] conn = nm.arange(nc, dtype=nm.int32).reshape((nc // np, np)) coors.append(cc) conns.append(conn + inod) vdofs.append(vd) inod += nc if not flag.any(): break iels0 = iels flag0 = flag # Deal with elements to refine. if level < max_level: eflag = flag.sum(axis=1, dtype=nm.bool) iels = iels[eflag] rc0 = rc rx0 = rx rx, rc, ree =
refine_reference(ps.geometry, level + 2)
sfepy.discrete.fem.refine.refine_reference
#!/usr/bin/env python # 12.01.2007, c """ Solve partial differential equations given in a SfePy problem definition file. Example problem definition files can be found in ``examples/`` directory of the SfePy top-level directory. This script works with all the examples except those in ``examples/standalone/``. Both normal and parametric study runs are supported. A parametric study allows repeated runs for varying some of the simulation parameters - see ``examples/diffusion/poisson_parametric_study.py`` file. """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser, RawDescriptionHelpFormatter import sfepy from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.applications import PDESolverApp def print_terms(): import sfepy.terms as t tt = t.term_table print('Terms: %d available:' % len(tt)) print(sorted(tt.keys())) def print_solvers(): from sfepy.solvers import solver_table print('Solvers: %d available:' % len(solver_table)) print(sorted(solver_table.keys())) helps = { 'debug': 'automatically start debugger when an exception is raised', 'conf' : 'override problem description file items, written as python' ' dictionary without surrounding braces', 'options' : 'override options item of problem description,' ' written as python dictionary without surrounding braces', 'define' : 'pass given arguments written as python dictionary' ' without surrounding braces to define() function of problem description' ' file', 'filename' : 'basename of output file(s) [default: <basename of input file>]', 'output_format' : 'output file format, one of: {vtk, h5} [default: vtk]', 'save_restart' : 'if given, save restart files according to the given mode.', 'load_restart' : 'if given, load the given restart file', 'log' : 'log all messages to specified file (existing file will be overwritten!)', 'quiet' : 'do not print any messages to screen', 'save_ebc' : 'save a zero solution with applied EBCs (Dirichlet boundary conditions)', 'save_ebc_nodes' : 'save a zero solution with added non-zeros in EBC (Dirichlet boundary' ' conditions) nodes - scalar variables are shown using colors,' ' vector variables using arrows with non-zero components corresponding' ' to constrained components', 'save_regions' : 'save problem regions as meshes', 'save_regions_as_groups' : 'save problem regions in a single mesh but mark them by using different' ' element/node group numbers', 'save_field_meshes' : 'save meshes of problem fields (with extra DOF nodes)', 'solve_not' : 'do not solve (use in connection with --save-*)', 'list' : 'list data, what can be one of: {terms, solvers}', } def main(): parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s ' + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=helps['debug']) parser.add_argument('-c', '--conf', metavar='"key : value, ..."', action='store', dest='conf', type=str, default=None, help= helps['conf']) parser.add_argument('-O', '--options', metavar='"key : value, ..."', action='store', dest='app_options', type=str, default=None, help=helps['options']) parser.add_argument('-d', '--define', metavar='"key : value, ..."', action='store', dest='define_args', type=str, default=None, help=helps['define']) parser.add_argument('-o', metavar='filename', action='store', dest='output_filename_trunk', default=None, help=helps['filename']) parser.add_argument('--format', metavar='format', action='store', dest='output_format', default=None, help=helps['output_format']) parser.add_argument('--save-restart', metavar='mode', type=int, action='store', dest='save_restart', default=None, help=helps['save_restart']) parser.add_argument('--load-restart', metavar='filename', action='store', dest='load_restart', default=None, help=helps['load_restart']) parser.add_argument('--log', metavar='file', action='store', dest='log', default=None, help=helps['log']) parser.add_argument('-q', '--quiet', action='store_true', dest='quiet', default=False, help=helps['quiet']) parser.add_argument('--save-ebc', action='store_true', dest='save_ebc', default=False, help=helps['save_ebc']) parser.add_argument('--save-ebc-nodes', action='store_true', dest='save_ebc_nodes', default=False, help=helps['save_ebc_nodes']) parser.add_argument('--save-regions', action='store_true', dest='save_regions', default=False, help=helps['save_regions']) parser.add_argument('--save-regions-as-groups', action='store_true', dest='save_regions_as_groups', default=False, help=helps['save_regions_as_groups']) parser.add_argument('--save-field-meshes', action='store_true', dest='save_field_meshes', default=False, help=helps['save_field_meshes']) parser.add_argument('--solve-not', action='store_true', dest='solve_not', default=False, help=helps['solve_not']) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--list', metavar='what', action='store', dest='_list', default=None, help=helps['list']) group.add_argument('filename_in', nargs='?') options, petsc_opts = parser.parse_known_args() if options._list is not None: if options._list == 'terms': print_terms() elif options._list == 'solvers': print_solvers() return if options.debug: from sfepy.base.base import debug_on_error; debug_on_error() filename_in = options.filename_in output.set_output(filename=options.log, quiet=options.quiet, combined=options.log is not None) required, other =
get_standard_keywords()
sfepy.base.conf.get_standard_keywords
#!/usr/bin/env python # 12.01.2007, c """ Solve partial differential equations given in a SfePy problem definition file. Example problem definition files can be found in ``examples/`` directory of the SfePy top-level directory. This script works with all the examples except those in ``examples/standalone/``. Both normal and parametric study runs are supported. A parametric study allows repeated runs for varying some of the simulation parameters - see ``examples/diffusion/poisson_parametric_study.py`` file. """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser, RawDescriptionHelpFormatter import sfepy from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.applications import PDESolverApp def print_terms(): import sfepy.terms as t tt = t.term_table print('Terms: %d available:' % len(tt)) print(sorted(tt.keys())) def print_solvers(): from sfepy.solvers import solver_table print('Solvers: %d available:' % len(solver_table)) print(sorted(solver_table.keys())) helps = { 'debug': 'automatically start debugger when an exception is raised', 'conf' : 'override problem description file items, written as python' ' dictionary without surrounding braces', 'options' : 'override options item of problem description,' ' written as python dictionary without surrounding braces', 'define' : 'pass given arguments written as python dictionary' ' without surrounding braces to define() function of problem description' ' file', 'filename' : 'basename of output file(s) [default: <basename of input file>]', 'output_format' : 'output file format, one of: {vtk, h5} [default: vtk]', 'save_restart' : 'if given, save restart files according to the given mode.', 'load_restart' : 'if given, load the given restart file', 'log' : 'log all messages to specified file (existing file will be overwritten!)', 'quiet' : 'do not print any messages to screen', 'save_ebc' : 'save a zero solution with applied EBCs (Dirichlet boundary conditions)', 'save_ebc_nodes' : 'save a zero solution with added non-zeros in EBC (Dirichlet boundary' ' conditions) nodes - scalar variables are shown using colors,' ' vector variables using arrows with non-zero components corresponding' ' to constrained components', 'save_regions' : 'save problem regions as meshes', 'save_regions_as_groups' : 'save problem regions in a single mesh but mark them by using different' ' element/node group numbers', 'save_field_meshes' : 'save meshes of problem fields (with extra DOF nodes)', 'solve_not' : 'do not solve (use in connection with --save-*)', 'list' : 'list data, what can be one of: {terms, solvers}', } def main(): parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s ' + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=helps['debug']) parser.add_argument('-c', '--conf', metavar='"key : value, ..."', action='store', dest='conf', type=str, default=None, help= helps['conf']) parser.add_argument('-O', '--options', metavar='"key : value, ..."', action='store', dest='app_options', type=str, default=None, help=helps['options']) parser.add_argument('-d', '--define', metavar='"key : value, ..."', action='store', dest='define_args', type=str, default=None, help=helps['define']) parser.add_argument('-o', metavar='filename', action='store', dest='output_filename_trunk', default=None, help=helps['filename']) parser.add_argument('--format', metavar='format', action='store', dest='output_format', default=None, help=helps['output_format']) parser.add_argument('--save-restart', metavar='mode', type=int, action='store', dest='save_restart', default=None, help=helps['save_restart']) parser.add_argument('--load-restart', metavar='filename', action='store', dest='load_restart', default=None, help=helps['load_restart']) parser.add_argument('--log', metavar='file', action='store', dest='log', default=None, help=helps['log']) parser.add_argument('-q', '--quiet', action='store_true', dest='quiet', default=False, help=helps['quiet']) parser.add_argument('--save-ebc', action='store_true', dest='save_ebc', default=False, help=helps['save_ebc']) parser.add_argument('--save-ebc-nodes', action='store_true', dest='save_ebc_nodes', default=False, help=helps['save_ebc_nodes']) parser.add_argument('--save-regions', action='store_true', dest='save_regions', default=False, help=helps['save_regions']) parser.add_argument('--save-regions-as-groups', action='store_true', dest='save_regions_as_groups', default=False, help=helps['save_regions_as_groups']) parser.add_argument('--save-field-meshes', action='store_true', dest='save_field_meshes', default=False, help=helps['save_field_meshes']) parser.add_argument('--solve-not', action='store_true', dest='solve_not', default=False, help=helps['solve_not']) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--list', metavar='what', action='store', dest='_list', default=None, help=helps['list']) group.add_argument('filename_in', nargs='?') options, petsc_opts = parser.parse_known_args() if options._list is not None: if options._list == 'terms': print_terms() elif options._list == 'solvers': print_solvers() return if options.debug: from sfepy.base.base import debug_on_error; debug_on_error() filename_in = options.filename_in output.set_output(filename=options.log, quiet=options.quiet, combined=options.log is not None) required, other = get_standard_keywords() if options.solve_not: required.remove('equations') required.remove('solver_[0-9]+|solvers') other.extend(['equations']) conf = ProblemConf.from_file_and_options(filename_in, options, required, other, define_args=options.define_args) opts = conf.options output_prefix = opts.get('output_prefix', 'sfepy:') opts.save_restart = options.save_restart opts.load_restart = options.load_restart app =
PDESolverApp(conf, options, output_prefix)
sfepy.applications.PDESolverApp
#!/usr/bin/env python # 12.01.2007, c """ Solve partial differential equations given in a SfePy problem definition file. Example problem definition files can be found in ``examples/`` directory of the SfePy top-level directory. This script works with all the examples except those in ``examples/standalone/``. Both normal and parametric study runs are supported. A parametric study allows repeated runs for varying some of the simulation parameters - see ``examples/diffusion/poisson_parametric_study.py`` file. """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser, RawDescriptionHelpFormatter import sfepy from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.applications import PDESolverApp def print_terms(): import sfepy.terms as t tt = t.term_table print('Terms: %d available:' % len(tt)) print(sorted(tt.keys())) def print_solvers(): from sfepy.solvers import solver_table print('Solvers: %d available:' % len(solver_table)) print(sorted(solver_table.keys())) helps = { 'debug': 'automatically start debugger when an exception is raised', 'conf' : 'override problem description file items, written as python' ' dictionary without surrounding braces', 'options' : 'override options item of problem description,' ' written as python dictionary without surrounding braces', 'define' : 'pass given arguments written as python dictionary' ' without surrounding braces to define() function of problem description' ' file', 'filename' : 'basename of output file(s) [default: <basename of input file>]', 'output_format' : 'output file format, one of: {vtk, h5} [default: vtk]', 'save_restart' : 'if given, save restart files according to the given mode.', 'load_restart' : 'if given, load the given restart file', 'log' : 'log all messages to specified file (existing file will be overwritten!)', 'quiet' : 'do not print any messages to screen', 'save_ebc' : 'save a zero solution with applied EBCs (Dirichlet boundary conditions)', 'save_ebc_nodes' : 'save a zero solution with added non-zeros in EBC (Dirichlet boundary' ' conditions) nodes - scalar variables are shown using colors,' ' vector variables using arrows with non-zero components corresponding' ' to constrained components', 'save_regions' : 'save problem regions as meshes', 'save_regions_as_groups' : 'save problem regions in a single mesh but mark them by using different' ' element/node group numbers', 'save_field_meshes' : 'save meshes of problem fields (with extra DOF nodes)', 'solve_not' : 'do not solve (use in connection with --save-*)', 'list' : 'list data, what can be one of: {terms, solvers}', } def main(): parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s ' + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=helps['debug']) parser.add_argument('-c', '--conf', metavar='"key : value, ..."', action='store', dest='conf', type=str, default=None, help= helps['conf']) parser.add_argument('-O', '--options', metavar='"key : value, ..."', action='store', dest='app_options', type=str, default=None, help=helps['options']) parser.add_argument('-d', '--define', metavar='"key : value, ..."', action='store', dest='define_args', type=str, default=None, help=helps['define']) parser.add_argument('-o', metavar='filename', action='store', dest='output_filename_trunk', default=None, help=helps['filename']) parser.add_argument('--format', metavar='format', action='store', dest='output_format', default=None, help=helps['output_format']) parser.add_argument('--save-restart', metavar='mode', type=int, action='store', dest='save_restart', default=None, help=helps['save_restart']) parser.add_argument('--load-restart', metavar='filename', action='store', dest='load_restart', default=None, help=helps['load_restart']) parser.add_argument('--log', metavar='file', action='store', dest='log', default=None, help=helps['log']) parser.add_argument('-q', '--quiet', action='store_true', dest='quiet', default=False, help=helps['quiet']) parser.add_argument('--save-ebc', action='store_true', dest='save_ebc', default=False, help=helps['save_ebc']) parser.add_argument('--save-ebc-nodes', action='store_true', dest='save_ebc_nodes', default=False, help=helps['save_ebc_nodes']) parser.add_argument('--save-regions', action='store_true', dest='save_regions', default=False, help=helps['save_regions']) parser.add_argument('--save-regions-as-groups', action='store_true', dest='save_regions_as_groups', default=False, help=helps['save_regions_as_groups']) parser.add_argument('--save-field-meshes', action='store_true', dest='save_field_meshes', default=False, help=helps['save_field_meshes']) parser.add_argument('--solve-not', action='store_true', dest='solve_not', default=False, help=helps['solve_not']) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--list', metavar='what', action='store', dest='_list', default=None, help=helps['list']) group.add_argument('filename_in', nargs='?') options, petsc_opts = parser.parse_known_args() if options._list is not None: if options._list == 'terms': print_terms() elif options._list == 'solvers': print_solvers() return if options.debug: from sfepy.base.base import debug_on_error;
debug_on_error()
sfepy.base.base.debug_on_error
#!/usr/bin/env python # 12.01.2007, c """ Solve partial differential equations given in a SfePy problem definition file. Example problem definition files can be found in ``examples/`` directory of the SfePy top-level directory. This script works with all the examples except those in ``examples/standalone/``. Both normal and parametric study runs are supported. A parametric study allows repeated runs for varying some of the simulation parameters - see ``examples/diffusion/poisson_parametric_study.py`` file. """ from __future__ import print_function from __future__ import absolute_import from argparse import ArgumentParser, RawDescriptionHelpFormatter import sfepy from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.applications import PDESolverApp def print_terms(): import sfepy.terms as t tt = t.term_table print('Terms: %d available:' % len(tt)) print(sorted(tt.keys())) def print_solvers(): from sfepy.solvers import solver_table print('Solvers: %d available:' % len(solver_table)) print(sorted(
solver_table.keys()
sfepy.solvers.solver_table.keys
r""" Incompressible Stokes flow with Navier (slip) boundary conditions, flow driven by a moving wall and a small diffusion for stabilization. This example demonstrates the use of `no-penetration` and `edge direction` boundary conditions together with Navier or slip boundary conditions. Alternatively the `no-penetration` boundary conditions can be applied in a weak sense using the penalty term ``dw_non_penetration_p``. Find :math:`\ul{u}`, :math:`p` such that: .. math:: \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u} - \int_{\Omega} p\ \nabla \cdot \ul{v} + \int_{\Gamma_1} \beta \ul{v} \cdot (\ul{u} - \ul{u}_d) + \int_{\Gamma_2} \beta \ul{v} \cdot \ul{u} = 0 \;, \quad \forall \ul{v} \;, \int_{\Omega} \mu \nabla q \cdot \nabla p + \int_{\Omega} q\ \nabla \cdot \ul{u} = 0 \;, \quad \forall q \;, where :math:`\nu` is the fluid viscosity, :math:`\beta` is the slip coefficient, :math:`\mu` is the (small) numerical diffusion coefficient, :math:`\Gamma_1` is the top wall that moves with the given driving velocity :math:`\ul{u}_d` and :math:`\Gamma_2` are the remaining walls. The Navier conditions are in effect on both :math:`\Gamma_1`, :math:`\Gamma_2` and are expressed by the corresponding integrals in the equations above. The `no-penetration` boundary conditions are applied on :math:`\Gamma_1`, :math:`\Gamma_2`, except the vertices of the block edges, where the `edge direction` boundary conditions are applied. The penalty term formulation is given by the following equations. Find :math:`\ul{u}`, :math:`p` such that: .. math:: \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u} - \int_{\Omega} p\ \nabla \cdot \ul{v} + \int_{\Gamma_1} \beta \ul{v} \cdot (\ul{u} - \ul{u}_d) + \int_{\Gamma_2} \beta \ul{v} \cdot \ul{u} + \int_{\Gamma_1 \cup \Gamma_2} \epsilon (\ul{n} \cdot \ul{v}) (\ul{n} \cdot \ul{u}) = 0 \;, \quad \forall \ul{v} \;, \int_{\Omega} \mu \nabla q \cdot \nabla p + \int_{\Omega} q\ \nabla \cdot \ul{u} = 0 \;, \quad \forall q \;, where :math:`\epsilon` is the penalty coefficient (sufficiently large). The `no-penetration` boundary conditions are applied on :math:`\Gamma_1`, :math:`\Gamma_2`. Optionally, Dirichlet boundary conditions can be applied on the inlet in the both cases, see below. For large meshes use the ``'ls_i'`` linear solver - PETSc + petsc4py are needed in that case. Several parameters can be set using the ``--define`` option of ``simple.py``, see :func:`define()` and the examples below. Examples -------- Specify the inlet velocity and a finer mesh:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d shape="(11,31,31),u_inlet=0.5" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Use the penalty term formulation and einsum-based terms with the default (numpy) backend:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "mode=penalty,term_mode=einsum" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Change backend to opt_einsum (needs to be installed) and use the quadratic velocity approximation order:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "u_order=2,mode=penalty,term_mode=einsum,backend=opt_einsum,optimize=auto" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Note the pressure field distribution improvement w.r.t. the previous examples. IfPETSc + petsc4py are installed, try using the iterative solver to speed up the solution:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "u_order=2,ls=ls_i,mode=penalty,term_mode=einsum,backend=opt_einsum,optimize=auto" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import assert_, output from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.homogenization.utils import define_box_regions def define(dims=(3, 1, 0.5), shape=(11, 15, 15), u_order=1, refine=0, ls='ls_d', u_inlet=None, mode='lcbc', term_mode='original', backend='numpy', optimize='optimal', verbosity=0): """ Parameters ---------- dims : tuple The block domain dimensions. shape : tuple The mesh resolution: increase to improve accuracy. u_order : int The velocity field approximation order. refine : int The refinement level. ls : 'ls_d' or 'ls_i' The pre-configured linear solver name. u_inlet : float, optional The x-component of the inlet velocity. mode : 'lcbc' or 'penalty' The alternative formulations. term_mode : 'original' or 'einsum' The switch to use either the original or new experimental einsum-based terms. backend : str The einsum mode backend. optimize : str The einsum mode optimization (backend dependent). verbosity : 0, 1, 2, 3 The verbosity level of einsum-based terms. """ output('dims: {}, shape: {}, u_order: {}, refine: {}, u_inlet: {}' .format(dims, shape, u_order, refine, u_inlet)) output('linear solver: {}'.format(ls)) output('mode: {}, term_mode: {}'.format(mode, term_mode)) if term_mode == 'einsum': output('backend: {}, optimize: {}, verbosity: {}' .format(backend, optimize, verbosity))
assert_(mode in {'lcbc', 'penalty'})
sfepy.base.base.assert_
r""" Incompressible Stokes flow with Navier (slip) boundary conditions, flow driven by a moving wall and a small diffusion for stabilization. This example demonstrates the use of `no-penetration` and `edge direction` boundary conditions together with Navier or slip boundary conditions. Alternatively the `no-penetration` boundary conditions can be applied in a weak sense using the penalty term ``dw_non_penetration_p``. Find :math:`\ul{u}`, :math:`p` such that: .. math:: \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u} - \int_{\Omega} p\ \nabla \cdot \ul{v} + \int_{\Gamma_1} \beta \ul{v} \cdot (\ul{u} - \ul{u}_d) + \int_{\Gamma_2} \beta \ul{v} \cdot \ul{u} = 0 \;, \quad \forall \ul{v} \;, \int_{\Omega} \mu \nabla q \cdot \nabla p + \int_{\Omega} q\ \nabla \cdot \ul{u} = 0 \;, \quad \forall q \;, where :math:`\nu` is the fluid viscosity, :math:`\beta` is the slip coefficient, :math:`\mu` is the (small) numerical diffusion coefficient, :math:`\Gamma_1` is the top wall that moves with the given driving velocity :math:`\ul{u}_d` and :math:`\Gamma_2` are the remaining walls. The Navier conditions are in effect on both :math:`\Gamma_1`, :math:`\Gamma_2` and are expressed by the corresponding integrals in the equations above. The `no-penetration` boundary conditions are applied on :math:`\Gamma_1`, :math:`\Gamma_2`, except the vertices of the block edges, where the `edge direction` boundary conditions are applied. The penalty term formulation is given by the following equations. Find :math:`\ul{u}`, :math:`p` such that: .. math:: \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u} - \int_{\Omega} p\ \nabla \cdot \ul{v} + \int_{\Gamma_1} \beta \ul{v} \cdot (\ul{u} - \ul{u}_d) + \int_{\Gamma_2} \beta \ul{v} \cdot \ul{u} + \int_{\Gamma_1 \cup \Gamma_2} \epsilon (\ul{n} \cdot \ul{v}) (\ul{n} \cdot \ul{u}) = 0 \;, \quad \forall \ul{v} \;, \int_{\Omega} \mu \nabla q \cdot \nabla p + \int_{\Omega} q\ \nabla \cdot \ul{u} = 0 \;, \quad \forall q \;, where :math:`\epsilon` is the penalty coefficient (sufficiently large). The `no-penetration` boundary conditions are applied on :math:`\Gamma_1`, :math:`\Gamma_2`. Optionally, Dirichlet boundary conditions can be applied on the inlet in the both cases, see below. For large meshes use the ``'ls_i'`` linear solver - PETSc + petsc4py are needed in that case. Several parameters can be set using the ``--define`` option of ``simple.py``, see :func:`define()` and the examples below. Examples -------- Specify the inlet velocity and a finer mesh:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d shape="(11,31,31),u_inlet=0.5" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Use the penalty term formulation and einsum-based terms with the default (numpy) backend:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "mode=penalty,term_mode=einsum" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Change backend to opt_einsum (needs to be installed) and use the quadratic velocity approximation order:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "u_order=2,mode=penalty,term_mode=einsum,backend=opt_einsum,optimize=auto" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Note the pressure field distribution improvement w.r.t. the previous examples. IfPETSc + petsc4py are installed, try using the iterative solver to speed up the solution:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "u_order=2,ls=ls_i,mode=penalty,term_mode=einsum,backend=opt_einsum,optimize=auto" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import assert_, output from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.homogenization.utils import define_box_regions def define(dims=(3, 1, 0.5), shape=(11, 15, 15), u_order=1, refine=0, ls='ls_d', u_inlet=None, mode='lcbc', term_mode='original', backend='numpy', optimize='optimal', verbosity=0): """ Parameters ---------- dims : tuple The block domain dimensions. shape : tuple The mesh resolution: increase to improve accuracy. u_order : int The velocity field approximation order. refine : int The refinement level. ls : 'ls_d' or 'ls_i' The pre-configured linear solver name. u_inlet : float, optional The x-component of the inlet velocity. mode : 'lcbc' or 'penalty' The alternative formulations. term_mode : 'original' or 'einsum' The switch to use either the original or new experimental einsum-based terms. backend : str The einsum mode backend. optimize : str The einsum mode optimization (backend dependent). verbosity : 0, 1, 2, 3 The verbosity level of einsum-based terms. """ output('dims: {}, shape: {}, u_order: {}, refine: {}, u_inlet: {}' .format(dims, shape, u_order, refine, u_inlet)) output('linear solver: {}'.format(ls)) output('mode: {}, term_mode: {}'.format(mode, term_mode)) if term_mode == 'einsum': output('backend: {}, optimize: {}, verbosity: {}' .format(backend, optimize, verbosity)) assert_(mode in {'lcbc', 'penalty'})
assert_(term_mode in {'original', 'einsum'})
sfepy.base.base.assert_
r""" Incompressible Stokes flow with Navier (slip) boundary conditions, flow driven by a moving wall and a small diffusion for stabilization. This example demonstrates the use of `no-penetration` and `edge direction` boundary conditions together with Navier or slip boundary conditions. Alternatively the `no-penetration` boundary conditions can be applied in a weak sense using the penalty term ``dw_non_penetration_p``. Find :math:`\ul{u}`, :math:`p` such that: .. math:: \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u} - \int_{\Omega} p\ \nabla \cdot \ul{v} + \int_{\Gamma_1} \beta \ul{v} \cdot (\ul{u} - \ul{u}_d) + \int_{\Gamma_2} \beta \ul{v} \cdot \ul{u} = 0 \;, \quad \forall \ul{v} \;, \int_{\Omega} \mu \nabla q \cdot \nabla p + \int_{\Omega} q\ \nabla \cdot \ul{u} = 0 \;, \quad \forall q \;, where :math:`\nu` is the fluid viscosity, :math:`\beta` is the slip coefficient, :math:`\mu` is the (small) numerical diffusion coefficient, :math:`\Gamma_1` is the top wall that moves with the given driving velocity :math:`\ul{u}_d` and :math:`\Gamma_2` are the remaining walls. The Navier conditions are in effect on both :math:`\Gamma_1`, :math:`\Gamma_2` and are expressed by the corresponding integrals in the equations above. The `no-penetration` boundary conditions are applied on :math:`\Gamma_1`, :math:`\Gamma_2`, except the vertices of the block edges, where the `edge direction` boundary conditions are applied. The penalty term formulation is given by the following equations. Find :math:`\ul{u}`, :math:`p` such that: .. math:: \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u} - \int_{\Omega} p\ \nabla \cdot \ul{v} + \int_{\Gamma_1} \beta \ul{v} \cdot (\ul{u} - \ul{u}_d) + \int_{\Gamma_2} \beta \ul{v} \cdot \ul{u} + \int_{\Gamma_1 \cup \Gamma_2} \epsilon (\ul{n} \cdot \ul{v}) (\ul{n} \cdot \ul{u}) = 0 \;, \quad \forall \ul{v} \;, \int_{\Omega} \mu \nabla q \cdot \nabla p + \int_{\Omega} q\ \nabla \cdot \ul{u} = 0 \;, \quad \forall q \;, where :math:`\epsilon` is the penalty coefficient (sufficiently large). The `no-penetration` boundary conditions are applied on :math:`\Gamma_1`, :math:`\Gamma_2`. Optionally, Dirichlet boundary conditions can be applied on the inlet in the both cases, see below. For large meshes use the ``'ls_i'`` linear solver - PETSc + petsc4py are needed in that case. Several parameters can be set using the ``--define`` option of ``simple.py``, see :func:`define()` and the examples below. Examples -------- Specify the inlet velocity and a finer mesh:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d shape="(11,31,31),u_inlet=0.5" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Use the penalty term formulation and einsum-based terms with the default (numpy) backend:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "mode=penalty,term_mode=einsum" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Change backend to opt_einsum (needs to be installed) and use the quadratic velocity approximation order:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "u_order=2,mode=penalty,term_mode=einsum,backend=opt_einsum,optimize=auto" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Note the pressure field distribution improvement w.r.t. the previous examples. IfPETSc + petsc4py are installed, try using the iterative solver to speed up the solution:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "u_order=2,ls=ls_i,mode=penalty,term_mode=einsum,backend=opt_einsum,optimize=auto" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import assert_, output from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.homogenization.utils import define_box_regions def define(dims=(3, 1, 0.5), shape=(11, 15, 15), u_order=1, refine=0, ls='ls_d', u_inlet=None, mode='lcbc', term_mode='original', backend='numpy', optimize='optimal', verbosity=0): """ Parameters ---------- dims : tuple The block domain dimensions. shape : tuple The mesh resolution: increase to improve accuracy. u_order : int The velocity field approximation order. refine : int The refinement level. ls : 'ls_d' or 'ls_i' The pre-configured linear solver name. u_inlet : float, optional The x-component of the inlet velocity. mode : 'lcbc' or 'penalty' The alternative formulations. term_mode : 'original' or 'einsum' The switch to use either the original or new experimental einsum-based terms. backend : str The einsum mode backend. optimize : str The einsum mode optimization (backend dependent). verbosity : 0, 1, 2, 3 The verbosity level of einsum-based terms. """ output('dims: {}, shape: {}, u_order: {}, refine: {}, u_inlet: {}' .format(dims, shape, u_order, refine, u_inlet)) output('linear solver: {}'.format(ls)) output('mode: {}, term_mode: {}'.format(mode, term_mode)) if term_mode == 'einsum': output('backend: {}, optimize: {}, verbosity: {}' .format(backend, optimize, verbosity)) assert_(mode in {'lcbc', 'penalty'}) assert_(term_mode in {'original', 'einsum'}) if u_order > 1: assert_(mode == 'penalty', msg='set mode=penalty to use u_order > 1!') dims = nm.array(dims, dtype=nm.float64) shape = nm.array(shape, dtype=nm.int32) def mesh_hook(mesh, mode): """ Generate the block mesh. """ if mode == 'read': mesh = gen_block_mesh(dims, shape, [0, 0, 0], name='user_block', verbose=False) return mesh elif mode == 'write': pass filename_mesh =
UserMeshIO(mesh_hook)
sfepy.discrete.fem.meshio.UserMeshIO
r""" Incompressible Stokes flow with Navier (slip) boundary conditions, flow driven by a moving wall and a small diffusion for stabilization. This example demonstrates the use of `no-penetration` and `edge direction` boundary conditions together with Navier or slip boundary conditions. Alternatively the `no-penetration` boundary conditions can be applied in a weak sense using the penalty term ``dw_non_penetration_p``. Find :math:`\ul{u}`, :math:`p` such that: .. math:: \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u} - \int_{\Omega} p\ \nabla \cdot \ul{v} + \int_{\Gamma_1} \beta \ul{v} \cdot (\ul{u} - \ul{u}_d) + \int_{\Gamma_2} \beta \ul{v} \cdot \ul{u} = 0 \;, \quad \forall \ul{v} \;, \int_{\Omega} \mu \nabla q \cdot \nabla p + \int_{\Omega} q\ \nabla \cdot \ul{u} = 0 \;, \quad \forall q \;, where :math:`\nu` is the fluid viscosity, :math:`\beta` is the slip coefficient, :math:`\mu` is the (small) numerical diffusion coefficient, :math:`\Gamma_1` is the top wall that moves with the given driving velocity :math:`\ul{u}_d` and :math:`\Gamma_2` are the remaining walls. The Navier conditions are in effect on both :math:`\Gamma_1`, :math:`\Gamma_2` and are expressed by the corresponding integrals in the equations above. The `no-penetration` boundary conditions are applied on :math:`\Gamma_1`, :math:`\Gamma_2`, except the vertices of the block edges, where the `edge direction` boundary conditions are applied. The penalty term formulation is given by the following equations. Find :math:`\ul{u}`, :math:`p` such that: .. math:: \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u} - \int_{\Omega} p\ \nabla \cdot \ul{v} + \int_{\Gamma_1} \beta \ul{v} \cdot (\ul{u} - \ul{u}_d) + \int_{\Gamma_2} \beta \ul{v} \cdot \ul{u} + \int_{\Gamma_1 \cup \Gamma_2} \epsilon (\ul{n} \cdot \ul{v}) (\ul{n} \cdot \ul{u}) = 0 \;, \quad \forall \ul{v} \;, \int_{\Omega} \mu \nabla q \cdot \nabla p + \int_{\Omega} q\ \nabla \cdot \ul{u} = 0 \;, \quad \forall q \;, where :math:`\epsilon` is the penalty coefficient (sufficiently large). The `no-penetration` boundary conditions are applied on :math:`\Gamma_1`, :math:`\Gamma_2`. Optionally, Dirichlet boundary conditions can be applied on the inlet in the both cases, see below. For large meshes use the ``'ls_i'`` linear solver - PETSc + petsc4py are needed in that case. Several parameters can be set using the ``--define`` option of ``simple.py``, see :func:`define()` and the examples below. Examples -------- Specify the inlet velocity and a finer mesh:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d shape="(11,31,31),u_inlet=0.5" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Use the penalty term formulation and einsum-based terms with the default (numpy) backend:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "mode=penalty,term_mode=einsum" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Change backend to opt_einsum (needs to be installed) and use the quadratic velocity approximation order:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "u_order=2,mode=penalty,term_mode=einsum,backend=opt_einsum,optimize=auto" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Note the pressure field distribution improvement w.r.t. the previous examples. IfPETSc + petsc4py are installed, try using the iterative solver to speed up the solution:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "u_order=2,ls=ls_i,mode=penalty,term_mode=einsum,backend=opt_einsum,optimize=auto" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import assert_, output from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.homogenization.utils import define_box_regions def define(dims=(3, 1, 0.5), shape=(11, 15, 15), u_order=1, refine=0, ls='ls_d', u_inlet=None, mode='lcbc', term_mode='original', backend='numpy', optimize='optimal', verbosity=0): """ Parameters ---------- dims : tuple The block domain dimensions. shape : tuple The mesh resolution: increase to improve accuracy. u_order : int The velocity field approximation order. refine : int The refinement level. ls : 'ls_d' or 'ls_i' The pre-configured linear solver name. u_inlet : float, optional The x-component of the inlet velocity. mode : 'lcbc' or 'penalty' The alternative formulations. term_mode : 'original' or 'einsum' The switch to use either the original or new experimental einsum-based terms. backend : str The einsum mode backend. optimize : str The einsum mode optimization (backend dependent). verbosity : 0, 1, 2, 3 The verbosity level of einsum-based terms. """ output('dims: {}, shape: {}, u_order: {}, refine: {}, u_inlet: {}' .format(dims, shape, u_order, refine, u_inlet)) output('linear solver: {}'.format(ls)) output('mode: {}, term_mode: {}'.format(mode, term_mode)) if term_mode == 'einsum': output('backend: {}, optimize: {}, verbosity: {}' .format(backend, optimize, verbosity)) assert_(mode in {'lcbc', 'penalty'}) assert_(term_mode in {'original', 'einsum'}) if u_order > 1: assert_(mode == 'penalty', msg='set mode=penalty to use u_order > 1!') dims = nm.array(dims, dtype=nm.float64) shape = nm.array(shape, dtype=nm.int32) def mesh_hook(mesh, mode): """ Generate the block mesh. """ if mode == 'read': mesh = gen_block_mesh(dims, shape, [0, 0, 0], name='user_block', verbose=False) return mesh elif mode == 'write': pass filename_mesh = UserMeshIO(mesh_hook) regions =
define_box_regions(3, 0.5 * dims)
sfepy.homogenization.utils.define_box_regions
r""" Incompressible Stokes flow with Navier (slip) boundary conditions, flow driven by a moving wall and a small diffusion for stabilization. This example demonstrates the use of `no-penetration` and `edge direction` boundary conditions together with Navier or slip boundary conditions. Alternatively the `no-penetration` boundary conditions can be applied in a weak sense using the penalty term ``dw_non_penetration_p``. Find :math:`\ul{u}`, :math:`p` such that: .. math:: \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u} - \int_{\Omega} p\ \nabla \cdot \ul{v} + \int_{\Gamma_1} \beta \ul{v} \cdot (\ul{u} - \ul{u}_d) + \int_{\Gamma_2} \beta \ul{v} \cdot \ul{u} = 0 \;, \quad \forall \ul{v} \;, \int_{\Omega} \mu \nabla q \cdot \nabla p + \int_{\Omega} q\ \nabla \cdot \ul{u} = 0 \;, \quad \forall q \;, where :math:`\nu` is the fluid viscosity, :math:`\beta` is the slip coefficient, :math:`\mu` is the (small) numerical diffusion coefficient, :math:`\Gamma_1` is the top wall that moves with the given driving velocity :math:`\ul{u}_d` and :math:`\Gamma_2` are the remaining walls. The Navier conditions are in effect on both :math:`\Gamma_1`, :math:`\Gamma_2` and are expressed by the corresponding integrals in the equations above. The `no-penetration` boundary conditions are applied on :math:`\Gamma_1`, :math:`\Gamma_2`, except the vertices of the block edges, where the `edge direction` boundary conditions are applied. The penalty term formulation is given by the following equations. Find :math:`\ul{u}`, :math:`p` such that: .. math:: \int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u} - \int_{\Omega} p\ \nabla \cdot \ul{v} + \int_{\Gamma_1} \beta \ul{v} \cdot (\ul{u} - \ul{u}_d) + \int_{\Gamma_2} \beta \ul{v} \cdot \ul{u} + \int_{\Gamma_1 \cup \Gamma_2} \epsilon (\ul{n} \cdot \ul{v}) (\ul{n} \cdot \ul{u}) = 0 \;, \quad \forall \ul{v} \;, \int_{\Omega} \mu \nabla q \cdot \nabla p + \int_{\Omega} q\ \nabla \cdot \ul{u} = 0 \;, \quad \forall q \;, where :math:`\epsilon` is the penalty coefficient (sufficiently large). The `no-penetration` boundary conditions are applied on :math:`\Gamma_1`, :math:`\Gamma_2`. Optionally, Dirichlet boundary conditions can be applied on the inlet in the both cases, see below. For large meshes use the ``'ls_i'`` linear solver - PETSc + petsc4py are needed in that case. Several parameters can be set using the ``--define`` option of ``simple.py``, see :func:`define()` and the examples below. Examples -------- Specify the inlet velocity and a finer mesh:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d shape="(11,31,31),u_inlet=0.5" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Use the penalty term formulation and einsum-based terms with the default (numpy) backend:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "mode=penalty,term_mode=einsum" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Change backend to opt_einsum (needs to be installed) and use the quadratic velocity approximation order:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "u_order=2,mode=penalty,term_mode=einsum,backend=opt_einsum,optimize=auto" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk Note the pressure field distribution improvement w.r.t. the previous examples. IfPETSc + petsc4py are installed, try using the iterative solver to speed up the solution:: python3 simple.py examples/navier_stokes/stokes_slip_bc -d "u_order=2,ls=ls_i,mode=penalty,term_mode=einsum,backend=opt_einsum,optimize=auto" python3 resview.py -f p:p0 u:o.4:p1 u:g:f0.2:p1 -- user_block.vtk """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import assert_, output from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.homogenization.utils import define_box_regions def define(dims=(3, 1, 0.5), shape=(11, 15, 15), u_order=1, refine=0, ls='ls_d', u_inlet=None, mode='lcbc', term_mode='original', backend='numpy', optimize='optimal', verbosity=0): """ Parameters ---------- dims : tuple The block domain dimensions. shape : tuple The mesh resolution: increase to improve accuracy. u_order : int The velocity field approximation order. refine : int The refinement level. ls : 'ls_d' or 'ls_i' The pre-configured linear solver name. u_inlet : float, optional The x-component of the inlet velocity. mode : 'lcbc' or 'penalty' The alternative formulations. term_mode : 'original' or 'einsum' The switch to use either the original or new experimental einsum-based terms. backend : str The einsum mode backend. optimize : str The einsum mode optimization (backend dependent). verbosity : 0, 1, 2, 3 The verbosity level of einsum-based terms. """ output('dims: {}, shape: {}, u_order: {}, refine: {}, u_inlet: {}' .format(dims, shape, u_order, refine, u_inlet)) output('linear solver: {}'.format(ls)) output('mode: {}, term_mode: {}'.format(mode, term_mode)) if term_mode == 'einsum': output('backend: {}, optimize: {}, verbosity: {}' .format(backend, optimize, verbosity)) assert_(mode in {'lcbc', 'penalty'}) assert_(term_mode in {'original', 'einsum'}) if u_order > 1:
assert_(mode == 'penalty', msg='set mode=penalty to use u_order > 1!')
sfepy.base.base.assert_
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!')
output('using values:')
sfepy.base.base.output
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:')
output(" Young's modulus:", options.young)
sfepy.base.base.output
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young)
output(" Poisson's ratio:", options.poisson)
sfepy.base.base.output
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson)
output(' vertical load:', options.load)
sfepy.base.base.output
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load)
output('uniform mesh refinement level:', options.refine)
sfepy.base.base.output
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh =
Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh')
sfepy.discrete.fem.Mesh.from_file
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain =
FEDomain('domain', mesh)
sfepy.discrete.fem.FEDomain
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u =
FieldVariable('u', 'unknown', field)
sfepy.discrete.FieldVariable
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v =
FieldVariable('v', 'test', field, primary_var_name='u')
sfepy.discrete.FieldVariable
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D =
stiffness_from_youngpoisson(2, options.young, options.poisson)
sfepy.mechanics.matcoefs.stiffness_from_youngpoisson
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt =
Material('Asphalt', D=D)
sfepy.discrete.Material
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral =
Integral('i', order=2*options.order)
sfepy.discrete.Integral
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 =
Integral('i', order=0)
sfepy.discrete.Integral
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq =
Equation('balance', t1 - t2)
sfepy.discrete.Equation
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs =
Equations([eq])
sfepy.discrete.Equations
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0}) ysym = EssentialBC('YSym', left, {'u.0' : 0.0}) ls =
ScipyDirect({})
sfepy.solvers.ls.ScipyDirect
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0}) ysym = EssentialBC('YSym', left, {'u.0' : 0.0}) ls = ScipyDirect({}) nls_status =
IndexedStruct()
sfepy.base.base.IndexedStruct
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0}) ysym = EssentialBC('YSym', left, {'u.0' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls =
Newton({}, lin_solver=ls, status=nls_status)
sfepy.solvers.nls.Newton
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0}) ysym = EssentialBC('YSym', left, {'u.0' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb =
Problem('elasticity', equations=eqs, nls=nls, ls=ls)
sfepy.discrete.Problem
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0}) ysym = EssentialBC('YSym', left, {'u.0' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) pb.time_update(ebcs=Conditions([xsym, ysym])) # Solve the problem. state = pb.solve()
output(nls_status)
sfepy.base.base.output
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0}) ysym = EssentialBC('YSym', left, {'u.0' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) pb.time_update(ebcs=Conditions([xsym, ysym])) # Solve the problem. state = pb.solve() output(nls_status) # Postprocess the solution. out = state.create_output_dict() out = stress_strain(out, pb, state, extend=True) pb.save_state('its2D_interactive.vtk', out=out) gdata = geometry_data['2_3'] nc = len(gdata.coors) integral_vn = Integral('ivn', coors=gdata.coors, weights=[gdata.volume / nc] * nc) nodal_stress(out, pb, state, integrals=Integrals([integral_vn])) if options.probe: # Probe the solution. probes, labels = gen_lines(pb) sfield = Field.from_args('sym_tensor', nm.float64, 3, omega, approx_order=options.order - 1) stress = FieldVariable('stress', 'parameter', sfield, primary_var_name='(set-to-None)') strain = FieldVariable('strain', 'parameter', sfield, primary_var_name='(set-to-None)') cfield = Field.from_args('component', nm.float64, 1, omega, approx_order=options.order - 1) component = FieldVariable('component', 'parameter', cfield, primary_var_name='(set-to-None)') ev = pb.evaluate order = 2 * (options.order - 1) strain_qp = ev('ev_cauchy_strain.%d.Omega(u)' % order, mode='qp') stress_qp = ev('ev_cauchy_stress.%d.Omega(Asphalt.D, u)' % order, mode='qp', copy_materials=False)
project_by_component(strain, strain_qp, component, order)
sfepy.discrete.projections.project_by_component
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0}) ysym = EssentialBC('YSym', left, {'u.0' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) pb.time_update(ebcs=Conditions([xsym, ysym])) # Solve the problem. state = pb.solve() output(nls_status) # Postprocess the solution. out = state.create_output_dict() out = stress_strain(out, pb, state, extend=True) pb.save_state('its2D_interactive.vtk', out=out) gdata = geometry_data['2_3'] nc = len(gdata.coors) integral_vn = Integral('ivn', coors=gdata.coors, weights=[gdata.volume / nc] * nc) nodal_stress(out, pb, state, integrals=Integrals([integral_vn])) if options.probe: # Probe the solution. probes, labels = gen_lines(pb) sfield = Field.from_args('sym_tensor', nm.float64, 3, omega, approx_order=options.order - 1) stress = FieldVariable('stress', 'parameter', sfield, primary_var_name='(set-to-None)') strain = FieldVariable('strain', 'parameter', sfield, primary_var_name='(set-to-None)') cfield = Field.from_args('component', nm.float64, 1, omega, approx_order=options.order - 1) component = FieldVariable('component', 'parameter', cfield, primary_var_name='(set-to-None)') ev = pb.evaluate order = 2 * (options.order - 1) strain_qp = ev('ev_cauchy_strain.%d.Omega(u)' % order, mode='qp') stress_qp = ev('ev_cauchy_stress.%d.Omega(Asphalt.D, u)' % order, mode='qp', copy_materials=False) project_by_component(strain, strain_qp, component, order)
project_by_component(stress, stress_qp, component, order)
sfepy.discrete.projections.project_by_component
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0}) ysym = EssentialBC('YSym', left, {'u.0' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) pb.time_update(ebcs=Conditions([xsym, ysym])) # Solve the problem. state = pb.solve() output(nls_status) # Postprocess the solution. out = state.create_output_dict() out = stress_strain(out, pb, state, extend=True) pb.save_state('its2D_interactive.vtk', out=out) gdata = geometry_data['2_3'] nc = len(gdata.coors) integral_vn = Integral('ivn', coors=gdata.coors, weights=[gdata.volume / nc] * nc) nodal_stress(out, pb, state, integrals=Integrals([integral_vn])) if options.probe: # Probe the solution. probes, labels = gen_lines(pb) sfield = Field.from_args('sym_tensor', nm.float64, 3, omega, approx_order=options.order - 1) stress = FieldVariable('stress', 'parameter', sfield, primary_var_name='(set-to-None)') strain = FieldVariable('strain', 'parameter', sfield, primary_var_name='(set-to-None)') cfield = Field.from_args('component', nm.float64, 1, omega, approx_order=options.order - 1) component = FieldVariable('component', 'parameter', cfield, primary_var_name='(set-to-None)') ev = pb.evaluate order = 2 * (options.order - 1) strain_qp = ev('ev_cauchy_strain.%d.Omega(u)' % order, mode='qp') stress_qp = ev('ev_cauchy_stress.%d.Omega(Asphalt.D, u)' % order, mode='qp', copy_materials=False) project_by_component(strain, strain_qp, component, order) project_by_component(stress, stress_qp, component, order) all_results = [] for ii, probe in enumerate(probes): fig, results = probe_results(u, strain, stress, probe, labels[ii]) fig.savefig('its2D_interactive_probe_%d.png' % ii) all_results.append(results) for ii, results in enumerate(all_results): output('probe %d:' % ii) output.level += 2 for key, res in ordered_iteritems(results): output(key + ':') val = res[1] output(' min: %+.2e, mean: %+.2e, max: %+.2e' % (val.min(), val.mean(), val.max())) output.level -= 2 if options.show: # Show the solution. If the approximation order is greater than 1, the # extra DOFs are simply thrown away. from sfepy.postprocess.viewer import Viewer view =
Viewer('its2D_interactive.vtk')
sfepy.postprocess.viewer.Viewer
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(
LineProbe(p0, p1, n_point)
sfepy.discrete.probes.LineProbe
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine):
output('refine %d...' % ii)
sfepy.base.base.output
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0}) ysym = EssentialBC('YSym', left, {'u.0' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) pb.time_update(ebcs=
Conditions([xsym, ysym])
sfepy.discrete.conditions.Conditions
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0}) ysym = EssentialBC('YSym', left, {'u.0' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) pb.time_update(ebcs=Conditions([xsym, ysym])) # Solve the problem. state = pb.solve() output(nls_status) # Postprocess the solution. out = state.create_output_dict() out = stress_strain(out, pb, state, extend=True) pb.save_state('its2D_interactive.vtk', out=out) gdata = geometry_data['2_3'] nc = len(gdata.coors) integral_vn = Integral('ivn', coors=gdata.coors, weights=[gdata.volume / nc] * nc) nodal_stress(out, pb, state, integrals=
Integrals([integral_vn])
sfepy.discrete.Integrals
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0}) ysym = EssentialBC('YSym', left, {'u.0' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) pb.time_update(ebcs=Conditions([xsym, ysym])) # Solve the problem. state = pb.solve() output(nls_status) # Postprocess the solution. out = state.create_output_dict() out = stress_strain(out, pb, state, extend=True) pb.save_state('its2D_interactive.vtk', out=out) gdata = geometry_data['2_3'] nc = len(gdata.coors) integral_vn = Integral('ivn', coors=gdata.coors, weights=[gdata.volume / nc] * nc) nodal_stress(out, pb, state, integrals=Integrals([integral_vn])) if options.probe: # Probe the solution. probes, labels = gen_lines(pb) sfield = Field.from_args('sym_tensor', nm.float64, 3, omega, approx_order=options.order - 1) stress = FieldVariable('stress', 'parameter', sfield, primary_var_name='(set-to-None)') strain = FieldVariable('strain', 'parameter', sfield, primary_var_name='(set-to-None)') cfield = Field.from_args('component', nm.float64, 1, omega, approx_order=options.order - 1) component = FieldVariable('component', 'parameter', cfield, primary_var_name='(set-to-None)') ev = pb.evaluate order = 2 * (options.order - 1) strain_qp = ev('ev_cauchy_strain.%d.Omega(u)' % order, mode='qp') stress_qp = ev('ev_cauchy_stress.%d.Omega(Asphalt.D, u)' % order, mode='qp', copy_materials=False) project_by_component(strain, strain_qp, component, order) project_by_component(stress, stress_qp, component, order) all_results = [] for ii, probe in enumerate(probes): fig, results = probe_results(u, strain, stress, probe, labels[ii]) fig.savefig('its2D_interactive_probe_%d.png' % ii) all_results.append(results) for ii, results in enumerate(all_results):
output('probe %d:' % ii)
sfepy.base.base.output
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0}) ysym = EssentialBC('YSym', left, {'u.0' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) pb.time_update(ebcs=Conditions([xsym, ysym])) # Solve the problem. state = pb.solve() output(nls_status) # Postprocess the solution. out = state.create_output_dict() out = stress_strain(out, pb, state, extend=True) pb.save_state('its2D_interactive.vtk', out=out) gdata = geometry_data['2_3'] nc = len(gdata.coors) integral_vn = Integral('ivn', coors=gdata.coors, weights=[gdata.volume / nc] * nc) nodal_stress(out, pb, state, integrals=Integrals([integral_vn])) if options.probe: # Probe the solution. probes, labels = gen_lines(pb) sfield = Field.from_args('sym_tensor', nm.float64, 3, omega, approx_order=options.order - 1) stress = FieldVariable('stress', 'parameter', sfield, primary_var_name='(set-to-None)') strain = FieldVariable('strain', 'parameter', sfield, primary_var_name='(set-to-None)') cfield = Field.from_args('component', nm.float64, 1, omega, approx_order=options.order - 1) component = FieldVariable('component', 'parameter', cfield, primary_var_name='(set-to-None)') ev = pb.evaluate order = 2 * (options.order - 1) strain_qp = ev('ev_cauchy_strain.%d.Omega(u)' % order, mode='qp') stress_qp = ev('ev_cauchy_stress.%d.Omega(Asphalt.D, u)' % order, mode='qp', copy_materials=False) project_by_component(strain, strain_qp, component, order) project_by_component(stress, stress_qp, component, order) all_results = [] for ii, probe in enumerate(probes): fig, results = probe_results(u, strain, stress, probe, labels[ii]) fig.savefig('its2D_interactive_probe_%d.png' % ii) all_results.append(results) for ii, results in enumerate(all_results): output('probe %d:' % ii) output.level += 2 for key, res in
ordered_iteritems(results)
sfepy.base.base.ordered_iteritems
#!/usr/bin/env python """ Diametrically point loaded 2-D disk, using commands for interactive use. See :ref:`sec-primer`. The script combines the functionality of all the ``its2D_?.py`` examples and allows setting various simulation parameters, namely: - material parameters - displacement field approximation order - uniform mesh refinement level The example shows also how to probe the results as in :ref:`linear_elasticity-its2D_4`, and how to display the results using Mayavi. Using :mod:`sfepy.discrete.probes` allows correct probing of fields with the approximation order greater than one. In the SfePy top-level directory the following command can be used to get usage information:: python examples/linear_elasticity/its2D_interactive.py -h Notes ----- The ``--probe`` and ``--show`` options work simultaneously only if Mayavi and Matplotlib use the same backend type (for example wx). """ from __future__ import absolute_import import sys from six.moves import range sys.path.append('.') from argparse import ArgumentParser, RawDescriptionHelpFormatter import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import assert_, output, ordered_iteritems, IndexedStruct from sfepy.discrete import (FieldVariable, Material, Integral, Integrals, 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.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete.fem.geometry_element import geometry_data from sfepy.discrete.probes import LineProbe from sfepy.discrete.projections import project_by_component from examples.linear_elasticity.its2D_2 import stress_strain from examples.linear_elasticity.its2D_3 import nodal_stress def gen_lines(problem): """ Define two line probes. Additional probes can be added by appending to `ps0` (start points) and `ps1` (end points) lists. """ ps0 = [[0.0, 0.0], [0.0, 0.0]] ps1 = [[75.0, 0.0], [0.0, 75.0]] # Use enough points for higher order approximations. n_point = 1000 labels = ['%s -> %s' % (p0, p1) for p0, p1 in zip(ps0, ps1)] probes = [] for ip in range(len(ps0)): p0, p1 = ps0[ip], ps1[ip] probes.append(LineProbe(p0, p1, n_point)) return probes, labels def probe_results(u, strain, stress, probe, label): """ Probe the results using the given probe and plot the probed values. """ results = {} pars, vals = probe(u) results['u'] = (pars, vals) pars, vals = probe(strain) results['cauchy_strain'] = (pars, vals) pars, vals = probe(stress) results['cauchy_stress'] = (pars, vals) fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = results['u'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$u_{%d}$' % (ic + 1), lw=1, ls='-', marker='+', ms=3) plt.ylabel('displacements') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) sym_indices = ['11', '22', '12'] plt.subplot(312) pars, vals = results['cauchy_strain'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) plt.subplot(313) pars, vals = results['cauchy_stress'] for ic in range(vals.shape[1]): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_indices[ic], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', fontsize=10) return fig, results helps = { 'young' : "the Young's modulus [default: %(default)s]", 'poisson' : "the Poisson's ratio [default: %(default)s]", 'load' : "the vertical load value (negative means compression)" " [default: %(default)s]", 'order' : 'displacement field approximation order [default: %(default)s]', 'refine' : 'uniform mesh refinement level [default: %(default)s]', 'probe' : 'probe the results', 'show' : 'show the results figure', } def main(): from sfepy import data_dir parser = ArgumentParser(description=__doc__, formatter_class=RawDescriptionHelpFormatter) parser.add_argument('--version', action='version', version='%(prog)s') parser.add_argument('--young', metavar='float', type=float, action='store', dest='young', default=2000.0, help=helps['young']) parser.add_argument('--poisson', metavar='float', type=float, action='store', dest='poisson', default=0.4, help=helps['poisson']) parser.add_argument('--load', metavar='float', type=float, action='store', dest='load', default=-1000.0, help=helps['load']) parser.add_argument('--order', metavar='int', type=int, action='store', dest='order', default=1, help=helps['order']) parser.add_argument('-r', '--refine', metavar='int', type=int, action='store', dest='refine', default=0, help=helps['refine']) parser.add_argument('-s', '--show', action="store_true", dest='show', default=False, help=helps['show']) parser.add_argument('-p', '--probe', action="store_true", dest='probe', default=False, help=helps['probe']) options = parser.parse_args() assert_((0.0 < options.poisson < 0.5), "Poisson's ratio must be in ]0, 0.5[!") assert_((0 < options.order), 'displacement approximation order must be at least 1!') output('using values:') output(" Young's modulus:", options.young) output(" Poisson's ratio:", options.poisson) output(' vertical load:', options.load) output('uniform mesh refinement level:', options.refine) # Build the problem definition. mesh = Mesh.from_file(data_dir + '/meshes/2d/its2D.mesh') domain = FEDomain('domain', mesh) if options.refine > 0: for ii in range(options.refine): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) omega = domain.create_region('Omega', 'all') left = domain.create_region('Left', 'vertices in x < 0.001', 'facet') bottom = domain.create_region('Bottom', 'vertices in y < 0.001', 'facet') top = domain.create_region('Top', 'vertex 2', 'vertex') field = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=options.order) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') D = stiffness_from_youngpoisson(2, options.young, options.poisson) asphalt = Material('Asphalt', D=D) load = Material('Load', values={'.val' : [0.0, options.load]}) integral = Integral('i', order=2*options.order) integral0 = Integral('i', order=0) t1 = Term.new('dw_lin_elastic(Asphalt.D, v, u)', integral, omega, Asphalt=asphalt, v=v, u=u) t2 = Term.new('dw_point_load(Load.val, v)', integral0, top, Load=load, v=v) eq = Equation('balance', t1 - t2) eqs = Equations([eq]) xsym = EssentialBC('XSym', bottom, {'u.1' : 0.0}) ysym = EssentialBC('YSym', left, {'u.0' : 0.0}) ls = ScipyDirect({}) nls_status = IndexedStruct() nls = Newton({}, lin_solver=ls, status=nls_status) pb = Problem('elasticity', equations=eqs, nls=nls, ls=ls) pb.time_update(ebcs=Conditions([xsym, ysym])) # Solve the problem. state = pb.solve() output(nls_status) # Postprocess the solution. out = state.create_output_dict() out = stress_strain(out, pb, state, extend=True) pb.save_state('its2D_interactive.vtk', out=out) gdata = geometry_data['2_3'] nc = len(gdata.coors) integral_vn = Integral('ivn', coors=gdata.coors, weights=[gdata.volume / nc] * nc) nodal_stress(out, pb, state, integrals=Integrals([integral_vn])) if options.probe: # Probe the solution. probes, labels = gen_lines(pb) sfield = Field.from_args('sym_tensor', nm.float64, 3, omega, approx_order=options.order - 1) stress = FieldVariable('stress', 'parameter', sfield, primary_var_name='(set-to-None)') strain = FieldVariable('strain', 'parameter', sfield, primary_var_name='(set-to-None)') cfield = Field.from_args('component', nm.float64, 1, omega, approx_order=options.order - 1) component = FieldVariable('component', 'parameter', cfield, primary_var_name='(set-to-None)') ev = pb.evaluate order = 2 * (options.order - 1) strain_qp = ev('ev_cauchy_strain.%d.Omega(u)' % order, mode='qp') stress_qp = ev('ev_cauchy_stress.%d.Omega(Asphalt.D, u)' % order, mode='qp', copy_materials=False) project_by_component(strain, strain_qp, component, order) project_by_component(stress, stress_qp, component, order) all_results = [] for ii, probe in enumerate(probes): fig, results = probe_results(u, strain, stress, probe, labels[ii]) fig.savefig('its2D_interactive_probe_%d.png' % ii) all_results.append(results) for ii, results in enumerate(all_results): output('probe %d:' % ii) output.level += 2 for key, res in ordered_iteritems(results):
output(key + ':')
sfepy.base.base.output
""" Computational domain for isogeometric analysis. """ import os.path as op import numpy as nm from sfepy.base.base import Struct from sfepy.discrete.common.domain import Domain import sfepy.discrete.iga as iga import sfepy.discrete.iga.io as io from sfepy.discrete.iga.extmods.igac import eval_in_tp_coors class NurbsPatch(Struct): """ Single NURBS patch data. """ def __init__(self, knots, degrees, cps, weights, cs, conn): Struct.__init__(self, name='nurbs', knots=knots, degrees=degrees, cps=cps, weights=weights, cs=cs, conn=conn) self.n_els = [len(ii) for ii in cs] self.dim = len(self.n_els) def _get_ref_coors_1d(self, pars, axis): uk = nm.unique(self.knots[axis]) indices = nm.searchsorted(uk[1:], pars) ref_coors = nm.empty_like(pars) for ii in xrange(len(uk) - 1): ispan = nm.where(indices == ii)[0] pp = pars[ispan] ref_coors[ispan] = (pp - uk[ii]) / (uk[ii+1] - uk[ii]) return uk, indices, ref_coors def __call__(self, u=None, v=None, w=None, field=None): """ Igakit-like interface for NURBS evaluation. """ pars = [u] if v is not None: pars += [v] if w is not None: pars += [w] indices = [] rcs = [] for ia, par in enumerate(pars): uk, indx, rc = self._get_ref_coors_1d(par, ia) indices.append(indx.astype(nm.uint32)) rcs.append(rc) out = eval_in_tp_coors(field, indices, rcs, self.cps, self.weights, self.degrees, self.cs, self.conn) return out def evaluate(self, field, u=None, v=None, w=None): """ Igakit-like interface for NURBS evaluation. """ return self(u, v, w, field) class IGDomain(Domain): """ Bezier extraction based NURBS domain for isogeometric analysis. """ @staticmethod def from_file(filename): """ filename : str The name of the IGA domain file. """ (knots, degrees, cps, weights, cs, conn, bcps, bweights, bconn, regions) =
io.read_iga_data(filename)
sfepy.discrete.iga.io.read_iga_data
""" Computational domain for isogeometric analysis. """ import os.path as op import numpy as nm from sfepy.base.base import Struct from sfepy.discrete.common.domain import Domain import sfepy.discrete.iga as iga import sfepy.discrete.iga.io as io from sfepy.discrete.iga.extmods.igac import eval_in_tp_coors class NurbsPatch(Struct): """ Single NURBS patch data. """ def __init__(self, knots, degrees, cps, weights, cs, conn): Struct.__init__(self, name='nurbs', knots=knots, degrees=degrees, cps=cps, weights=weights, cs=cs, conn=conn) self.n_els = [len(ii) for ii in cs] self.dim = len(self.n_els) def _get_ref_coors_1d(self, pars, axis): uk = nm.unique(self.knots[axis]) indices = nm.searchsorted(uk[1:], pars) ref_coors = nm.empty_like(pars) for ii in xrange(len(uk) - 1): ispan = nm.where(indices == ii)[0] pp = pars[ispan] ref_coors[ispan] = (pp - uk[ii]) / (uk[ii+1] - uk[ii]) return uk, indices, ref_coors def __call__(self, u=None, v=None, w=None, field=None): """ Igakit-like interface for NURBS evaluation. """ pars = [u] if v is not None: pars += [v] if w is not None: pars += [w] indices = [] rcs = [] for ia, par in enumerate(pars): uk, indx, rc = self._get_ref_coors_1d(par, ia) indices.append(indx.astype(nm.uint32)) rcs.append(rc) out = eval_in_tp_coors(field, indices, rcs, self.cps, self.weights, self.degrees, self.cs, self.conn) return out def evaluate(self, field, u=None, v=None, w=None): """ Igakit-like interface for NURBS evaluation. """ return self(u, v, w, field) class IGDomain(Domain): """ Bezier extraction based NURBS domain for isogeometric analysis. """ @staticmethod def from_file(filename): """ filename : str The name of the IGA domain file. """ (knots, degrees, cps, weights, cs, conn, bcps, bweights, bconn, regions) = io.read_iga_data(filename) nurbs = NurbsPatch(knots, degrees, cps, weights, cs, conn) bmesh =
Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn)
sfepy.base.base.Struct
""" Computational domain for isogeometric analysis. """ import os.path as op import numpy as nm from sfepy.base.base import Struct from sfepy.discrete.common.domain import Domain import sfepy.discrete.iga as iga import sfepy.discrete.iga.io as io from sfepy.discrete.iga.extmods.igac import eval_in_tp_coors class NurbsPatch(Struct): """ Single NURBS patch data. """ def __init__(self, knots, degrees, cps, weights, cs, conn): Struct.__init__(self, name='nurbs', knots=knots, degrees=degrees, cps=cps, weights=weights, cs=cs, conn=conn) self.n_els = [len(ii) for ii in cs] self.dim = len(self.n_els) def _get_ref_coors_1d(self, pars, axis): uk = nm.unique(self.knots[axis]) indices = nm.searchsorted(uk[1:], pars) ref_coors = nm.empty_like(pars) for ii in xrange(len(uk) - 1): ispan = nm.where(indices == ii)[0] pp = pars[ispan] ref_coors[ispan] = (pp - uk[ii]) / (uk[ii+1] - uk[ii]) return uk, indices, ref_coors def __call__(self, u=None, v=None, w=None, field=None): """ Igakit-like interface for NURBS evaluation. """ pars = [u] if v is not None: pars += [v] if w is not None: pars += [w] indices = [] rcs = [] for ia, par in enumerate(pars): uk, indx, rc = self._get_ref_coors_1d(par, ia) indices.append(indx.astype(nm.uint32)) rcs.append(rc) out = eval_in_tp_coors(field, indices, rcs, self.cps, self.weights, self.degrees, self.cs, self.conn) return out def evaluate(self, field, u=None, v=None, w=None): """ Igakit-like interface for NURBS evaluation. """ return self(u, v, w, field) class IGDomain(Domain): """ Bezier extraction based NURBS domain for isogeometric analysis. """ @staticmethod def from_file(filename): """ filename : str The name of the IGA domain file. """ (knots, degrees, cps, weights, cs, conn, bcps, bweights, bconn, regions) = io.read_iga_data(filename) nurbs = NurbsPatch(knots, degrees, cps, weights, cs, conn) bmesh = Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn) name = op.splitext(filename)[0] domain = IGDomain(name, nurbs=nurbs, bmesh=bmesh, regions=regions) return domain def __init__(self, name, nurbs, bmesh, regions=None, **kwargs): """ Create an IGA domain. Parameters ---------- name : str The domain name. """ Domain.__init__(self, name, nurbs=nurbs, bmesh=bmesh, regions=regions, **kwargs) from sfepy.discrete.fem.geometry_element import create_geometry_elements from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.extmods.cmesh import CMesh from sfepy.discrete.fem.utils import prepare_remap ac = nm.ascontiguousarray self.nurbs.cs = [ac(nm.array(cc, dtype=nm.float64)[:, None, ...]) for cc in self.nurbs.cs] self.nurbs.degrees = self.nurbs.degrees.astype(nm.int32) self.facets =
iga.get_bezier_element_entities(nurbs.degrees)
sfepy.discrete.iga.get_bezier_element_entities
""" Computational domain for isogeometric analysis. """ import os.path as op import numpy as nm from sfepy.base.base import Struct from sfepy.discrete.common.domain import Domain import sfepy.discrete.iga as iga import sfepy.discrete.iga.io as io from sfepy.discrete.iga.extmods.igac import eval_in_tp_coors class NurbsPatch(Struct): """ Single NURBS patch data. """ def __init__(self, knots, degrees, cps, weights, cs, conn): Struct.__init__(self, name='nurbs', knots=knots, degrees=degrees, cps=cps, weights=weights, cs=cs, conn=conn) self.n_els = [len(ii) for ii in cs] self.dim = len(self.n_els) def _get_ref_coors_1d(self, pars, axis): uk = nm.unique(self.knots[axis]) indices = nm.searchsorted(uk[1:], pars) ref_coors = nm.empty_like(pars) for ii in xrange(len(uk) - 1): ispan = nm.where(indices == ii)[0] pp = pars[ispan] ref_coors[ispan] = (pp - uk[ii]) / (uk[ii+1] - uk[ii]) return uk, indices, ref_coors def __call__(self, u=None, v=None, w=None, field=None): """ Igakit-like interface for NURBS evaluation. """ pars = [u] if v is not None: pars += [v] if w is not None: pars += [w] indices = [] rcs = [] for ia, par in enumerate(pars): uk, indx, rc = self._get_ref_coors_1d(par, ia) indices.append(indx.astype(nm.uint32)) rcs.append(rc) out = eval_in_tp_coors(field, indices, rcs, self.cps, self.weights, self.degrees, self.cs, self.conn) return out def evaluate(self, field, u=None, v=None, w=None): """ Igakit-like interface for NURBS evaluation. """ return self(u, v, w, field) class IGDomain(Domain): """ Bezier extraction based NURBS domain for isogeometric analysis. """ @staticmethod def from_file(filename): """ filename : str The name of the IGA domain file. """ (knots, degrees, cps, weights, cs, conn, bcps, bweights, bconn, regions) = io.read_iga_data(filename) nurbs = NurbsPatch(knots, degrees, cps, weights, cs, conn) bmesh = Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn) name = op.splitext(filename)[0] domain = IGDomain(name, nurbs=nurbs, bmesh=bmesh, regions=regions) return domain def __init__(self, name, nurbs, bmesh, regions=None, **kwargs): """ Create an IGA domain. Parameters ---------- name : str The domain name. """ Domain.__init__(self, name, nurbs=nurbs, bmesh=bmesh, regions=regions, **kwargs) from sfepy.discrete.fem.geometry_element import create_geometry_elements from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.extmods.cmesh import CMesh from sfepy.discrete.fem.utils import prepare_remap ac = nm.ascontiguousarray self.nurbs.cs = [ac(nm.array(cc, dtype=nm.float64)[:, None, ...]) for cc in self.nurbs.cs] self.nurbs.degrees = self.nurbs.degrees.astype(nm.int32) self.facets = iga.get_bezier_element_entities(nurbs.degrees) tconn =
iga.get_bezier_topology(bmesh.conn, nurbs.degrees)
sfepy.discrete.iga.get_bezier_topology
""" Computational domain for isogeometric analysis. """ import os.path as op import numpy as nm from sfepy.base.base import Struct from sfepy.discrete.common.domain import Domain import sfepy.discrete.iga as iga import sfepy.discrete.iga.io as io from sfepy.discrete.iga.extmods.igac import eval_in_tp_coors class NurbsPatch(Struct): """ Single NURBS patch data. """ def __init__(self, knots, degrees, cps, weights, cs, conn): Struct.__init__(self, name='nurbs', knots=knots, degrees=degrees, cps=cps, weights=weights, cs=cs, conn=conn) self.n_els = [len(ii) for ii in cs] self.dim = len(self.n_els) def _get_ref_coors_1d(self, pars, axis): uk = nm.unique(self.knots[axis]) indices = nm.searchsorted(uk[1:], pars) ref_coors = nm.empty_like(pars) for ii in xrange(len(uk) - 1): ispan = nm.where(indices == ii)[0] pp = pars[ispan] ref_coors[ispan] = (pp - uk[ii]) / (uk[ii+1] - uk[ii]) return uk, indices, ref_coors def __call__(self, u=None, v=None, w=None, field=None): """ Igakit-like interface for NURBS evaluation. """ pars = [u] if v is not None: pars += [v] if w is not None: pars += [w] indices = [] rcs = [] for ia, par in enumerate(pars): uk, indx, rc = self._get_ref_coors_1d(par, ia) indices.append(indx.astype(nm.uint32)) rcs.append(rc) out = eval_in_tp_coors(field, indices, rcs, self.cps, self.weights, self.degrees, self.cs, self.conn) return out def evaluate(self, field, u=None, v=None, w=None): """ Igakit-like interface for NURBS evaluation. """ return self(u, v, w, field) class IGDomain(Domain): """ Bezier extraction based NURBS domain for isogeometric analysis. """ @staticmethod def from_file(filename): """ filename : str The name of the IGA domain file. """ (knots, degrees, cps, weights, cs, conn, bcps, bweights, bconn, regions) = io.read_iga_data(filename) nurbs = NurbsPatch(knots, degrees, cps, weights, cs, conn) bmesh = Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn) name = op.splitext(filename)[0] domain = IGDomain(name, nurbs=nurbs, bmesh=bmesh, regions=regions) return domain def __init__(self, name, nurbs, bmesh, regions=None, **kwargs): """ Create an IGA domain. Parameters ---------- name : str The domain name. """ Domain.__init__(self, name, nurbs=nurbs, bmesh=bmesh, regions=regions, **kwargs) from sfepy.discrete.fem.geometry_element import create_geometry_elements from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.extmods.cmesh import CMesh from sfepy.discrete.fem.utils import prepare_remap ac = nm.ascontiguousarray self.nurbs.cs = [ac(nm.array(cc, dtype=nm.float64)[:, None, ...]) for cc in self.nurbs.cs] self.nurbs.degrees = self.nurbs.degrees.astype(nm.int32) self.facets = iga.get_bezier_element_entities(nurbs.degrees) tconn = iga.get_bezier_topology(bmesh.conn, nurbs.degrees) itc = nm.unique(tconn) remap = prepare_remap(itc, bmesh.conn.max() + 1) ltcoors = bmesh.cps[itc] ltconn = remap[tconn] n_nod, dim = ltcoors.shape n_el = ltconn.shape[0] self.shape =
Struct(n_nod=n_nod, dim=dim, tdim=0, n_el=n_el, n_gr=1)
sfepy.base.base.Struct
""" Computational domain for isogeometric analysis. """ import os.path as op import numpy as nm from sfepy.base.base import Struct from sfepy.discrete.common.domain import Domain import sfepy.discrete.iga as iga import sfepy.discrete.iga.io as io from sfepy.discrete.iga.extmods.igac import eval_in_tp_coors class NurbsPatch(Struct): """ Single NURBS patch data. """ def __init__(self, knots, degrees, cps, weights, cs, conn): Struct.__init__(self, name='nurbs', knots=knots, degrees=degrees, cps=cps, weights=weights, cs=cs, conn=conn) self.n_els = [len(ii) for ii in cs] self.dim = len(self.n_els) def _get_ref_coors_1d(self, pars, axis): uk = nm.unique(self.knots[axis]) indices = nm.searchsorted(uk[1:], pars) ref_coors = nm.empty_like(pars) for ii in xrange(len(uk) - 1): ispan = nm.where(indices == ii)[0] pp = pars[ispan] ref_coors[ispan] = (pp - uk[ii]) / (uk[ii+1] - uk[ii]) return uk, indices, ref_coors def __call__(self, u=None, v=None, w=None, field=None): """ Igakit-like interface for NURBS evaluation. """ pars = [u] if v is not None: pars += [v] if w is not None: pars += [w] indices = [] rcs = [] for ia, par in enumerate(pars): uk, indx, rc = self._get_ref_coors_1d(par, ia) indices.append(indx.astype(nm.uint32)) rcs.append(rc) out = eval_in_tp_coors(field, indices, rcs, self.cps, self.weights, self.degrees, self.cs, self.conn) return out def evaluate(self, field, u=None, v=None, w=None): """ Igakit-like interface for NURBS evaluation. """ return self(u, v, w, field) class IGDomain(Domain): """ Bezier extraction based NURBS domain for isogeometric analysis. """ @staticmethod def from_file(filename): """ filename : str The name of the IGA domain file. """ (knots, degrees, cps, weights, cs, conn, bcps, bweights, bconn, regions) = io.read_iga_data(filename) nurbs = NurbsPatch(knots, degrees, cps, weights, cs, conn) bmesh = Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn) name = op.splitext(filename)[0] domain = IGDomain(name, nurbs=nurbs, bmesh=bmesh, regions=regions) return domain def __init__(self, name, nurbs, bmesh, regions=None, **kwargs): """ Create an IGA domain. Parameters ---------- name : str The domain name. """ Domain.__init__(self, name, nurbs=nurbs, bmesh=bmesh, regions=regions, **kwargs) from sfepy.discrete.fem.geometry_element import create_geometry_elements from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.extmods.cmesh import CMesh from sfepy.discrete.fem.utils import prepare_remap ac = nm.ascontiguousarray self.nurbs.cs = [ac(nm.array(cc, dtype=nm.float64)[:, None, ...]) for cc in self.nurbs.cs] self.nurbs.degrees = self.nurbs.degrees.astype(nm.int32) self.facets = iga.get_bezier_element_entities(nurbs.degrees) tconn = iga.get_bezier_topology(bmesh.conn, nurbs.degrees) itc = nm.unique(tconn) remap = prepare_remap(itc, bmesh.conn.max() + 1) ltcoors = bmesh.cps[itc] ltconn = remap[tconn] n_nod, dim = ltcoors.shape n_el = ltconn.shape[0] self.shape = Struct(n_nod=n_nod, dim=dim, tdim=0, n_el=n_el, n_gr=1) desc = '%d_%d' % (dim, 2**dim) mat_id = nm.zeros(ltconn.shape[0], dtype=nm.int32) self.mesh = Mesh.from_data(self.name + '_topo', ltcoors, None, [ltconn], [mat_id], [desc]) self.cmesh =
CMesh.from_mesh(self.mesh)
sfepy.discrete.fem.extmods.cmesh.CMesh.from_mesh
""" Computational domain for isogeometric analysis. """ import os.path as op import numpy as nm from sfepy.base.base import Struct from sfepy.discrete.common.domain import Domain import sfepy.discrete.iga as iga import sfepy.discrete.iga.io as io from sfepy.discrete.iga.extmods.igac import eval_in_tp_coors class NurbsPatch(Struct): """ Single NURBS patch data. """ def __init__(self, knots, degrees, cps, weights, cs, conn): Struct.__init__(self, name='nurbs', knots=knots, degrees=degrees, cps=cps, weights=weights, cs=cs, conn=conn) self.n_els = [len(ii) for ii in cs] self.dim = len(self.n_els) def _get_ref_coors_1d(self, pars, axis): uk = nm.unique(self.knots[axis]) indices = nm.searchsorted(uk[1:], pars) ref_coors = nm.empty_like(pars) for ii in xrange(len(uk) - 1): ispan = nm.where(indices == ii)[0] pp = pars[ispan] ref_coors[ispan] = (pp - uk[ii]) / (uk[ii+1] - uk[ii]) return uk, indices, ref_coors def __call__(self, u=None, v=None, w=None, field=None): """ Igakit-like interface for NURBS evaluation. """ pars = [u] if v is not None: pars += [v] if w is not None: pars += [w] indices = [] rcs = [] for ia, par in enumerate(pars): uk, indx, rc = self._get_ref_coors_1d(par, ia) indices.append(indx.astype(nm.uint32)) rcs.append(rc) out = eval_in_tp_coors(field, indices, rcs, self.cps, self.weights, self.degrees, self.cs, self.conn) return out def evaluate(self, field, u=None, v=None, w=None): """ Igakit-like interface for NURBS evaluation. """ return self(u, v, w, field) class IGDomain(Domain): """ Bezier extraction based NURBS domain for isogeometric analysis. """ @staticmethod def from_file(filename): """ filename : str The name of the IGA domain file. """ (knots, degrees, cps, weights, cs, conn, bcps, bweights, bconn, regions) = io.read_iga_data(filename) nurbs = NurbsPatch(knots, degrees, cps, weights, cs, conn) bmesh = Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn) name = op.splitext(filename)[0] domain = IGDomain(name, nurbs=nurbs, bmesh=bmesh, regions=regions) return domain def __init__(self, name, nurbs, bmesh, regions=None, **kwargs): """ Create an IGA domain. Parameters ---------- name : str The domain name. """ Domain.__init__(self, name, nurbs=nurbs, bmesh=bmesh, regions=regions, **kwargs) from sfepy.discrete.fem.geometry_element import create_geometry_elements from sfepy.discrete.fem import Mesh from sfepy.discrete.fem.extmods.cmesh import CMesh from sfepy.discrete.fem.utils import prepare_remap ac = nm.ascontiguousarray self.nurbs.cs = [ac(nm.array(cc, dtype=nm.float64)[:, None, ...]) for cc in self.nurbs.cs] self.nurbs.degrees = self.nurbs.degrees.astype(nm.int32) self.facets = iga.get_bezier_element_entities(nurbs.degrees) tconn = iga.get_bezier_topology(bmesh.conn, nurbs.degrees) itc = nm.unique(tconn) remap = prepare_remap(itc, bmesh.conn.max() + 1) ltcoors = bmesh.cps[itc] ltconn = remap[tconn] n_nod, dim = ltcoors.shape n_el = ltconn.shape[0] self.shape = Struct(n_nod=n_nod, dim=dim, tdim=0, n_el=n_el, n_gr=1) desc = '%d_%d' % (dim, 2**dim) mat_id = nm.zeros(ltconn.shape[0], dtype=nm.int32) self.mesh = Mesh.from_data(self.name + '_topo', ltcoors, None, [ltconn], [mat_id], [desc]) self.cmesh = CMesh.from_mesh(self.mesh) gels =
create_geometry_elements()
sfepy.discrete.fem.geometry_element.create_geometry_elements
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes =
split_range(total_size, chunk_size)
sfepy.linalg.split_range
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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__
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) self.function =
Struct.get(self, 'function', None)
sfepy.base.base.Struct.get
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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 subdomain lists (igs). """ 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_igs = v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: v_igs = field.igs 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, self.arg_traces.values()) if is_any_trace: region.setup_mirror_region() self.char_fun.igs = region.igs 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() if field is not None: s_igs = field.igs else: s_igs = None 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, virtual_igs=v_igs, state=svar, state_igs=s_igs, primary=svar, primary_igs=s_igs, 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() if field is not None: p_igs = field.igs else: p_igs = None 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, virtual_igs=v_igs, state=None, state_igs=[], primary=pvar.get_primary(), primary_igs=p_igs, 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, virtual_igs=v_igs, state=vvar.get_primary(), state_igs=v_igs, primary=vvar.get_primary(), primary_igs=v_igs, 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 = [] iname, region_name, ig = self.get_current_group() 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, self.integral_name), ig, 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 self.integration.iteritems(): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.itervalues())) 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_current_group(self): return (self.integral_name, self.region.name, self.char_fun.ig) def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def set_current_group(self, ig): self.char_fun.set_current_group(ig) def igs(self): return self.char_fun.igs 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 iter_groups(self): if self.dof_conn_type == 'point': igs = self.igs()[0:1] else: igs = self.igs() for ig in igs: if self.integration in ('volume', 'plate'): if not len(self.region.get_cells(ig)): continue self.set_current_group(ig) yield ig def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic 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_approximation(self, variable, get_saved=False): """ Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`). """ geo, _, key = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return ap, geo 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.name) 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(self.region.igs) elif self.integration == 'plate': phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, 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
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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 subdomain lists (igs). """ 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_igs = v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: v_igs = field.igs 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, self.arg_traces.values()) if is_any_trace: region.setup_mirror_region() self.char_fun.igs = region.igs 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() if field is not None: s_igs = field.igs else: s_igs = None 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, virtual_igs=v_igs, state=svar, state_igs=s_igs, primary=svar, primary_igs=s_igs, 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() if field is not None: p_igs = field.igs else: p_igs = None 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, virtual_igs=v_igs, state=None, state_igs=[], primary=pvar.get_primary(), primary_igs=p_igs, 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, virtual_igs=v_igs, state=vvar.get_primary(), state_igs=v_igs, primary=vvar.get_primary(), primary_igs=v_igs, 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 = [] iname, region_name, ig = self.get_current_group() 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, self.integral_name), ig, 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 self.integration.iteritems(): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.itervalues())) 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_current_group(self): return (self.integral_name, self.region.name, self.char_fun.ig) def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def set_current_group(self, ig): self.char_fun.set_current_group(ig) def igs(self): return self.char_fun.igs 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 iter_groups(self): if self.dof_conn_type == 'point': igs = self.igs()[0:1] else: igs = self.igs() for ig in igs: if self.integration in ('volume', 'plate'): if not len(self.region.get_cells(ig)): continue self.set_current_group(ig) yield ig def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic 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_approximation(self, variable, get_saved=False): """ Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`). """ geo, _, key = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return ap, geo 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.name) 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(self.region.igs) elif self.integration == 'plate': phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, 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
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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 subdomain lists (igs). """ 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_igs = v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: v_igs = field.igs 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, self.arg_traces.values()) if is_any_trace: region.setup_mirror_region() self.char_fun.igs = region.igs 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() if field is not None: s_igs = field.igs else: s_igs = None 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, virtual_igs=v_igs, state=svar, state_igs=s_igs, primary=svar, primary_igs=s_igs, 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() if field is not None: p_igs = field.igs else: p_igs = None 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, virtual_igs=v_igs, state=None, state_igs=[], primary=pvar.get_primary(), primary_igs=p_igs, 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, virtual_igs=v_igs, state=vvar.get_primary(), state_igs=v_igs, primary=vvar.get_primary(), primary_igs=v_igs, 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 = [] iname, region_name, ig = self.get_current_group() 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, self.integral_name), ig, 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 self.integration.iteritems(): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.itervalues())) 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_current_group(self): return (self.integral_name, self.region.name, self.char_fun.ig) def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def set_current_group(self, ig): self.char_fun.set_current_group(ig) def igs(self): return self.char_fun.igs 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 iter_groups(self): if self.dof_conn_type == 'point': igs = self.igs()[0:1] else: igs = self.igs() for ig in igs: if self.integration in ('volume', 'plate'): if not len(self.region.get_cells(ig)): continue self.set_current_group(ig) yield ig def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic 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_approximation(self, variable, get_saved=False): """ Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`). """ geo, _, key = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return ap, geo 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.name) 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(self.region.igs) elif self.integration == 'plate': phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, 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(self.char_fun.ig, 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): """ Default implementation of function to check term argument shapes at run-time. """ pass 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
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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 subdomain lists (igs). """ 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_igs = v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: v_igs = field.igs 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, self.arg_traces.values()) if is_any_trace: region.setup_mirror_region() self.char_fun.igs = region.igs 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() if field is not None: s_igs = field.igs else: s_igs = None 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, virtual_igs=v_igs, state=svar, state_igs=s_igs, primary=svar, primary_igs=s_igs, 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() if field is not None: p_igs = field.igs else: p_igs = None 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, virtual_igs=v_igs, state=None, state_igs=[], primary=pvar.get_primary(), primary_igs=p_igs, 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, virtual_igs=v_igs, state=vvar.get_primary(), state_igs=v_igs, primary=vvar.get_primary(), primary_igs=v_igs, 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 = [] iname, region_name, ig = self.get_current_group() 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, self.integral_name), ig, 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 self.integration.iteritems(): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.itervalues())) 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_current_group(self): return (self.integral_name, self.region.name, self.char_fun.ig) def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def set_current_group(self, ig): self.char_fun.set_current_group(ig) def igs(self): return self.char_fun.igs 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 iter_groups(self): if self.dof_conn_type == 'point': igs = self.igs()[0:1] else: igs = self.igs() for ig in igs: if self.integration in ('volume', 'plate'): if not len(self.region.get_cells(ig)): continue self.set_current_group(ig) yield ig def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic 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_approximation(self, variable, get_saved=False): """ Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`). """ geo, _, key = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return ap, geo 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.name) 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(self.region.igs)
sfepy.discrete.common.mappings.PhysicalQPs
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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 subdomain lists (igs). """ 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_igs = v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: v_igs = field.igs 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, self.arg_traces.values()) if is_any_trace: region.setup_mirror_region() self.char_fun.igs = region.igs 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() if field is not None: s_igs = field.igs else: s_igs = None 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, virtual_igs=v_igs, state=svar, state_igs=s_igs, primary=svar, primary_igs=s_igs, 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() if field is not None: p_igs = field.igs else: p_igs = None 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, virtual_igs=v_igs, state=None, state_igs=[], primary=pvar.get_primary(), primary_igs=p_igs, 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, virtual_igs=v_igs, state=vvar.get_primary(), state_igs=v_igs, primary=vvar.get_primary(), primary_igs=v_igs, 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 = [] iname, region_name, ig = self.get_current_group() 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, self.integral_name), ig, 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 self.integration.iteritems(): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.itervalues())) 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_current_group(self): return (self.integral_name, self.region.name, self.char_fun.ig) def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def set_current_group(self, ig): self.char_fun.set_current_group(ig) def igs(self): return self.char_fun.igs 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 iter_groups(self): if self.dof_conn_type == 'point': igs = self.igs()[0:1] else: igs = self.igs() for ig in igs: if self.integration in ('volume', 'plate'): if not len(self.region.get_cells(ig)): continue self.set_current_group(ig) yield ig def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic 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_approximation(self, variable, get_saved=False): """ Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`). """ geo, _, key = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return ap, geo 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.name) 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(self.region.igs) elif self.integration == 'plate': phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, 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(self.char_fun.ig, 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): """ Default implementation of function to check term argument shapes at run-time. """ pass 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: terms.errclear() raise ValueError return fargs def call_function(self, out, fargs): try: status = self.function(out, *fargs) except RuntimeError: terms.errclear() raise ValueError if status:
terms.errclear()
sfepy.terms.extmods.terms.errclear
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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 subdomain lists (igs). """ 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_igs = v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: v_igs = field.igs 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, self.arg_traces.values()) if is_any_trace: region.setup_mirror_region() self.char_fun.igs = region.igs 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() if field is not None: s_igs = field.igs else: s_igs = None 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, virtual_igs=v_igs, state=svar, state_igs=s_igs, primary=svar, primary_igs=s_igs, 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() if field is not None: p_igs = field.igs else: p_igs = None 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, virtual_igs=v_igs, state=None, state_igs=[], primary=pvar.get_primary(), primary_igs=p_igs, 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, virtual_igs=v_igs, state=vvar.get_primary(), state_igs=v_igs, primary=vvar.get_primary(), primary_igs=v_igs, 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 = [] iname, region_name, ig = self.get_current_group() 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, self.integral_name), ig, 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 self.integration.iteritems(): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.itervalues())) 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_current_group(self): return (self.integral_name, self.region.name, self.char_fun.ig) def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def set_current_group(self, ig): self.char_fun.set_current_group(ig) def igs(self): return self.char_fun.igs 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 iter_groups(self): if self.dof_conn_type == 'point': igs = self.igs()[0:1] else: igs = self.igs() for ig in igs: if self.integration in ('volume', 'plate'): if not len(self.region.get_cells(ig)): continue self.set_current_group(ig) yield ig def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic 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_approximation(self, variable, get_saved=False): """ Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`). """ geo, _, key = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return ap, geo 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.name) 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(self.region.igs) elif self.integration == 'plate': phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') else: phys_qps =
get_physical_qps(self.region, self.integral)
sfepy.discrete.common.mappings.get_physical_qps
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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 subdomain lists (igs). """ 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_igs = v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: v_igs = field.igs 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, self.arg_traces.values()) if is_any_trace: region.setup_mirror_region() self.char_fun.igs = region.igs 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() if field is not None: s_igs = field.igs else: s_igs = None 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, virtual_igs=v_igs, state=svar, state_igs=s_igs, primary=svar, primary_igs=s_igs, 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() if field is not None: p_igs = field.igs else: p_igs = None 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, virtual_igs=v_igs, state=None, state_igs=[], primary=pvar.get_primary(), primary_igs=p_igs, 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, virtual_igs=v_igs, state=vvar.get_primary(), state_igs=v_igs, primary=vvar.get_primary(), primary_igs=v_igs, 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 = [] iname, region_name, ig = self.get_current_group() 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, self.integral_name), ig, 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 self.integration.iteritems(): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.itervalues())) 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_current_group(self): return (self.integral_name, self.region.name, self.char_fun.ig) def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def set_current_group(self, ig): self.char_fun.set_current_group(ig) def igs(self): return self.char_fun.igs 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 iter_groups(self): if self.dof_conn_type == 'point': igs = self.igs()[0:1] else: igs = self.igs() for ig in igs: if self.integration in ('volume', 'plate'): if not len(self.region.get_cells(ig)): continue self.set_current_group(ig) yield ig def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic 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_approximation(self, variable, get_saved=False): """ Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`). """ geo, _, key = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return ap, geo 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.name) 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(self.region.igs) elif self.integration == 'plate': phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, 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(self.char_fun.ig, 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): """ Default implementation of function to check term argument shapes at run-time. """ pass 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:
terms.errclear()
sfepy.terms.extmods.terms.errclear
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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 subdomain lists (igs). """ 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_igs = v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: v_igs = field.igs 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, self.arg_traces.values()) if is_any_trace: region.setup_mirror_region() self.char_fun.igs = region.igs 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() if field is not None: s_igs = field.igs else: s_igs = None 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, virtual_igs=v_igs, state=svar, state_igs=s_igs, primary=svar, primary_igs=s_igs, 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() if field is not None: p_igs = field.igs else: p_igs = None 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, virtual_igs=v_igs, state=None, state_igs=[], primary=pvar.get_primary(), primary_igs=p_igs, 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, virtual_igs=v_igs, state=vvar.get_primary(), state_igs=v_igs, primary=vvar.get_primary(), primary_igs=v_igs, 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 = [] iname, region_name, ig = self.get_current_group() 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, self.integral_name), ig, 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 self.integration.iteritems(): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.itervalues())) 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_current_group(self): return (self.integral_name, self.region.name, self.char_fun.ig) def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def set_current_group(self, ig): self.char_fun.set_current_group(ig) def igs(self): return self.char_fun.igs 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 iter_groups(self): if self.dof_conn_type == 'point': igs = self.igs()[0:1] else: igs = self.igs() for ig in igs: if self.integration in ('volume', 'plate'): if not len(self.region.get_cells(ig)): continue self.set_current_group(ig) yield ig def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic 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_approximation(self, variable, get_saved=False): """ Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`). """ geo, _, key = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return ap, geo 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.name) 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(self.region.igs) elif self.integration == 'plate': phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, 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(self.char_fun.ig, 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): """ Default implementation of function to check term argument shapes at run-time. """ pass 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: terms.errclear() raise ValueError return fargs def call_function(self, out, fargs): try: status = self.function(out, *fargs) except RuntimeError:
terms.errclear()
sfepy.terms.extmods.terms.errclear
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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 subdomain lists (igs). """ 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_igs = v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: v_igs = field.igs 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, self.arg_traces.values()) if is_any_trace: region.setup_mirror_region() self.char_fun.igs = region.igs 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() if field is not None: s_igs = field.igs else: s_igs = None 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, virtual_igs=v_igs, state=svar, state_igs=s_igs, primary=svar, primary_igs=s_igs, 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() if field is not None: p_igs = field.igs else: p_igs = None 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, virtual_igs=v_igs, state=None, state_igs=[], primary=pvar.get_primary(), primary_igs=p_igs, 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, virtual_igs=v_igs, state=vvar.get_primary(), state_igs=v_igs, primary=vvar.get_primary(), primary_igs=v_igs, 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 = [] iname, region_name, ig = self.get_current_group() 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, self.integral_name), ig, 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 self.integration.iteritems(): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.itervalues())) 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_current_group(self): return (self.integral_name, self.region.name, self.char_fun.ig) def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def set_current_group(self, ig): self.char_fun.set_current_group(ig) def igs(self): return self.char_fun.igs 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 iter_groups(self): if self.dof_conn_type == 'point': igs = self.igs()[0:1] else: igs = self.igs() for ig in igs: if self.integration in ('volume', 'plate'): if not len(self.region.get_cells(ig)): continue self.set_current_group(ig) yield ig def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic 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_approximation(self, variable, get_saved=False): """ Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`). """ geo, _, key = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return ap, geo 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.name) 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(self.region.igs) elif self.integration == 'plate': phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, 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(self.char_fun.ig, 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): """ Default implementation of function to check term argument shapes at run-time. """ pass 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: terms.errclear() raise ValueError return fargs def call_function(self, out, fargs): try: status = self.function(out, *fargs) except RuntimeError: terms.errclear() raise ValueError 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, 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 == 'eval': val = 0.0 status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = tuple(args) + (mode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) shape, dtype = self.get_eval_shape(*_args, **kwargs) if dtype == nm.float64: _v, stat = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif dtype == nm.complex128: _v, stat = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % dtype) val += _v status += stat val *= self.sign elif mode in ('el_avg', 'el', 'qp'): vals = None iels = nm.empty((0, 2), dtype=nm.int32) status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = tuple(args) + (mode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) shape, dtype = self.get_eval_shape(*_args, **kwargs) if dtype == nm.float64: val, stat = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif dtype == nm.complex128: val, stat = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) if vals is None: vals = val else: vals = nm.r_[vals, val] _iels = self.get_assembling_cells(val.shape) aux = nm.c_[nm.repeat(ig, _iels.shape[0])[:, None], _iels[:, None]] iels = nm.r_[iels, aux] status += stat vals *= self.sign elif mode == 'weak': vals = [] iels = [] status = 0 varr = self.get_virtual_variable() if diff_var is not None: varc = self.get_variables(as_list=False)[diff_var] for ig in self.iter_groups(): 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: val, stat = self.eval_real(shape, fargs, mode, term_mode, diff_var, **kwargs) elif varr.dtype == nm.complex128: val, stat = self.eval_complex(shape, fargs, mode, term_mode, diff_var, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % varr.dtype) vals.append(self.sign * val) iels.append((ig, self.get_assembling_cells(val.shape))) status += stat # Setup return value. if mode == 'eval': out = (val,) else: out = (vals, iels) if goptions['check_term_finiteness']: assert_(nm.isfinite(out[0]).all(), msg='%+.2e * %s.%d.%s(%s) term values not finite!' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_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): import sfepy.discrete.fem.extmods.assemble as asm vvar = self.get_virtual_variable() dc_type = self.get_dof_conn_type() if mode == 'vector': if asm_obj.dtype == nm.float64: assemble = asm.assemble_vector else:
assert_(asm_obj.dtype == nm.complex128)
sfepy.base.base.assert_
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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 subdomain lists (igs). """ 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_igs = v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: v_igs = field.igs 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, self.arg_traces.values()) if is_any_trace: region.setup_mirror_region() self.char_fun.igs = region.igs 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() if field is not None: s_igs = field.igs else: s_igs = None 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, virtual_igs=v_igs, state=svar, state_igs=s_igs, primary=svar, primary_igs=s_igs, 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() if field is not None: p_igs = field.igs else: p_igs = None 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, virtual_igs=v_igs, state=None, state_igs=[], primary=pvar.get_primary(), primary_igs=p_igs, 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, virtual_igs=v_igs, state=vvar.get_primary(), state_igs=v_igs, primary=vvar.get_primary(), primary_igs=v_igs, 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 = [] iname, region_name, ig = self.get_current_group() 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, self.integral_name), ig, 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 self.integration.iteritems(): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.itervalues())) 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_current_group(self): return (self.integral_name, self.region.name, self.char_fun.ig) def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def set_current_group(self, ig): self.char_fun.set_current_group(ig) def igs(self): return self.char_fun.igs 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 iter_groups(self): if self.dof_conn_type == 'point': igs = self.igs()[0:1] else: igs = self.igs() for ig in igs: if self.integration in ('volume', 'plate'): if not len(self.region.get_cells(ig)): continue self.set_current_group(ig) yield ig def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic 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_approximation(self, variable, get_saved=False): """ Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`). """ geo, _, key = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return ap, geo 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.name) 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(self.region.igs) elif self.integration == 'plate': phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, 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(self.char_fun.ig, 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): """ Default implementation of function to check term argument shapes at run-time. """ pass 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: terms.errclear() raise ValueError return fargs def call_function(self, out, fargs): try: status = self.function(out, *fargs) except RuntimeError: terms.errclear() raise ValueError 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, 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 == 'eval': val = 0.0 status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = tuple(args) + (mode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) shape, dtype = self.get_eval_shape(*_args, **kwargs) if dtype == nm.float64: _v, stat = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif dtype == nm.complex128: _v, stat = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % dtype) val += _v status += stat val *= self.sign elif mode in ('el_avg', 'el', 'qp'): vals = None iels = nm.empty((0, 2), dtype=nm.int32) status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = tuple(args) + (mode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) shape, dtype = self.get_eval_shape(*_args, **kwargs) if dtype == nm.float64: val, stat = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif dtype == nm.complex128: val, stat = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) if vals is None: vals = val else: vals = nm.r_[vals, val] _iels = self.get_assembling_cells(val.shape) aux = nm.c_[nm.repeat(ig, _iels.shape[0])[:, None], _iels[:, None]] iels = nm.r_[iels, aux] status += stat vals *= self.sign elif mode == 'weak': vals = [] iels = [] status = 0 varr = self.get_virtual_variable() if diff_var is not None: varc = self.get_variables(as_list=False)[diff_var] for ig in self.iter_groups(): 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: val, stat = self.eval_real(shape, fargs, mode, term_mode, diff_var, **kwargs) elif varr.dtype == nm.complex128: val, stat = self.eval_complex(shape, fargs, mode, term_mode, diff_var, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % varr.dtype) vals.append(self.sign * val) iels.append((ig, self.get_assembling_cells(val.shape))) status += stat # Setup return value. if mode == 'eval': out = (val,) else: out = (vals, iels) if goptions['check_term_finiteness']: assert_(nm.isfinite(out[0]).all(), msg='%+.2e * %s.%d.%s(%s) term values not finite!' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_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): import sfepy.discrete.fem.extmods.assemble as asm vvar = self.get_virtual_variable() dc_type = self.get_dof_conn_type() 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]) for ii, (ig, _iels) in enumerate(iels): vec_in_els = val[ii] dc = vvar.get_dof_conn(dc_type, ig)
assert_(vec_in_els.shape[2] == dc.shape[1])
sfepy.base.base.assert_
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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 subdomain lists (igs). """ 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_igs = v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: v_igs = field.igs 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, self.arg_traces.values()) if is_any_trace: region.setup_mirror_region() self.char_fun.igs = region.igs 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() if field is not None: s_igs = field.igs else: s_igs = None 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, virtual_igs=v_igs, state=svar, state_igs=s_igs, primary=svar, primary_igs=s_igs, 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() if field is not None: p_igs = field.igs else: p_igs = None 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, virtual_igs=v_igs, state=None, state_igs=[], primary=pvar.get_primary(), primary_igs=p_igs, 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, virtual_igs=v_igs, state=vvar.get_primary(), state_igs=v_igs, primary=vvar.get_primary(), primary_igs=v_igs, 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 = [] iname, region_name, ig = self.get_current_group() 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, self.integral_name), ig, 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 self.integration.iteritems(): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.itervalues())) 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_current_group(self): return (self.integral_name, self.region.name, self.char_fun.ig) def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def set_current_group(self, ig): self.char_fun.set_current_group(ig) def igs(self): return self.char_fun.igs 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 iter_groups(self): if self.dof_conn_type == 'point': igs = self.igs()[0:1] else: igs = self.igs() for ig in igs: if self.integration in ('volume', 'plate'): if not len(self.region.get_cells(ig)): continue self.set_current_group(ig) yield ig def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic 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_approximation(self, variable, get_saved=False): """ Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`). """ geo, _, key = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return ap, geo 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.name) 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(self.region.igs) elif self.integration == 'plate': phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, 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(self.char_fun.ig, 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): """ Default implementation of function to check term argument shapes at run-time. """ pass 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
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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 subdomain lists (igs). """ 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_igs = v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: v_igs = field.igs 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, self.arg_traces.values()) if is_any_trace: region.setup_mirror_region() self.char_fun.igs = region.igs 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() if field is not None: s_igs = field.igs else: s_igs = None 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, virtual_igs=v_igs, state=svar, state_igs=s_igs, primary=svar, primary_igs=s_igs, 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() if field is not None: p_igs = field.igs else: p_igs = None 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, virtual_igs=v_igs, state=None, state_igs=[], primary=pvar.get_primary(), primary_igs=p_igs, 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, virtual_igs=v_igs, state=vvar.get_primary(), state_igs=v_igs, primary=vvar.get_primary(), primary_igs=v_igs, 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 = [] iname, region_name, ig = self.get_current_group() 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, self.integral_name), ig, 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 self.integration.iteritems(): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.itervalues())) 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_current_group(self): return (self.integral_name, self.region.name, self.char_fun.ig) def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def set_current_group(self, ig): self.char_fun.set_current_group(ig) def igs(self): return self.char_fun.igs 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 iter_groups(self): if self.dof_conn_type == 'point': igs = self.igs()[0:1] else: igs = self.igs() for ig in igs: if self.integration in ('volume', 'plate'): if not len(self.region.get_cells(ig)): continue self.set_current_group(ig) yield ig def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic 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_approximation(self, variable, get_saved=False): """ Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`). """ geo, _, key = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return ap, geo 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.name) 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(self.region.igs) elif self.integration == 'plate': phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, 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(self.char_fun.ig, 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): """ Default implementation of function to check term argument shapes at run-time. """ pass 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: terms.errclear() raise ValueError return fargs def call_function(self, out, fargs): try: status = self.function(out, *fargs) except RuntimeError: terms.errclear() raise ValueError 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, 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 == 'eval': val = 0.0 status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = tuple(args) + (mode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) shape, dtype = self.get_eval_shape(*_args, **kwargs) if dtype == nm.float64: _v, stat = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif dtype == nm.complex128: _v, stat = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % dtype) val += _v status += stat val *= self.sign elif mode in ('el_avg', 'el', 'qp'): vals = None iels = nm.empty((0, 2), dtype=nm.int32) status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = tuple(args) + (mode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) shape, dtype = self.get_eval_shape(*_args, **kwargs) if dtype == nm.float64: val, stat = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif dtype == nm.complex128: val, stat = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) if vals is None: vals = val else: vals = nm.r_[vals, val] _iels = self.get_assembling_cells(val.shape) aux = nm.c_[nm.repeat(ig, _iels.shape[0])[:, None], _iels[:, None]] iels = nm.r_[iels, aux] status += stat vals *= self.sign elif mode == 'weak': vals = [] iels = [] status = 0 varr = self.get_virtual_variable() if diff_var is not None: varc = self.get_variables(as_list=False)[diff_var] for ig in self.iter_groups(): 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: val, stat = self.eval_real(shape, fargs, mode, term_mode, diff_var, **kwargs) elif varr.dtype == nm.complex128: val, stat = self.eval_complex(shape, fargs, mode, term_mode, diff_var, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % varr.dtype) vals.append(self.sign * val) iels.append((ig, self.get_assembling_cells(val.shape))) status += stat # Setup return value. if mode == 'eval': out = (val,) else: out = (vals, iels) if goptions['check_term_finiteness']: assert_(nm.isfinite(out[0]).all(), msg='%+.2e * %s.%d.%s(%s) term values not finite!' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_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): import sfepy.discrete.fem.extmods.assemble as asm vvar = self.get_virtual_variable() dc_type = self.get_dof_conn_type() 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]) for ii, (ig, _iels) in enumerate(iels): vec_in_els = val[ii] dc = vvar.get_dof_conn(dc_type, ig) assert_(vec_in_els.shape[2] == dc.shape[1]) assemble(asm_obj, vec_in_els, _iels, 1.0, dc) elif mode == 'matrix': if asm_obj.dtype == nm.float64: assemble = asm.assemble_matrix else:
assert_(asm_obj.dtype == nm.complex128)
sfepy.base.base.assert_
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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() if desc.name == 'intFE': obj = constructor(desc.name, desc.args, None, region, desc=desc) else: obj = constructor(desc.name, desc.args, None, region) obj.set_integral(integrals.get(desc.integral)) 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 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.char_fun = CharacteristicFunction(self.region) 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 __call__(self, diff_var=None, chunk_size=None, **kwargs): """ Subclasses either implement __call__ or plug in a proper _call(). """ return self._call(diff_var, chunk_size, **kwargs) def _call(self, diff_var=None, chunk_size=None, **kwargs): msg = 'base class method "_call" called for %s' \ % self.__class__.__name__ raise RuntimeError(msg) 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 subdomain lists (igs). """ if user is None: user = {} 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 subdomain lists (igs). """ 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_igs = v_tg = None if vvar is not None: field = vvar.get_field() if field is not None: v_igs = field.igs 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, self.arg_traces.values()) if is_any_trace: region.setup_mirror_region() self.char_fun.igs = region.igs 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() if field is not None: s_igs = field.igs else: s_igs = None 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, virtual_igs=v_igs, state=svar, state_igs=s_igs, primary=svar, primary_igs=s_igs, 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() if field is not None: p_igs = field.igs else: p_igs = None 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, virtual_igs=v_igs, state=None, state_igs=[], primary=pvar.get_primary(), primary_igs=p_igs, 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, virtual_igs=v_igs, state=vvar.get_primary(), state_igs=v_igs, primary=vvar.get_primary(), primary_igs=v_igs, 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 = [] iname, region_name, ig = self.get_current_group() 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, self.integral_name), ig, 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 self.integration.iteritems(): var = self.get_args(arg_types=[arg_type])[0] self.geometry_types[var.name] = gtype gtypes = list(set(self.geometry_types.itervalues())) 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_current_group(self): return (self.integral_name, self.region.name, self.char_fun.ig) def get_dof_conn_type(self): return Struct(name='dof_conn_info', type=self.dof_conn_type, region_name=self.region.name) def set_current_group(self, ig): self.char_fun.set_current_group(ig) def igs(self): return self.char_fun.igs 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 iter_groups(self): if self.dof_conn_type == 'point': igs = self.igs()[0:1] else: igs = self.igs() for ig in igs: if self.integration in ('volume', 'plate'): if not len(self.region.get_cells(ig)): continue self.set_current_group(ig) yield ig def time_update(self, ts): if ts is not None: self.step = ts.step self.dt = ts.dt self.is_quasistatic = ts.is_quasistatic 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_approximation(self, variable, get_saved=False): """ Return approximation corresponding to `variable`. Also return the corresponding geometry (actual or saved, according to `get_saved`). """ geo, _, key = self.get_mapping(variable, get_saved=get_saved, return_key=True) ig = key[2] ap = variable.get_approximation(ig) return ap, geo 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.name) 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(self.region.igs) elif self.integration == 'plate': phys_qps = get_physical_qps(self.region, self.integral, map_kind='v') 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.field.get_mapping(ig, 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, ig_map, ig_map_i = self.region.get_mirror_region() ig = ig_map_i[self.char_fun.ig] else: region = self.region ig = self.char_fun.ig out = variable.get_data_shape(ig, 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(self.char_fun.ig, 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): """ Default implementation of function to check term argument shapes at run-time. """ pass 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: terms.errclear() raise ValueError return fargs def call_function(self, out, fargs): try: status = self.function(out, *fargs) except RuntimeError: terms.errclear() raise ValueError 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, 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 == 'eval': val = 0.0 status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = tuple(args) + (mode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) shape, dtype = self.get_eval_shape(*_args, **kwargs) if dtype == nm.float64: _v, stat = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif dtype == nm.complex128: _v, stat = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % dtype) val += _v status += stat val *= self.sign elif mode in ('el_avg', 'el', 'qp'): vals = None iels = nm.empty((0, 2), dtype=nm.int32) status = 0 for ig in self.iter_groups(): args = self.get_args(**kwargs) self.check_shapes(*args) _args = tuple(args) + (mode, term_mode, diff_var) fargs = self.call_get_fargs(_args, kwargs) shape, dtype = self.get_eval_shape(*_args, **kwargs) if dtype == nm.float64: val, stat = self.eval_real(shape, fargs, mode, term_mode, **kwargs) elif dtype == nm.complex128: val, stat = self.eval_complex(shape, fargs, mode, term_mode, **kwargs) if vals is None: vals = val else: vals = nm.r_[vals, val] _iels = self.get_assembling_cells(val.shape) aux = nm.c_[nm.repeat(ig, _iels.shape[0])[:, None], _iels[:, None]] iels = nm.r_[iels, aux] status += stat vals *= self.sign elif mode == 'weak': vals = [] iels = [] status = 0 varr = self.get_virtual_variable() if diff_var is not None: varc = self.get_variables(as_list=False)[diff_var] for ig in self.iter_groups(): 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: val, stat = self.eval_real(shape, fargs, mode, term_mode, diff_var, **kwargs) elif varr.dtype == nm.complex128: val, stat = self.eval_complex(shape, fargs, mode, term_mode, diff_var, **kwargs) else: raise ValueError('unsupported term dtype! (%s)' % varr.dtype) vals.append(self.sign * val) iels.append((ig, self.get_assembling_cells(val.shape))) status += stat # Setup return value. if mode == 'eval': out = (val,) else: out = (vals, iels) if goptions['check_term_finiteness']: assert_(nm.isfinite(out[0]).all(), msg='%+.2e * %s.%d.%s(%s) term values not finite!' % (self.sign, self.name, self.integral.order, self.region.name, self.arg_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): import sfepy.discrete.fem.extmods.assemble as asm vvar = self.get_virtual_variable() dc_type = self.get_dof_conn_type() 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]) for ii, (ig, _iels) in enumerate(iels): vec_in_els = val[ii] dc = vvar.get_dof_conn(dc_type, ig) assert_(vec_in_els.shape[2] == dc.shape[1]) assemble(asm_obj, vec_in_els, _iels, 1.0, dc) 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) for ii, (ig, _iels) in enumerate(iels): mtx_in_els = val[ii] if ((asm_obj.dtype == nm.complex128) and (mtx_in_els.dtype == nm.float64)): mtx_in_els = mtx_in_els.astype(nm.complex128) rdc = vvar.get_dof_conn(dc_type, ig) is_trace = self.arg_traces[svar.name] cdc = svar.get_dof_conn(dc_type, ig, is_trace=is_trace)
assert_(mtx_in_els.shape[2:] == (rdc.shape[1], cdc.shape[1]))
sfepy.base.base.assert_
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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)) def set_current_group(self, ig): for term in self: term.char_fun.set_current_group(ig) class Term(Struct): name = '' arg_types = () arg_shapes = {} integration = 'volume' geometries = ['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
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 from sfepy.linalg import split_range _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 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', '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) 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 vector_chunk_generator(total_size, chunk_size, shape_in, zero=False, set_shape=True, dtype=nm.float64): if not chunk_size: chunk_size = total_size shape = list(shape_in) sizes = split_range(total_size, chunk_size) ii = nm.array(0, dtype=nm.int32) for size in sizes: chunk = nm.arange(size, dtype=nm.int32) + ii if set_shape: shape[0] = size if zero: out = nm.zeros(shape, dtype=dtype) else: out = nm.empty(shape, dtype=dtype) yield out, chunk ii += size 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 # 22.01.2006, c class CharacteristicFunction(Struct): def __init__(self, region): self.igs = region.igs self.region = region self.local_chunk = None self.ig = None def __call__(self, chunk_size, shape_in, zero=False, set_shape=True, ret_local_chunk=False, dtype=nm.float64): els = self.region.get_cells(self.ig) for out, chunk in vector_chunk_generator(els.shape[0], chunk_size, shape_in, zero, set_shape, dtype): self.local_chunk = chunk if ret_local_chunk: yield out, chunk else: yield out, els[chunk] self.local_chunk = None def set_current_group(self, ig): self.ig = ig def get_local_chunk(self): return self.local_chunk class ConnInfo(Struct): def get_region(self, can_trace=True): if self.is_trace and can_trace: return self.region.get_mirror_region()[0] 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()[0] else: reg = self.region if reg is not None: return reg.name else: return None def iter_igs(self): if self.region is not None: for ig in self.region.igs: if self.virtual_igs is not None: ir = self.virtual_igs.tolist().index(ig) rig = self.virtual_igs[ir] else: rig = None if not self.is_trace: ii = ig else: ig_map_i = self.region.get_mirror_region()[2] ii = ig_map_i[ig] if self.state_igs is not None: ic = self.state_igs.tolist().index(ii) cig = self.state_igs[ic] else: cig = None yield rig, cig else: yield None, 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
""" Functions to visualize quadrature points in reference elements. """ import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output from sfepy.postprocess.plot_dofs import _get_axes, _to2d from sfepy.postprocess.plot_facets import plot_geometry def _get_qp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement aux =
Integral('aux', order=order)
sfepy.discrete.Integral
""" Functions to visualize quadrature points in reference elements. """ import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output from sfepy.postprocess.plot_dofs import _get_axes, _to2d from sfepy.postprocess.plot_facets import plot_geometry def _get_qp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement aux = Integral('aux', order=order) coors, weights = aux.get_qp(geometry) true_order = aux.qps[geometry].order output('geometry:', geometry, 'order:', order, 'num. points:', coors.shape[0], 'true_order:', true_order) output('min. weight:', weights.min()) output('max. weight:', weights.max()) return GeometryElement(geometry), coors, weights def _get_bqp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement from sfepy.discrete.fem import Mesh, FEDomain, Field gel =
GeometryElement(geometry)
sfepy.discrete.fem.geometry_element.GeometryElement
""" Functions to visualize quadrature points in reference elements. """ import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output from sfepy.postprocess.plot_dofs import _get_axes, _to2d from sfepy.postprocess.plot_facets import plot_geometry def _get_qp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement aux = Integral('aux', order=order) coors, weights = aux.get_qp(geometry) true_order = aux.qps[geometry].order output('geometry:', geometry, 'order:', order, 'num. points:', coors.shape[0], 'true_order:', true_order) output('min. weight:', weights.min()) output('max. weight:', weights.max()) return GeometryElement(geometry), coors, weights def _get_bqp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement from sfepy.discrete.fem import Mesh, FEDomain, Field gel = GeometryElement(geometry) mesh = Mesh.from_data('aux', gel.coors, None, [gel.conn[None, :]], [[0]], [geometry]) domain =
FEDomain('domain', mesh)
sfepy.discrete.fem.FEDomain
""" Functions to visualize quadrature points in reference elements. """ import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output from sfepy.postprocess.plot_dofs import _get_axes, _to2d from sfepy.postprocess.plot_facets import plot_geometry def _get_qp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement aux = Integral('aux', order=order) coors, weights = aux.get_qp(geometry) true_order = aux.qps[geometry].order output('geometry:', geometry, 'order:', order, 'num. points:', coors.shape[0], 'true_order:', true_order) output('min. weight:', weights.min()) output('max. weight:', weights.max()) return GeometryElement(geometry), coors, weights def _get_bqp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement from sfepy.discrete.fem import Mesh, FEDomain, Field gel = GeometryElement(geometry) mesh = Mesh.from_data('aux', gel.coors, None, [gel.conn[None, :]], [[0]], [geometry]) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') surf = domain.create_region('Surf', 'vertices of surface', 'facet') field = Field.from_args('f', nm.float64, shape=1, region=omega, approx_order=1) field.setup_surface_data(surf) integral =
Integral('aux', order=order)
sfepy.discrete.Integral