prompt
stringlengths
174
59.5k
completion
stringlengths
7
228
api
stringlengths
12
64
from __future__ import absolute_import from copy import copy import numpy as nm from sfepy.base.testing import TestCommon from sfepy.base.base import ordered_iteritems from sfepy import data_dir filename_meshes = [data_dir + '/meshes/elements/%s_2.mesh' % geom for geom in ['1_2', '2_3', '2_4', '3_4', '3_8', '3_2_4']] def make_term_args(arg_shapes, arg_kinds, arg_types, ats_mode, domain, material_value=None, poly_space_base=None): from sfepy.base.base import basestr from sfepy.discrete import FieldVariable, Material, Variables, Materials from sfepy.discrete.fem import Field from sfepy.solvers.ts import TimeStepper from sfepy.mechanics.tensors import dim2sym omega = domain.regions['Omega'] dim = domain.shape.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number ;) return 1 else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return [_parse_scalar_shape(ii.strip()) for ii in sh.split(',')] else: return (int(sh),) args = {} str_args = [] materials = [] variables = [] for ii, arg_kind in enumerate(arg_kinds): if arg_kind != 'ts': if ats_mode is not None: extended_ats = arg_types[ii] + ('/%s' % ats_mode) else: extended_ats = arg_types[ii] try: sh = arg_shapes[arg_types[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) field = Field.from_args('f%d' % ii, nm.float64, shape, omega, approx_order=1, poly_space_base=poly_space_base) if arg_kind == 'virtual_variable': if sh[1] is not None: istate = arg_types.index(sh[1]) else: # Only virtual variable in arguments. istate = -1 # -> Make fake variable. var =
FieldVariable('u-1', 'unknown', field)
sfepy.discrete.FieldVariable
from __future__ import absolute_import from copy import copy import numpy as nm from sfepy.base.testing import TestCommon from sfepy.base.base import ordered_iteritems from sfepy import data_dir filename_meshes = [data_dir + '/meshes/elements/%s_2.mesh' % geom for geom in ['1_2', '2_3', '2_4', '3_4', '3_8', '3_2_4']] def make_term_args(arg_shapes, arg_kinds, arg_types, ats_mode, domain, material_value=None, poly_space_base=None): from sfepy.base.base import basestr from sfepy.discrete import FieldVariable, Material, Variables, Materials from sfepy.discrete.fem import Field from sfepy.solvers.ts import TimeStepper from sfepy.mechanics.tensors import dim2sym omega = domain.regions['Omega'] dim = domain.shape.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number ;) return 1 else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return [_parse_scalar_shape(ii.strip()) for ii in sh.split(',')] else: return (int(sh),) args = {} str_args = [] materials = [] variables = [] for ii, arg_kind in enumerate(arg_kinds): if arg_kind != 'ts': if ats_mode is not None: extended_ats = arg_types[ii] + ('/%s' % ats_mode) else: extended_ats = arg_types[ii] try: sh = arg_shapes[arg_types[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) field = Field.from_args('f%d' % ii, nm.float64, shape, omega, approx_order=1, poly_space_base=poly_space_base) if arg_kind == 'virtual_variable': if sh[1] is not None: istate = arg_types.index(sh[1]) else: # Only virtual variable in arguments. istate = -1 # -> Make fake variable. var = FieldVariable('u-1', 'unknown', field) var.set_constant(0.0) variables.append(var) var = FieldVariable('v', 'test', field, primary_var_name='u%d' % istate) elif arg_kind == 'state_variable': var =
FieldVariable('u%d' % ii, 'unknown', field)
sfepy.discrete.FieldVariable
from __future__ import absolute_import from copy import copy import numpy as nm from sfepy.base.testing import TestCommon from sfepy.base.base import ordered_iteritems from sfepy import data_dir filename_meshes = [data_dir + '/meshes/elements/%s_2.mesh' % geom for geom in ['1_2', '2_3', '2_4', '3_4', '3_8', '3_2_4']] def make_term_args(arg_shapes, arg_kinds, arg_types, ats_mode, domain, material_value=None, poly_space_base=None): from sfepy.base.base import basestr from sfepy.discrete import FieldVariable, Material, Variables, Materials from sfepy.discrete.fem import Field from sfepy.solvers.ts import TimeStepper from sfepy.mechanics.tensors import dim2sym omega = domain.regions['Omega'] dim = domain.shape.dim sym = dim2sym(dim) def _parse_scalar_shape(sh): if isinstance(sh, basestr): if sh == 'D': return dim elif sh == 'D2': return dim**2 elif sh == 'S': return sym elif sh == 'N': # General number ;) return 1 else: return int(sh) else: return sh def _parse_tuple_shape(sh): if isinstance(sh, basestr): return [_parse_scalar_shape(ii.strip()) for ii in sh.split(',')] else: return (int(sh),) args = {} str_args = [] materials = [] variables = [] for ii, arg_kind in enumerate(arg_kinds): if arg_kind != 'ts': if ats_mode is not None: extended_ats = arg_types[ii] + ('/%s' % ats_mode) else: extended_ats = arg_types[ii] try: sh = arg_shapes[arg_types[ii]] except KeyError: sh = arg_shapes[extended_ats] if arg_kind.endswith('variable'): shape = _parse_scalar_shape(sh[0] if isinstance(sh, tuple) else sh) field = Field.from_args('f%d' % ii, nm.float64, shape, omega, approx_order=1, poly_space_base=poly_space_base) if arg_kind == 'virtual_variable': if sh[1] is not None: istate = arg_types.index(sh[1]) else: # Only virtual variable in arguments. istate = -1 # -> Make fake variable. var = FieldVariable('u-1', 'unknown', field) var.set_constant(0.0) variables.append(var) var = FieldVariable('v', 'test', field, primary_var_name='u%d' % istate) elif arg_kind == 'state_variable': var = FieldVariable('u%d' % ii, 'unknown', field) var.set_constant(0.0) elif arg_kind == 'parameter_variable': var = FieldVariable('p%d' % ii, 'parameter', field, primary_var_name='(set-to-None)') var.set_constant(0.0) variables.append(var) str_args.append(var.name) args[var.name] = var elif arg_kind.endswith('material'): if sh is None: # Switched-off opt_material. continue prefix = '' if isinstance(sh, basestr): aux = sh.split(':') if len(aux) == 2: prefix, sh = aux if material_value is None: material_value = 1.0 shape = _parse_tuple_shape(sh) if (len(shape) > 1) or (shape[0] > 1): if ((len(shape) == 2) and (shape[0] == shape[1]) and (material_value != 0.0)): # Identity matrix. val = nm.eye(shape[0], dtype=nm.float64) else: # Array. val = nm.empty(shape, dtype=nm.float64) val.fill(material_value) values = {'%sc%d' % (prefix, ii) : val} elif (len(shape) == 1) and (shape[0] == 1): # Single scalar as a special value. values = {'.c%d' % ii : material_value} else: raise ValueError('wrong material shape! (%s)' % shape) mat = Material('m%d' % ii, values=values) materials.append(mat) str_args.append(mat.name + '.' + 'c%d' % ii) args[mat.name] = mat elif arg_kind == 'ts': ts =
TimeStepper(0.0, 1.0, 1.0, 5)
sfepy.solvers.ts.TimeStepper
""" Basic uniform mesh refinement functions. """ import numpy as nm from sfepy.discrete.fem import Mesh def refine_2_3(mesh_in): """ Refines mesh out of triangles by cutting cutting each edge in half and making 4 new finer triangles out of one coarser one. """ cmesh = mesh_in.cmesh # Unique edge centres. e_centres = cmesh.get_centroids(cmesh.dim - 1) # New coordinates after the original ones. coors = nm.r_[mesh_in.coors, e_centres] o1 = mesh_in.n_nod cc = cmesh.get_conn(cmesh.dim, cmesh.dim - 1) conn = mesh_in.get_conn('2_3') n_el = conn.shape[0] e_nodes = cc.indices.reshape((n_el, 3)) + o1 c = nm.c_[conn, e_nodes].T new_conn = nm.vstack([c[0], c[3], c[5], c[3], c[4], c[5], c[1], c[4], c[3], c[2], c[5], c[4]]).T new_conn = new_conn.reshape((4 * n_el, 3)) new_mat_id = cmesh.cell_groups.repeat(4) mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, [new_conn], [new_mat_id], mesh_in.descs ) return mesh def refine_2_4(mesh_in): """ Refines mesh out of quadrilaterals by cutting cutting each edge in half and making 4 new finer quadrilaterals out of one coarser one. """ cmesh = mesh_in.cmesh # Unique edge centres. e_centres = cmesh.get_centroids(cmesh.dim - 1) # Unique element centres. centres = cmesh.get_centroids(cmesh.dim) # New coordinates after the original ones. coors = nm.r_[mesh_in.coors, e_centres, centres] o1 = mesh_in.n_nod o2 = o1 + e_centres.shape[0] cc = cmesh.get_conn(cmesh.dim, cmesh.dim - 1) conn = mesh_in.get_conn('2_4') n_el = conn.shape[0] e_nodes = cc.indices.reshape((n_el, 4)) + o1 nodes = nm.arange(n_el) + o2 c = nm.c_[conn, e_nodes, nodes].T new_conn = nm.vstack([c[0], c[4], c[8], c[7], c[1], c[5], c[8], c[4], c[2], c[6], c[8], c[5], c[3], c[7], c[8], c[6]]).T new_conn = new_conn.reshape((4 * n_el, 4)) new_mat_id = cmesh.cell_groups.repeat(4) mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, [new_conn], [new_mat_id], mesh_in.descs ) return mesh def refine_3_4(mesh_in): """ Refines tetrahedra by cutting each edge in half and making 8 new finer tetrahedra out of one coarser one. Old nodal coordinates come first in `coors`, then the new ones. The new tetrahedra are similar to the old one, no degeneration is supposed to occur as at most 3 congruence classes of tetrahedra appear, even when re-applied iteratively (provided that `conns` are not modified between two applications - ordering of vertices in tetrahedra matters not only for positivity of volumes). References: - <NAME>: Simplicial grid refinement: on Freudenthal s algorithm and the optimal number of congruence classes, Numer.Math. 85 (2000), no. 1, 1--29, or - <NAME>: Tetrahedral grid refinement, Computing 55 (1995), no. 4, 355--378, or http://citeseer.ist.psu.edu/bey95tetrahedral.html """ cmesh = mesh_in.cmesh # Unique edge centres. e_centres = cmesh.get_centroids(cmesh.dim - 2) # New coordinates after the original ones. coors = nm.r_[mesh_in.coors, e_centres] o1 = mesh_in.n_nod cc = cmesh.get_conn(cmesh.dim, cmesh.dim - 2) conn = mesh_in.get_conn('3_4') n_el = conn.shape[0] e_nodes = cc.indices.reshape((n_el, 6)) + o1 c = nm.c_[conn, e_nodes].T new_conn = nm.vstack([c[0], c[4], c[6], c[7], c[4], c[1], c[5], c[8], c[6], c[5], c[2], c[9], c[7], c[8], c[9], c[3], c[4], c[6], c[7], c[8], c[4], c[6], c[8], c[5], c[6], c[7], c[8], c[9], c[6], c[5], c[9], c[8]]).T new_conn = new_conn.reshape((8 * n_el, 4)) new_mat_id = cmesh.cell_groups.repeat(8) mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, [new_conn], [new_mat_id], mesh_in.descs ) return mesh def refine_3_8(mesh_in): """ Refines hexahedral mesh by cutting cutting each edge in half and making 8 new finer hexahedrons out of one coarser one. """ cmesh = mesh_in.cmesh # Unique edge centres. e_centres = cmesh.get_centroids(cmesh.dim - 2) # Unique face centres. f_centres = cmesh.get_centroids(cmesh.dim - 1) # Unique element centres. centres = cmesh.get_centroids(cmesh.dim) # New coordinates after the original ones. coors = nm.r_[mesh_in.coors, e_centres, f_centres, centres] o1 = mesh_in.n_nod o2 = o1 + e_centres.shape[0] o3 = o2 + f_centres.shape[0] ecc = cmesh.get_conn(cmesh.dim, cmesh.dim - 2) fcc = cmesh.get_conn(cmesh.dim, cmesh.dim - 1) conn = mesh_in.get_conn('3_8') n_el = conn.shape[0] st = nm.vstack e_nodes = ecc.indices.reshape((n_el, 12)) + o1 f_nodes = fcc.indices.reshape((n_el, 6)) + o2 nodes = nm.arange(n_el) + o3 c = nm.c_[conn, e_nodes, f_nodes, nodes].T new_conn = st([c[0], c[8], c[20], c[11], c[16], c[22], c[26], c[21], c[1], c[9], c[20], c[8], c[17], c[24], c[26], c[22], c[2], c[10], c[20], c[9], c[18], c[25], c[26], c[24], c[3], c[11], c[20], c[10], c[19], c[21], c[26], c[25], c[4], c[15], c[23], c[12], c[16], c[21], c[26], c[22], c[5], c[12], c[23], c[13], c[17], c[22], c[26], c[24], c[6], c[13], c[23], c[14], c[18], c[24], c[26], c[25], c[7], c[14], c[23], c[15], c[19], c[25], c[26], c[21]]).T new_conn = new_conn.reshape((8 * n_el, 8)) new_mat_id = cmesh.cell_groups.repeat(8) mesh = Mesh.from_data(mesh_in.name + '_r', coors, None, [new_conn], [new_mat_id], mesh_in.descs ) return mesh def refine_reference(geometry, level): """ Refine reference element given by `geometry`. Notes ----- The error edges must be generated in the order of the connectivity of the previous (lower) level. """ from sfepy.discrete.fem import FEDomain from sfepy.discrete.fem.geometry_element import geometry_data gcoors, gconn = geometry.coors, geometry.conn if level == 0: return gcoors, gconn, None gd = geometry_data[geometry.name] conn = nm.array([gd.conn], dtype=nm.int32) mat_id = conn[:, 0].copy() mat_id[:] = 0 mesh = Mesh.from_data('aux', gd.coors, None, [conn], [mat_id], [geometry.name]) domain =
FEDomain('aux', mesh)
sfepy.discrete.fem.FEDomain
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape)
assert_(1 <= dim <= 3)
sfepy.base.base.assert_
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape)
output('generating %d vertices...' % n_nod, verbose=verbose)
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd
output('...done', verbose=verbose)
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1)
output('generating %d cells...' % n_el, verbose=verbose)
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape)
output('...done', verbose=verbose)
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh =
Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc])
sfepy.discrete.fem.mesh.Mesh.from_data
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only...
output('generating %d vertices...' % n_nod, verbose=verbose)
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1
assert_(ii == n_nod)
sfepy.base.base.assert_
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod)
output('...done', verbose=verbose)
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32)
output('generating %d cells...' % n_el, verbose=verbose)
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in
cycle([nr-1, nnfi, nl-1])
sfepy.linalg.cycle
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1))
output('...done', verbose=verbose)
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh =
Mesh.from_data(name, coors, None, [conn], [mat_id], [desc])
sfepy.discrete.fem.mesh.Mesh.from_data
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 =
match_grid_plane(coors[s1], coors[s2], idim)
sfepy.discrete.fem.periodic.match_grid_plane
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None
output('repeating %s ...' % grid)
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None output('repeating %s ...' % grid) nblk = 1 for ii, gr in enumerate(grid): if ret_ndmap: (conn, coors, ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps, ndmap=ndmap) ndmap = ndmap0 else: conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps) nblk *= gr
output('...done')
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None output('repeating %s ...' % grid) nblk = 1 for ii, gr in enumerate(grid): if ret_ndmap: (conn, coors, ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps, ndmap=ndmap) ndmap = ndmap0 else: conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps) nblk *= gr output('...done') mat_ids = nm.tile(mat_ids, (nrep,)) mesh_out = Mesh.from_data('tiled mesh', coors * scale, ngrps, [conn], [mat_ids], [mesh.descs[0]]) if ret_ndmap: return mesh_out, ndmap else: return mesh_out def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ import os from sfepy import data_dir defdir = os.path.join(data_dir, 'meshes') if mesh_dir is None: mesh_dir = defdir def retype(args, types, defaults): args=list(args) args.extend(defaults[len(args):len(defaults)]) return tuple([type(value) for type, value in zip(types, args) ]) if kind == 'sphere': default = [5, 41, args[0]] args = retype(args, [float, int, float], default) mesh_pattern = os.path.join(mesh_dir, 'sphere-%.2f-%.2f-%i') else:
assert_(kind == 'cube')
sfepy.base.base.assert_
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None output('repeating %s ...' % grid) nblk = 1 for ii, gr in enumerate(grid): if ret_ndmap: (conn, coors, ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps, ndmap=ndmap) ndmap = ndmap0 else: conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps) nblk *= gr output('...done') mat_ids = nm.tile(mat_ids, (nrep,)) mesh_out = Mesh.from_data('tiled mesh', coors * scale, ngrps, [conn], [mat_ids], [mesh.descs[0]]) if ret_ndmap: return mesh_out, ndmap else: return mesh_out def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ import os from sfepy import data_dir defdir = os.path.join(data_dir, 'meshes') if mesh_dir is None: mesh_dir = defdir def retype(args, types, defaults): args=list(args) args.extend(defaults[len(args):len(defaults)]) return tuple([type(value) for type, value in zip(types, args) ]) if kind == 'sphere': default = [5, 41, args[0]] args = retype(args, [float, int, float], default) mesh_pattern = os.path.join(mesh_dir, 'sphere-%.2f-%.2f-%i') else: assert_(kind == 'cube') args = retype(args, (int, float, int, float, int, float), (args[0], args[1], args[0], args[1], args[0], args[1])) mesh_pattern = os.path.join(mesh_dir, 'cube-%i_%.2f-%i_%.2f-%i_%.2f') if verbose:
output(args)
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None output('repeating %s ...' % grid) nblk = 1 for ii, gr in enumerate(grid): if ret_ndmap: (conn, coors, ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps, ndmap=ndmap) ndmap = ndmap0 else: conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps) nblk *= gr output('...done') mat_ids = nm.tile(mat_ids, (nrep,)) mesh_out = Mesh.from_data('tiled mesh', coors * scale, ngrps, [conn], [mat_ids], [mesh.descs[0]]) if ret_ndmap: return mesh_out, ndmap else: return mesh_out def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ import os from sfepy import data_dir defdir = os.path.join(data_dir, 'meshes') if mesh_dir is None: mesh_dir = defdir def retype(args, types, defaults): args=list(args) args.extend(defaults[len(args):len(defaults)]) return tuple([type(value) for type, value in zip(types, args) ]) if kind == 'sphere': default = [5, 41, args[0]] args = retype(args, [float, int, float], default) mesh_pattern = os.path.join(mesh_dir, 'sphere-%.2f-%.2f-%i') else: assert_(kind == 'cube') args = retype(args, (int, float, int, float, int, float), (args[0], args[1], args[0], args[1], args[0], args[1])) mesh_pattern = os.path.join(mesh_dir, 'cube-%i_%.2f-%i_%.2f-%i_%.2f') if verbose: output(args) filename = mesh_pattern % args if not force_create: if os.path.exists(filename): return filename if os.path.exists(filename + '.mesh') : return filename + '.mesh' if os.path.exists(filename + '.vtk'): return filename + '.vtk' if kind == 'cube': filename = filename + suffix
ensure_path(filename)
sfepy.base.ioutils.ensure_path
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None output('repeating %s ...' % grid) nblk = 1 for ii, gr in enumerate(grid): if ret_ndmap: (conn, coors, ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps, ndmap=ndmap) ndmap = ndmap0 else: conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps) nblk *= gr output('...done') mat_ids = nm.tile(mat_ids, (nrep,)) mesh_out = Mesh.from_data('tiled mesh', coors * scale, ngrps, [conn], [mat_ids], [mesh.descs[0]]) if ret_ndmap: return mesh_out, ndmap else: return mesh_out def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ import os from sfepy import data_dir defdir = os.path.join(data_dir, 'meshes') if mesh_dir is None: mesh_dir = defdir def retype(args, types, defaults): args=list(args) args.extend(defaults[len(args):len(defaults)]) return tuple([type(value) for type, value in zip(types, args) ]) if kind == 'sphere': default = [5, 41, args[0]] args = retype(args, [float, int, float], default) mesh_pattern = os.path.join(mesh_dir, 'sphere-%.2f-%.2f-%i') else: assert_(kind == 'cube') args = retype(args, (int, float, int, float, int, float), (args[0], args[1], args[0], args[1], args[0], args[1])) mesh_pattern = os.path.join(mesh_dir, 'cube-%i_%.2f-%i_%.2f-%i_%.2f') if verbose: output(args) filename = mesh_pattern % args if not force_create: if os.path.exists(filename): return filename if os.path.exists(filename + '.mesh') : return filename + '.mesh' if os.path.exists(filename + '.vtk'): return filename + '.vtk' if kind == 'cube': filename = filename + suffix ensure_path(filename)
output('creating new cube mesh')
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None output('repeating %s ...' % grid) nblk = 1 for ii, gr in enumerate(grid): if ret_ndmap: (conn, coors, ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps, ndmap=ndmap) ndmap = ndmap0 else: conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps) nblk *= gr output('...done') mat_ids = nm.tile(mat_ids, (nrep,)) mesh_out = Mesh.from_data('tiled mesh', coors * scale, ngrps, [conn], [mat_ids], [mesh.descs[0]]) if ret_ndmap: return mesh_out, ndmap else: return mesh_out def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ import os from sfepy import data_dir defdir = os.path.join(data_dir, 'meshes') if mesh_dir is None: mesh_dir = defdir def retype(args, types, defaults): args=list(args) args.extend(defaults[len(args):len(defaults)]) return tuple([type(value) for type, value in zip(types, args) ]) if kind == 'sphere': default = [5, 41, args[0]] args = retype(args, [float, int, float], default) mesh_pattern = os.path.join(mesh_dir, 'sphere-%.2f-%.2f-%i') else: assert_(kind == 'cube') args = retype(args, (int, float, int, float, int, float), (args[0], args[1], args[0], args[1], args[0], args[1])) mesh_pattern = os.path.join(mesh_dir, 'cube-%i_%.2f-%i_%.2f-%i_%.2f') if verbose: output(args) filename = mesh_pattern % args if not force_create: if os.path.exists(filename): return filename if os.path.exists(filename + '.mesh') : return filename + '.mesh' if os.path.exists(filename + '.vtk'): return filename + '.vtk' if kind == 'cube': filename = filename + suffix ensure_path(filename) output('creating new cube mesh') output('(%i nodes in %.2f) x (%i nodes in %.2f) x (%i nodes in %.2f)' % args)
output('to file %s...' % filename)
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None output('repeating %s ...' % grid) nblk = 1 for ii, gr in enumerate(grid): if ret_ndmap: (conn, coors, ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps, ndmap=ndmap) ndmap = ndmap0 else: conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps) nblk *= gr output('...done') mat_ids = nm.tile(mat_ids, (nrep,)) mesh_out = Mesh.from_data('tiled mesh', coors * scale, ngrps, [conn], [mat_ids], [mesh.descs[0]]) if ret_ndmap: return mesh_out, ndmap else: return mesh_out def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ import os from sfepy import data_dir defdir = os.path.join(data_dir, 'meshes') if mesh_dir is None: mesh_dir = defdir def retype(args, types, defaults): args=list(args) args.extend(defaults[len(args):len(defaults)]) return tuple([type(value) for type, value in zip(types, args) ]) if kind == 'sphere': default = [5, 41, args[0]] args = retype(args, [float, int, float], default) mesh_pattern = os.path.join(mesh_dir, 'sphere-%.2f-%.2f-%i') else: assert_(kind == 'cube') args = retype(args, (int, float, int, float, int, float), (args[0], args[1], args[0], args[1], args[0], args[1])) mesh_pattern = os.path.join(mesh_dir, 'cube-%i_%.2f-%i_%.2f-%i_%.2f') if verbose: output(args) filename = mesh_pattern % args if not force_create: if os.path.exists(filename): return filename if os.path.exists(filename + '.mesh') : return filename + '.mesh' if os.path.exists(filename + '.vtk'): return filename + '.vtk' if kind == 'cube': filename = filename + suffix ensure_path(filename) output('creating new cube mesh') output('(%i nodes in %.2f) x (%i nodes in %.2f) x (%i nodes in %.2f)' % args) output('to file %s...' % filename) mesh = gen_block_mesh(args[1::2], args[0::2], (0.0, 0.0, 0.0), name=filename) mesh.write(filename, io='auto')
output('...done')
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None output('repeating %s ...' % grid) nblk = 1 for ii, gr in enumerate(grid): if ret_ndmap: (conn, coors, ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps, ndmap=ndmap) ndmap = ndmap0 else: conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps) nblk *= gr output('...done') mat_ids = nm.tile(mat_ids, (nrep,)) mesh_out = Mesh.from_data('tiled mesh', coors * scale, ngrps, [conn], [mat_ids], [mesh.descs[0]]) if ret_ndmap: return mesh_out, ndmap else: return mesh_out def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ import os from sfepy import data_dir defdir = os.path.join(data_dir, 'meshes') if mesh_dir is None: mesh_dir = defdir def retype(args, types, defaults): args=list(args) args.extend(defaults[len(args):len(defaults)]) return tuple([type(value) for type, value in zip(types, args) ]) if kind == 'sphere': default = [5, 41, args[0]] args = retype(args, [float, int, float], default) mesh_pattern = os.path.join(mesh_dir, 'sphere-%.2f-%.2f-%i') else: assert_(kind == 'cube') args = retype(args, (int, float, int, float, int, float), (args[0], args[1], args[0], args[1], args[0], args[1])) mesh_pattern = os.path.join(mesh_dir, 'cube-%i_%.2f-%i_%.2f-%i_%.2f') if verbose: output(args) filename = mesh_pattern % args if not force_create: if os.path.exists(filename): return filename if os.path.exists(filename + '.mesh') : return filename + '.mesh' if os.path.exists(filename + '.vtk'): return filename + '.vtk' if kind == 'cube': filename = filename + suffix ensure_path(filename) output('creating new cube mesh') output('(%i nodes in %.2f) x (%i nodes in %.2f) x (%i nodes in %.2f)' % args) output('to file %s...' % filename) mesh = gen_block_mesh(args[1::2], args[0::2], (0.0, 0.0, 0.0), name=filename) mesh.write(filename, io='auto') output('...done') else: import subprocess, shutil, tempfile filename = filename + '.mesh'
ensure_path(filename)
sfepy.base.ioutils.ensure_path
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None output('repeating %s ...' % grid) nblk = 1 for ii, gr in enumerate(grid): if ret_ndmap: (conn, coors, ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps, ndmap=ndmap) ndmap = ndmap0 else: conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps) nblk *= gr output('...done') mat_ids = nm.tile(mat_ids, (nrep,)) mesh_out = Mesh.from_data('tiled mesh', coors * scale, ngrps, [conn], [mat_ids], [mesh.descs[0]]) if ret_ndmap: return mesh_out, ndmap else: return mesh_out def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ import os from sfepy import data_dir defdir = os.path.join(data_dir, 'meshes') if mesh_dir is None: mesh_dir = defdir def retype(args, types, defaults): args=list(args) args.extend(defaults[len(args):len(defaults)]) return tuple([type(value) for type, value in zip(types, args) ]) if kind == 'sphere': default = [5, 41, args[0]] args = retype(args, [float, int, float], default) mesh_pattern = os.path.join(mesh_dir, 'sphere-%.2f-%.2f-%i') else: assert_(kind == 'cube') args = retype(args, (int, float, int, float, int, float), (args[0], args[1], args[0], args[1], args[0], args[1])) mesh_pattern = os.path.join(mesh_dir, 'cube-%i_%.2f-%i_%.2f-%i_%.2f') if verbose: output(args) filename = mesh_pattern % args if not force_create: if os.path.exists(filename): return filename if os.path.exists(filename + '.mesh') : return filename + '.mesh' if os.path.exists(filename + '.vtk'): return filename + '.vtk' if kind == 'cube': filename = filename + suffix ensure_path(filename) output('creating new cube mesh') output('(%i nodes in %.2f) x (%i nodes in %.2f) x (%i nodes in %.2f)' % args) output('to file %s...' % filename) mesh = gen_block_mesh(args[1::2], args[0::2], (0.0, 0.0, 0.0), name=filename) mesh.write(filename, io='auto') output('...done') else: import subprocess, shutil, tempfile filename = filename + '.mesh' ensure_path(filename) output('creating new sphere mesh (%i nodes, r=%.2f) and gradation %d' % args)
output('to file %s...' % filename)
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None output('repeating %s ...' % grid) nblk = 1 for ii, gr in enumerate(grid): if ret_ndmap: (conn, coors, ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps, ndmap=ndmap) ndmap = ndmap0 else: conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps) nblk *= gr output('...done') mat_ids = nm.tile(mat_ids, (nrep,)) mesh_out = Mesh.from_data('tiled mesh', coors * scale, ngrps, [conn], [mat_ids], [mesh.descs[0]]) if ret_ndmap: return mesh_out, ndmap else: return mesh_out def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ import os from sfepy import data_dir defdir = os.path.join(data_dir, 'meshes') if mesh_dir is None: mesh_dir = defdir def retype(args, types, defaults): args=list(args) args.extend(defaults[len(args):len(defaults)]) return tuple([type(value) for type, value in zip(types, args) ]) if kind == 'sphere': default = [5, 41, args[0]] args = retype(args, [float, int, float], default) mesh_pattern = os.path.join(mesh_dir, 'sphere-%.2f-%.2f-%i') else: assert_(kind == 'cube') args = retype(args, (int, float, int, float, int, float), (args[0], args[1], args[0], args[1], args[0], args[1])) mesh_pattern = os.path.join(mesh_dir, 'cube-%i_%.2f-%i_%.2f-%i_%.2f') if verbose: output(args) filename = mesh_pattern % args if not force_create: if os.path.exists(filename): return filename if os.path.exists(filename + '.mesh') : return filename + '.mesh' if os.path.exists(filename + '.vtk'): return filename + '.vtk' if kind == 'cube': filename = filename + suffix ensure_path(filename) output('creating new cube mesh') output('(%i nodes in %.2f) x (%i nodes in %.2f) x (%i nodes in %.2f)' % args) output('to file %s...' % filename) mesh = gen_block_mesh(args[1::2], args[0::2], (0.0, 0.0, 0.0), name=filename) mesh.write(filename, io='auto') output('...done') else: import subprocess, shutil, tempfile filename = filename + '.mesh' ensure_path(filename) output('creating new sphere mesh (%i nodes, r=%.2f) and gradation %d' % args) output('to file %s...' % filename) f = open(os.path.join(defdir, 'quantum', 'sphere.geo')) tmp_dir = tempfile.mkdtemp() tmpfile = os.path.join(tmp_dir, 'sphere.geo.temp') ff = open(tmpfile, "w") ff.write(""" R = %i.0; n = %i.0; dens = %f; """ % args) ff.write(f.read()) f.close() ff.close() subprocess.call(['gmsh', '-3', tmpfile, '-format', 'mesh', '-o', filename]) shutil.rmtree(tmp_dir)
output('...done')
sfepy.base.base.output
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None output('repeating %s ...' % grid) nblk = 1 for ii, gr in enumerate(grid): if ret_ndmap: (conn, coors, ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps, ndmap=ndmap) ndmap = ndmap0 else: conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps) nblk *= gr output('...done') mat_ids = nm.tile(mat_ids, (nrep,)) mesh_out = Mesh.from_data('tiled mesh', coors * scale, ngrps, [conn], [mat_ids], [mesh.descs[0]]) if ret_ndmap: return mesh_out, ndmap else: return mesh_out def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ import os from sfepy import data_dir defdir = os.path.join(data_dir, 'meshes') if mesh_dir is None: mesh_dir = defdir def retype(args, types, defaults): args=list(args) args.extend(defaults[len(args):len(defaults)]) return tuple([type(value) for type, value in zip(types, args) ]) if kind == 'sphere': default = [5, 41, args[0]] args = retype(args, [float, int, float], default) mesh_pattern = os.path.join(mesh_dir, 'sphere-%.2f-%.2f-%i') else: assert_(kind == 'cube') args = retype(args, (int, float, int, float, int, float), (args[0], args[1], args[0], args[1], args[0], args[1])) mesh_pattern = os.path.join(mesh_dir, 'cube-%i_%.2f-%i_%.2f-%i_%.2f') if verbose: output(args) filename = mesh_pattern % args if not force_create: if os.path.exists(filename): return filename if os.path.exists(filename + '.mesh') : return filename + '.mesh' if os.path.exists(filename + '.vtk'): return filename + '.vtk' if kind == 'cube': filename = filename + suffix ensure_path(filename) output('creating new cube mesh') output('(%i nodes in %.2f) x (%i nodes in %.2f) x (%i nodes in %.2f)' % args) output('to file %s...' % filename) mesh = gen_block_mesh(args[1::2], args[0::2], (0.0, 0.0, 0.0), name=filename) mesh.write(filename, io='auto') output('...done') else: import subprocess, shutil, tempfile filename = filename + '.mesh' ensure_path(filename) output('creating new sphere mesh (%i nodes, r=%.2f) and gradation %d' % args) output('to file %s...' % filename) f = open(os.path.join(defdir, 'quantum', 'sphere.geo')) tmp_dir = tempfile.mkdtemp() tmpfile = os.path.join(tmp_dir, 'sphere.geo.temp') ff = open(tmpfile, "w") ff.write(""" R = %i.0; n = %i.0; dens = %f; """ % args) ff.write(f.read()) f.close() ff.close() subprocess.call(['gmsh', '-3', tmpfile, '-format', 'mesh', '-o', filename]) shutil.rmtree(tmp_dir) output('...done') return filename def gen_mesh_from_string(mesh_name, mesh_dir): import re result = re.match('^\\s*([a-zA-Z]+)[:\\(]([^\\):]*)[:\\)](\\*)?\\s*$', mesh_name) if result is None: return mesh_name else: args = re.split(',', result.group(2)) kind = result.group(1) return gen_misc_mesh(mesh_dir, result.group(3)=='*', kind, args) def gen_mesh_from_geom(geo, a=None, verbose=False, refine=False): """ Runs mesh generator - tetgen for 3D or triangle for 2D meshes. Parameters ---------- geo : geometry geometry description a : int, optional a maximum area/volume constraint verbose : bool, optional detailed information refine : bool, optional refines mesh Returns ------- mesh : Mesh instance triangular or tetrahedral mesh """ import os.path as op import pexpect import tempfile import shutil tmp_dir = tempfile.mkdtemp() polyfilename = op.join(tmp_dir, 'meshgen.poly') # write geometry to poly file geo.to_poly_file(polyfilename) meshgen_call = {2: ('triangle', ''), 3: ('tetgen', 'BFENk')} params = "-ACp" params += "q" if refine else '' params += "V" if verbose else "Q" params += meshgen_call[geo.dim][1] if a is not None: params += "a%f" % (a) params += " %s" % (polyfilename) cmd = "%s %s" % (meshgen_call[geo.dim][0], params) if verbose: print("Generating mesh using", cmd) p=pexpect.run(cmd, timeout=None) bname, ext = op.splitext(polyfilename) if geo.dim == 2: mesh =
Mesh.from_file(bname + '.1.node')
sfepy.discrete.fem.mesh.Mesh.from_file
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None output('repeating %s ...' % grid) nblk = 1 for ii, gr in enumerate(grid): if ret_ndmap: (conn, coors, ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps, ndmap=ndmap) ndmap = ndmap0 else: conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps) nblk *= gr output('...done') mat_ids = nm.tile(mat_ids, (nrep,)) mesh_out = Mesh.from_data('tiled mesh', coors * scale, ngrps, [conn], [mat_ids], [mesh.descs[0]]) if ret_ndmap: return mesh_out, ndmap else: return mesh_out def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ import os from sfepy import data_dir defdir = os.path.join(data_dir, 'meshes') if mesh_dir is None: mesh_dir = defdir def retype(args, types, defaults): args=list(args) args.extend(defaults[len(args):len(defaults)]) return tuple([type(value) for type, value in zip(types, args) ]) if kind == 'sphere': default = [5, 41, args[0]] args = retype(args, [float, int, float], default) mesh_pattern = os.path.join(mesh_dir, 'sphere-%.2f-%.2f-%i') else: assert_(kind == 'cube') args = retype(args, (int, float, int, float, int, float), (args[0], args[1], args[0], args[1], args[0], args[1])) mesh_pattern = os.path.join(mesh_dir, 'cube-%i_%.2f-%i_%.2f-%i_%.2f') if verbose: output(args) filename = mesh_pattern % args if not force_create: if os.path.exists(filename): return filename if os.path.exists(filename + '.mesh') : return filename + '.mesh' if os.path.exists(filename + '.vtk'): return filename + '.vtk' if kind == 'cube': filename = filename + suffix ensure_path(filename) output('creating new cube mesh') output('(%i nodes in %.2f) x (%i nodes in %.2f) x (%i nodes in %.2f)' % args) output('to file %s...' % filename) mesh = gen_block_mesh(args[1::2], args[0::2], (0.0, 0.0, 0.0), name=filename) mesh.write(filename, io='auto') output('...done') else: import subprocess, shutil, tempfile filename = filename + '.mesh' ensure_path(filename) output('creating new sphere mesh (%i nodes, r=%.2f) and gradation %d' % args) output('to file %s...' % filename) f = open(os.path.join(defdir, 'quantum', 'sphere.geo')) tmp_dir = tempfile.mkdtemp() tmpfile = os.path.join(tmp_dir, 'sphere.geo.temp') ff = open(tmpfile, "w") ff.write(""" R = %i.0; n = %i.0; dens = %f; """ % args) ff.write(f.read()) f.close() ff.close() subprocess.call(['gmsh', '-3', tmpfile, '-format', 'mesh', '-o', filename]) shutil.rmtree(tmp_dir) output('...done') return filename def gen_mesh_from_string(mesh_name, mesh_dir): import re result = re.match('^\\s*([a-zA-Z]+)[:\\(]([^\\):]*)[:\\)](\\*)?\\s*$', mesh_name) if result is None: return mesh_name else: args = re.split(',', result.group(2)) kind = result.group(1) return gen_misc_mesh(mesh_dir, result.group(3)=='*', kind, args) def gen_mesh_from_geom(geo, a=None, verbose=False, refine=False): """ Runs mesh generator - tetgen for 3D or triangle for 2D meshes. Parameters ---------- geo : geometry geometry description a : int, optional a maximum area/volume constraint verbose : bool, optional detailed information refine : bool, optional refines mesh Returns ------- mesh : Mesh instance triangular or tetrahedral mesh """ import os.path as op import pexpect import tempfile import shutil tmp_dir = tempfile.mkdtemp() polyfilename = op.join(tmp_dir, 'meshgen.poly') # write geometry to poly file geo.to_poly_file(polyfilename) meshgen_call = {2: ('triangle', ''), 3: ('tetgen', 'BFENk')} params = "-ACp" params += "q" if refine else '' params += "V" if verbose else "Q" params += meshgen_call[geo.dim][1] if a is not None: params += "a%f" % (a) params += " %s" % (polyfilename) cmd = "%s %s" % (meshgen_call[geo.dim][0], params) if verbose: print("Generating mesh using", cmd) p=pexpect.run(cmd, timeout=None) bname, ext = op.splitext(polyfilename) if geo.dim == 2: mesh = Mesh.from_file(bname + '.1.node') if geo.dim == 3: mesh =
Mesh.from_file(bname + '.1.vtk')
sfepy.discrete.fem.mesh.Mesh.from_file
from __future__ import print_function from __future__ import absolute_import import numpy as nm import sys from six.moves import range sys.path.append('.') from sfepy.base.base import output, assert_ from sfepy.base.ioutils import ensure_path from sfepy.linalg import cycle from sfepy.discrete.fem.mesh import Mesh from sfepy.mesh.mesh_tools import elems_q2t def get_tensor_product_conn(shape): """ Generate vertex connectivity for cells of a tensor-product mesh of the given shape. Parameters ---------- shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the mesh. Returns ------- conn : array The vertex connectivity array. desc : str The cell kind. """ shape = nm.asarray(shape) dim = len(shape) assert_(1 <= dim <= 3) n_nod = nm.prod(shape) n_el = nm.prod(shape - 1) grid = nm.arange(n_nod, dtype=nm.int32) grid.shape = shape if dim == 1: conn = nm.zeros((n_el, 2), dtype=nm.int32) conn[:, 0] = grid[:-1] conn[:, 1] = grid[1:] desc = '1_2' elif dim == 2: conn = nm.zeros((n_el, 4), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1].flat conn[:, 1] = grid[1:, :-1].flat conn[:, 2] = grid[1:, 1:].flat conn[:, 3] = grid[:-1, 1:].flat desc = '2_4' else: conn = nm.zeros((n_el, 8), dtype=nm.int32) conn[:, 0] = grid[:-1, :-1, :-1].flat conn[:, 1] = grid[1:, :-1, :-1].flat conn[:, 2] = grid[1:, 1:, :-1].flat conn[:, 3] = grid[:-1, 1:, :-1].flat conn[:, 4] = grid[:-1, :-1, 1:].flat conn[:, 5] = grid[1:, :-1, 1:].flat conn[:, 6] = grid[1:, 1:, 1:].flat conn[:, 7] = grid[:-1, 1:, 1:].flat desc = '3_8' return conn, desc def gen_block_mesh(dims, shape, centre, mat_id=0, name='block', coors=None, verbose=True): """ Generate a 2D or 3D block mesh. The dimension is determined by the lenght of the shape argument. Parameters ---------- dims : array of 2 or 3 floats Dimensions of the block. shape : array of 2 or 3 ints Shape (counts of nodes in x, y, z) of the block mesh. centre : array of 2 or 3 floats Centre of the block. mat_id : int, optional The material id of all elements. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) dim = shape.shape[0] centre = centre[:dim] dims = dims[:dim] n_nod = nm.prod(shape) output('generating %d vertices...' % n_nod, verbose=verbose) x0 = centre - 0.5 * dims dd = dims / (shape - 1) ngrid = nm.mgrid[[slice(ii) for ii in shape]] ngrid.shape = (dim, n_nod) coors = x0 + ngrid.T * dd output('...done', verbose=verbose) n_el = nm.prod(shape - 1) output('generating %d cells...' % n_el, verbose=verbose) mat_ids = nm.empty((n_el,), dtype=nm.int32) mat_ids.fill(mat_id) conn, desc = get_tensor_product_conn(shape) output('...done', verbose=verbose) mesh = Mesh.from_data(name, coors, None, [conn], [mat_ids], [desc]) return mesh def gen_cylinder_mesh(dims, shape, centre, axis='x', force_hollow=False, is_open=False, open_angle=0.0, non_uniform=False, name='cylinder', verbose=True): """ Generate a cylindrical mesh along an axis. Its cross-section can be ellipsoidal. Parameters ---------- dims : array of 5 floats Dimensions of the cylinder: inner surface semi-axes a1, b1, outer surface semi-axes a2, b2, length. shape : array of 3 ints Shape (counts of nodes in radial, circumferential and longitudinal directions) of the cylinder mesh. centre : array of 3 floats Centre of the cylinder. axis: one of 'x', 'y', 'z' The axis of the cylinder. force_hollow : boolean Force hollow mesh even if inner radii a1 = b1 = 0. is_open : boolean Generate an open cylinder segment. open_angle : float Opening angle in radians. non_uniform : boolean If True, space the mesh nodes in radial direction so that the element volumes are (approximately) the same, making thus the elements towards the outer surface thinner. name : string Mesh name. verbose : bool If True, show progress of the mesh generation. Returns ------- mesh : Mesh instance """ dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) a1, b1, a2, b2, length = dims nr, nfi, nl = shape origin = centre - nm.array([0.5 * length, 0.0, 0.0]) dfi = 2.0 * (nm.pi - open_angle) / nfi if is_open: nnfi = nfi + 1 else: nnfi = nfi is_hollow = force_hollow or not (max(abs(a1), abs(b1)) < 1e-15) if is_hollow: mr = 0 else: mr = (nnfi - 1) * nl grid = nm.zeros((nr, nnfi, nl), dtype=nm.int32) n_nod = nr * nnfi * nl - mr coors = nm.zeros((n_nod, 3), dtype=nm.float64) angles = nm.linspace(open_angle, open_angle+(nfi)*dfi, nfi+1) xs = nm.linspace(0.0, length, nl) if non_uniform: ras = nm.zeros((nr,), dtype=nm.float64) rbs = nm.zeros_like(ras) advol = (a2**2 - a1**2) / (nr - 1) bdvol = (b2**2 - b1**2) / (nr - 1) ras[0], rbs[0] = a1, b1 for ii in range(1, nr): ras[ii] = nm.sqrt(advol + ras[ii-1]**2) rbs[ii] = nm.sqrt(bdvol + rbs[ii-1]**2) else: ras = nm.linspace(a1, a2, nr) rbs = nm.linspace(b1, b2, nr) # This is 3D only... output('generating %d vertices...' % n_nod, verbose=verbose) ii = 0 for ix in range(nr): a, b = ras[ix], rbs[ix] for iy, fi in enumerate(angles[:nnfi]): for iz, x in enumerate(xs): grid[ix,iy,iz] = ii coors[ii] = origin + [x, a * nm.cos(fi), b * nm.sin(fi)] ii += 1 if not is_hollow and (ix == 0): if iy > 0: grid[ix,iy,iz] = grid[ix,0,iz] ii -= 1 assert_(ii == n_nod) output('...done', verbose=verbose) n_el = (nr - 1) * nfi * (nl - 1) conn = nm.zeros((n_el, 8), dtype=nm.int32) output('generating %d cells...' % n_el, verbose=verbose) ii = 0 for (ix, iy, iz) in cycle([nr-1, nnfi, nl-1]): if iy < (nnfi - 1): conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,iy+1,iz ], grid[ix ,iy+1,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,iy+1,iz+1], grid[ix ,iy+1,iz+1]] ii += 1 elif not is_open: conn[ii,:] = [grid[ix ,iy ,iz ], grid[ix+1,iy ,iz ], grid[ix+1,0,iz ], grid[ix ,0,iz ], grid[ix ,iy ,iz+1], grid[ix+1,iy ,iz+1], grid[ix+1,0,iz+1], grid[ix ,0,iz+1]] ii += 1 mat_id = nm.zeros((n_el,), dtype = nm.int32) desc = '3_8' assert_(n_nod == (conn.max() + 1)) output('...done', verbose=verbose) if axis == 'z': coors = coors[:,[1,2,0]] elif axis == 'y': coors = coors[:,[2,0,1]] mesh = Mesh.from_data(name, coors, None, [conn], [mat_id], [desc]) return mesh def _spread_along_axis(axis, coors, tangents, grading_fun): """ Spread the coordinates along the given axis using the grading function, and the tangents in the other two directions. """ oo = list(set([0, 1, 2]).difference([axis])) c0, c1, c2 = coors[:, axis], coors[:, oo[0]], coors[:, oo[1]] out = nm.empty_like(coors) mi, ma = c0.min(), c0.max() nc0 = (c0 - mi) / (ma - mi) out[:, axis] = oc0 = grading_fun(nc0) * (ma - mi) + mi nc = oc0 - oc0.min() mi, ma = c1.min(), c1.max() n1 = 2 * (c1 - mi) / (ma - mi) - 1 out[:, oo[0]] = c1 + n1 * nc * tangents[oo[0]] mi, ma = c2.min(), c2.max() n2 = 2 * (c2 - mi) / (ma - mi) - 1 out[:, oo[1]] = c2 + n2 * nc * tangents[oo[1]] return out def _get_extension_side(side, grading_fun, mat_id, b_dims, b_shape, e_dims, e_shape, centre): """ Get a mesh extending the given side of a block mesh. """ # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) coff = 0.5 * (b_dims + pe_dims) cc = centre + coff * nm.eye(3)[side] if side == 0: # x axis. dims = [pe_dims[0], b_dims[1], b_dims[2]] shape = [e_shape, b_shape[1], b_shape[2]] tangents = [0, pe_dims[1] / pe_dims[0], pe_dims[2] / pe_dims[0]] elif side == 1: # y axis. dims = [b_dims[0], pe_dims[1], b_dims[2]] shape = [b_shape[0], e_shape, b_shape[2]] tangents = [pe_dims[0] / pe_dims[1], 0, pe_dims[2] / pe_dims[1]] elif side == 2: # z axis. dims = [b_dims[0], b_dims[1], pe_dims[2]] shape = [b_shape[0], b_shape[1], e_shape] tangents = [pe_dims[0] / pe_dims[2], pe_dims[1] / pe_dims[2], 0] e_mesh = gen_block_mesh(dims, shape, cc, mat_id=mat_id, verbose=False) e_mesh.coors[:] = _spread_along_axis(side, e_mesh.coors, tangents, grading_fun) return e_mesh, shape def gen_extended_block_mesh(b_dims, b_shape, e_dims, e_shape, centre, grading_fun=None, name=None): """ Generate a 3D mesh with a central block and (coarse) extending side meshes. The resulting mesh is again a block. Each of the components has a different material id. Parameters ---------- b_dims : array of 3 floats The dimensions of the central block. b_shape : array of 3 ints The shape (counts of nodes in x, y, z) of the central block mesh. e_dims : array of 3 floats The dimensions of the complete block (central block + extensions). e_shape : int The count of nodes of extending blocks in the direction from the central block. centre : array of 3 floats The centre of the mesh. grading_fun : callable, optional A function of :math:`x \in [0, 1]` that can be used to shift nodes in the extension axis directions to allow smooth grading of element sizes from the centre. The default function is :math:`x**p` with :math:`p` determined so that the element sizes next to the central block have the size of the shortest edge of the central block. name : string, optional The mesh name. Returns ------- mesh : Mesh instance """ b_dims = nm.asarray(b_dims, dtype=nm.float64) b_shape = nm.asarray(b_shape, dtype=nm.int32) e_dims = nm.asarray(e_dims, dtype=nm.float64) centre = nm.asarray(centre, dtype=nm.float64) # Pure extension dimensions. pe_dims = 0.5 * (e_dims - b_dims) # Central block element sizes. dd = (b_dims / (b_shape - 1)) # The "first x" going to grading_fun. nc = 1.0 / (e_shape - 1) # Grading power and function. power = nm.log(dd.min() / pe_dims.min()) / nm.log(nc) grading_fun = (lambda x: x**power) if grading_fun is None else grading_fun # Central block mesh. b_mesh = gen_block_mesh(b_dims, b_shape, centre, mat_id=0, verbose=False) # 'x' extension. e_mesh, xs = _get_extension_side(0, grading_fun, 10, b_dims, b_shape, e_dims, e_shape, centre) mesh = b_mesh + e_mesh # Mirror by 'x'. e_mesh.coors[:, 0] = (2 * centre[0]) - e_mesh.coors[:, 0] e_mesh.cmesh.cell_groups.fill(11) mesh = mesh + e_mesh # 'y' extension. e_mesh, ys = _get_extension_side(1, grading_fun, 20, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'y'. e_mesh.coors[:, 1] = (2 * centre[1]) - e_mesh.coors[:, 1] e_mesh.cmesh.cell_groups.fill(21) mesh = mesh + e_mesh # 'z' extension. e_mesh, zs = _get_extension_side(2, grading_fun, 30, b_dims, b_shape, e_dims, e_shape, centre) mesh = mesh + e_mesh # Mirror by 'z'. e_mesh.coors[:, 2] = (2 * centre[2]) - e_mesh.coors[:, 2] e_mesh.cmesh.cell_groups.fill(31) mesh = mesh + e_mesh if name is not None: mesh.name = name # Verify merging by checking the number of nodes. n_nod = (nm.prod(nm.maximum(b_shape - 2, 0)) + 2 * nm.prod(xs) + 2 * (max(ys[0] - 2, 0) * ys[1] * ys[2]) + 2 * (max(zs[0] - 2, 0) * max(zs[1] - 2, 0) * zs[2])) if n_nod != mesh.n_nod: raise ValueError('Merge of meshes failed! (%d == %d)' % (n_nod, mesh.n_nod)) return mesh def tiled_mesh1d(conn, coors, ngrps, idim, n_rep, bb, eps=1e-6, ndmap=False): from sfepy.discrete.fem.periodic import match_grid_plane s1 = nm.nonzero(coors[:,idim] < (bb[0] + eps))[0] s2 = nm.nonzero(coors[:,idim] > (bb[1] - eps))[0] if s1.shape != s2.shape: raise ValueError('incompatible shapes: %s == %s'\ % (s1.shape, s2.shape)) (nnod0, dim) = coors.shape nnod = nnod0 * n_rep - s1.shape[0] * (n_rep - 1) (nel0, nnel) = conn.shape nel = nel0 * n_rep dd = nm.zeros((dim,), dtype=nm.float64) dd[idim] = bb[1] - bb[0] m1, m2 = match_grid_plane(coors[s1], coors[s2], idim) oconn = nm.zeros((nel, nnel), dtype=nm.int32) ocoors = nm.zeros((nnod, dim), dtype=nm.float64) ongrps = nm.zeros((nnod,), dtype=nm.int32) if type(ndmap) is bool: ret_ndmap = ndmap else: ret_ndmap= True ndmap_out = nm.zeros((nnod,), dtype=nm.int32) el_off = 0 nd_off = 0 for ii in range(n_rep): if ii == 0: oconn[0:nel0,:] = conn ocoors[0:nnod0,:] = coors ongrps[0:nnod0] = ngrps.squeeze() nd_off += nnod0 mapto = s2[m2] mask = nm.ones((nnod0,), dtype=nm.int32) mask[s1] = 0 remap0 = nm.cumsum(mask) - 1 nnod0r = nnod0 - s1.shape[0] cidx = nm.where(mask) if ret_ndmap: ndmap_out[0:nnod0] = nm.arange(nnod0) else: remap = remap0 + nd_off remap[s1[m1]] = mapto mapto = remap[s2[m2]] ocoors[nd_off:(nd_off + nnod0r),:] =\ (coors[cidx,:] + ii * dd) ongrps[nd_off:(nd_off + nnod0r)] = ngrps[cidx].squeeze() oconn[el_off:(el_off + nel0),:] = remap[conn] if ret_ndmap: ndmap_out[nd_off:(nd_off + nnod0r)] = cidx[0] nd_off += nnod0r el_off += nel0 if ret_ndmap: if ndmap is not None: max_nd_ref = nm.max(ndmap) idxs = nm.where(ndmap_out > max_nd_ref) ndmap_out[idxs] = ndmap[ndmap_out[idxs]] return oconn, ocoors, ongrps, ndmap_out else: return oconn, ocoors, ongrps def gen_tiled_mesh(mesh, grid=None, scale=1.0, eps=1e-6, ret_ndmap=False): """ Generate a new mesh by repeating a given periodic element along each axis. Parameters ---------- mesh : Mesh instance The input periodic FE mesh. grid : array Number of repetition along each axis. scale : float, optional Scaling factor. eps : float, optional Tolerance for boundary detection. ret_ndmap : bool, optional If True, return global node map. Returns ------- mesh_out : Mesh instance FE mesh. ndmap : array Maps: actual node id --> node id in the reference cell. """ bbox = mesh.get_bounding_box() if grid is None: iscale = max(int(1.0 / scale), 1) grid = [iscale] * mesh.dim conn = mesh.get_conn(mesh.descs[0]) mat_ids = mesh.cmesh.cell_groups coors = mesh.coors ngrps = mesh.cmesh.vertex_groups nrep = nm.prod(grid) ndmap = None output('repeating %s ...' % grid) nblk = 1 for ii, gr in enumerate(grid): if ret_ndmap: (conn, coors, ngrps, ndmap0) = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps, ndmap=ndmap) ndmap = ndmap0 else: conn, coors, ngrps = tiled_mesh1d(conn, coors, ngrps, ii, gr, bbox.transpose()[ii], eps=eps) nblk *= gr output('...done') mat_ids = nm.tile(mat_ids, (nrep,)) mesh_out = Mesh.from_data('tiled mesh', coors * scale, ngrps, [conn], [mat_ids], [mesh.descs[0]]) if ret_ndmap: return mesh_out, ndmap else: return mesh_out def gen_misc_mesh(mesh_dir, force_create, kind, args, suffix='.mesh', verbose=False): """ Create sphere or cube mesh according to `kind` in the given directory if it does not exist and return path to it. """ import os from sfepy import data_dir defdir = os.path.join(data_dir, 'meshes') if mesh_dir is None: mesh_dir = defdir def retype(args, types, defaults): args=list(args) args.extend(defaults[len(args):len(defaults)]) return tuple([type(value) for type, value in zip(types, args) ]) if kind == 'sphere': default = [5, 41, args[0]] args = retype(args, [float, int, float], default) mesh_pattern = os.path.join(mesh_dir, 'sphere-%.2f-%.2f-%i') else: assert_(kind == 'cube') args = retype(args, (int, float, int, float, int, float), (args[0], args[1], args[0], args[1], args[0], args[1])) mesh_pattern = os.path.join(mesh_dir, 'cube-%i_%.2f-%i_%.2f-%i_%.2f') if verbose: output(args) filename = mesh_pattern % args if not force_create: if os.path.exists(filename): return filename if os.path.exists(filename + '.mesh') : return filename + '.mesh' if os.path.exists(filename + '.vtk'): return filename + '.vtk' if kind == 'cube': filename = filename + suffix ensure_path(filename) output('creating new cube mesh') output('(%i nodes in %.2f) x (%i nodes in %.2f) x (%i nodes in %.2f)' % args) output('to file %s...' % filename) mesh = gen_block_mesh(args[1::2], args[0::2], (0.0, 0.0, 0.0), name=filename) mesh.write(filename, io='auto') output('...done') else: import subprocess, shutil, tempfile filename = filename + '.mesh' ensure_path(filename) output('creating new sphere mesh (%i nodes, r=%.2f) and gradation %d' % args) output('to file %s...' % filename) f = open(os.path.join(defdir, 'quantum', 'sphere.geo')) tmp_dir = tempfile.mkdtemp() tmpfile = os.path.join(tmp_dir, 'sphere.geo.temp') ff = open(tmpfile, "w") ff.write(""" R = %i.0; n = %i.0; dens = %f; """ % args) ff.write(f.read()) f.close() ff.close() subprocess.call(['gmsh', '-3', tmpfile, '-format', 'mesh', '-o', filename]) shutil.rmtree(tmp_dir) output('...done') return filename def gen_mesh_from_string(mesh_name, mesh_dir): import re result = re.match('^\\s*([a-zA-Z]+)[:\\(]([^\\):]*)[:\\)](\\*)?\\s*$', mesh_name) if result is None: return mesh_name else: args = re.split(',', result.group(2)) kind = result.group(1) return gen_misc_mesh(mesh_dir, result.group(3)=='*', kind, args) def gen_mesh_from_geom(geo, a=None, verbose=False, refine=False): """ Runs mesh generator - tetgen for 3D or triangle for 2D meshes. Parameters ---------- geo : geometry geometry description a : int, optional a maximum area/volume constraint verbose : bool, optional detailed information refine : bool, optional refines mesh Returns ------- mesh : Mesh instance triangular or tetrahedral mesh """ import os.path as op import pexpect import tempfile import shutil tmp_dir = tempfile.mkdtemp() polyfilename = op.join(tmp_dir, 'meshgen.poly') # write geometry to poly file geo.to_poly_file(polyfilename) meshgen_call = {2: ('triangle', ''), 3: ('tetgen', 'BFENk')} params = "-ACp" params += "q" if refine else '' params += "V" if verbose else "Q" params += meshgen_call[geo.dim][1] if a is not None: params += "a%f" % (a) params += " %s" % (polyfilename) cmd = "%s %s" % (meshgen_call[geo.dim][0], params) if verbose: print("Generating mesh using", cmd) p=pexpect.run(cmd, timeout=None) bname, ext = op.splitext(polyfilename) if geo.dim == 2: mesh = Mesh.from_file(bname + '.1.node') if geo.dim == 3: mesh = Mesh.from_file(bname + '.1.vtk') shutil.rmtree(tmp_dir) return mesh def gen_mesh_from_voxels(voxels, dims, etype='q'): """ Generate FE mesh from voxels (volumetric data). Parameters ---------- voxels : array Voxel matrix, 1=material. dims : array Size of one voxel. etype : integer, optional 'q' - quadrilateral or hexahedral elements 't' - triangular or tetrahedral elements Returns ------- mesh : Mesh instance Finite element mesh. """ dims = nm.array(dims).squeeze() dim = len(dims) nddims = nm.array(voxels.shape) + 2 nodemtx = nm.zeros(nddims, dtype=nm.int32) if dim == 2: #iy, ix = nm.where(voxels.transpose()) iy, ix = nm.where(voxels) nel = ix.shape[0] if etype == 'q': nodemtx[ix,iy] += 1 nodemtx[ix + 1,iy] += 1 nodemtx[ix + 1,iy + 1] += 1 nodemtx[ix,iy + 1] += 1 elif etype == 't': nodemtx[ix,iy] += 2 nodemtx[ix + 1,iy] += 1 nodemtx[ix + 1,iy + 1] += 2 nodemtx[ix,iy + 1] += 1 nel *= 2 elif dim == 3: #iy, ix, iz = nm.where(voxels.transpose(1, 0, 2)) iy, ix, iz = nm.where(voxels) nel = ix.shape[0] if etype == 'q': nodemtx[ix,iy,iz] += 1 nodemtx[ix + 1,iy,iz] += 1 nodemtx[ix + 1,iy + 1,iz] += 1 nodemtx[ix,iy + 1,iz] += 1 nodemtx[ix,iy,iz + 1] += 1 nodemtx[ix + 1,iy,iz + 1] += 1 nodemtx[ix + 1,iy + 1,iz + 1] += 1 nodemtx[ix,iy + 1,iz + 1] += 1 elif etype == 't': nodemtx[ix,iy,iz] += 6 nodemtx[ix + 1,iy,iz] += 2 nodemtx[ix + 1,iy + 1,iz] += 2 nodemtx[ix,iy + 1,iz] += 2 nodemtx[ix,iy,iz + 1] += 2 nodemtx[ix + 1,iy,iz + 1] += 2 nodemtx[ix + 1,iy + 1,iz + 1] += 6 nodemtx[ix,iy + 1,iz + 1] += 2 nel *= 6 else: msg = 'incorrect voxel dimension! (%d)' % dim raise ValueError(msg) ndidx = nm.where(nodemtx) coors = nm.array(ndidx).transpose() * dims nnod = coors.shape[0] nodeid = -nm.ones(nddims, dtype=nm.int32) nodeid[ndidx] = nm.arange(nnod) # generate elements if dim == 2: elems = nm.array([nodeid[ix,iy], nodeid[ix + 1,iy], nodeid[ix + 1,iy + 1], nodeid[ix,iy + 1]]).transpose() elif dim == 3: elems = nm.array([nodeid[ix,iy,iz], nodeid[ix + 1,iy,iz], nodeid[ix + 1,iy + 1,iz], nodeid[ix,iy + 1,iz], nodeid[ix,iy,iz + 1], nodeid[ix + 1,iy,iz + 1], nodeid[ix + 1,iy + 1,iz + 1], nodeid[ix,iy + 1,iz + 1]]).transpose() if etype == 't': elems =
elems_q2t(elems)
sfepy.mesh.mesh_tools.elems_q2t
# 30.05.2007, c # last revision: 25.02.2008 from __future__ import absolute_import from sfepy import data_dir import six filename_mesh = data_dir + '/meshes/2d/square_unit_tri.mesh' material_1 = { 'name' : 'coef', 'values' : { 'val' : 1.0, }, } material_2 = { 'name' : 'm', 'values' : { 'K' : [[1.0, 0.0], [0.0, 1.0]], }, } field_1 = { 'name' : 'a_harmonic_field', 'dtype' : 'real', 'shape' : 'scalar', 'region' : 'Omega', 'approx_order' : 2, } variable_1 = { 'name' : 't', 'kind' : 'unknown field', 'field' : 'a_harmonic_field', 'order' : 0, } variable_2 = { 'name' : 's', 'kind' : 'test field', 'field' : 'a_harmonic_field', 'dual' : 't', } region_1000 = { 'name' : 'Omega', 'select' : 'all', } region_1 = { 'name' : 'Left', 'select' : 'vertices in (x < -0.499)', 'kind' : 'facet', } region_2 = { 'name' : 'Right', 'select' : 'vertices in (x > 0.499)', 'kind' : 'facet', } region_3 = { 'name' : 'Gamma', 'select' : 'vertices of surface', 'kind' : 'facet', } ebc_1 = { 'name' : 't_left', 'region' : 'Left', 'dofs' : {'t.0' : 5.0}, } ebc_2 = { 'name' : 't_right', 'region' : 'Right', 'dofs' : {'t.0' : 0.0}, } # 'Left' : ('T3', (30,), 'linear_y'), integral_1 = { 'name' : 'i', 'order' : 2, } equations = { 'Temperature' : """dw_laplace.i.Omega( coef.val, s, t ) = 0""" } solution = { 't' : '- 5.0 * (x - 0.5)', } solver_0 = { 'name' : 'ls', 'kind' : 'ls.scipy_direct', } solver_1 = { 'name' : 'newton', 'kind' : 'nls.newton', 'i_max' : 1, 'eps_a' : 1e-10, } lin_min, lin_max = 0.0, 2.0 ## # 31.05.2007, c def linear( bc, ts, coor, which ): vals = coor[:,which] min_val, max_val = vals.min(), vals.max() vals = (vals - min_val) / (max_val - min_val) * (lin_max - lin_min) + lin_min return vals ## # 31.05.2007, c def linear_x( bc, ts, coor ): return linear( bc, ts, coor, 0 ) def linear_y( bc, ts, coor ): return linear( bc, ts, coor, 1 ) def linear_z( bc, ts, coor ): return linear( bc, ts, coor, 2 ) from sfepy.base.testing import TestCommon ## # 30.05.2007, c class Test( TestCommon ): ## # 30.05.2007, c def from_conf( conf, options ): from sfepy.applications import solve_pde problem, state =
solve_pde(conf, save_results=False)
sfepy.applications.solve_pde
# 30.05.2007, c # last revision: 25.02.2008 from __future__ import absolute_import from sfepy import data_dir import six filename_mesh = data_dir + '/meshes/2d/square_unit_tri.mesh' material_1 = { 'name' : 'coef', 'values' : { 'val' : 1.0, }, } material_2 = { 'name' : 'm', 'values' : { 'K' : [[1.0, 0.0], [0.0, 1.0]], }, } field_1 = { 'name' : 'a_harmonic_field', 'dtype' : 'real', 'shape' : 'scalar', 'region' : 'Omega', 'approx_order' : 2, } variable_1 = { 'name' : 't', 'kind' : 'unknown field', 'field' : 'a_harmonic_field', 'order' : 0, } variable_2 = { 'name' : 's', 'kind' : 'test field', 'field' : 'a_harmonic_field', 'dual' : 't', } region_1000 = { 'name' : 'Omega', 'select' : 'all', } region_1 = { 'name' : 'Left', 'select' : 'vertices in (x < -0.499)', 'kind' : 'facet', } region_2 = { 'name' : 'Right', 'select' : 'vertices in (x > 0.499)', 'kind' : 'facet', } region_3 = { 'name' : 'Gamma', 'select' : 'vertices of surface', 'kind' : 'facet', } ebc_1 = { 'name' : 't_left', 'region' : 'Left', 'dofs' : {'t.0' : 5.0}, } ebc_2 = { 'name' : 't_right', 'region' : 'Right', 'dofs' : {'t.0' : 0.0}, } # 'Left' : ('T3', (30,), 'linear_y'), integral_1 = { 'name' : 'i', 'order' : 2, } equations = { 'Temperature' : """dw_laplace.i.Omega( coef.val, s, t ) = 0""" } solution = { 't' : '- 5.0 * (x - 0.5)', } solver_0 = { 'name' : 'ls', 'kind' : 'ls.scipy_direct', } solver_1 = { 'name' : 'newton', 'kind' : 'nls.newton', 'i_max' : 1, 'eps_a' : 1e-10, } lin_min, lin_max = 0.0, 2.0 ## # 31.05.2007, c def linear( bc, ts, coor, which ): vals = coor[:,which] min_val, max_val = vals.min(), vals.max() vals = (vals - min_val) / (max_val - min_val) * (lin_max - lin_min) + lin_min return vals ## # 31.05.2007, c def linear_x( bc, ts, coor ): return linear( bc, ts, coor, 0 ) def linear_y( bc, ts, coor ): return linear( bc, ts, coor, 1 ) def linear_z( bc, ts, coor ): return linear( bc, ts, coor, 2 ) from sfepy.base.testing import TestCommon ## # 30.05.2007, c class Test( TestCommon ): ## # 30.05.2007, c def from_conf( conf, options ): from sfepy.applications import solve_pde problem, state = solve_pde(conf, save_results=False) test = Test(problem=problem, state=state, conf=conf, options=options) return test from_conf = staticmethod( from_conf ) ## # 30.05.2007, c def test_solution( self ): sol = self.conf.solution vec = self.state() problem = self.problem variables = problem.get_variables() ok = True for var_name, expression in six.iteritems(sol): coor = variables[var_name].field.get_coor() ana_sol = self.eval_coor_expression( expression, coor ) num_sol = variables.get_state_part_view( vec, var_name ) ret = self.compare_vectors( ana_sol, num_sol, label1 = 'analytical %s' % var_name, label2 = 'numerical %s' % var_name ) if not ret: self.report( 'variable %s: failed' % var_name ) ok = ok and ret return ok ## # c: 30.05.2007, r: 19.02.2008 def test_boundary_fluxes( self ): import os.path as op from sfepy.linalg import rotation_matrix2d from sfepy.discrete.evaluate import BasicEvaluator from sfepy.discrete import Material problem = self.problem angles = [0, 30, 45] region_names = ['Left', 'Right', 'Gamma'] values = [5.0, -5.0, 0.0] variables = problem.get_variables() get_state = variables.get_state_part_view state = self.state.copy(deep=True) problem.time_update(ebcs={}, epbcs={}) # problem.save_ebc( 'aux.vtk' ) state.apply_ebc() ev = BasicEvaluator( problem ) aux = ev.eval_residual(state()) field = variables['t'].field conf_m = problem.conf.get_item_by_name('materials', 'm') m =
Material.from_conf(conf_m, problem.functions)
sfepy.discrete.Material.from_conf
# 30.05.2007, c # last revision: 25.02.2008 from __future__ import absolute_import from sfepy import data_dir import six filename_mesh = data_dir + '/meshes/2d/square_unit_tri.mesh' material_1 = { 'name' : 'coef', 'values' : { 'val' : 1.0, }, } material_2 = { 'name' : 'm', 'values' : { 'K' : [[1.0, 0.0], [0.0, 1.0]], }, } field_1 = { 'name' : 'a_harmonic_field', 'dtype' : 'real', 'shape' : 'scalar', 'region' : 'Omega', 'approx_order' : 2, } variable_1 = { 'name' : 't', 'kind' : 'unknown field', 'field' : 'a_harmonic_field', 'order' : 0, } variable_2 = { 'name' : 's', 'kind' : 'test field', 'field' : 'a_harmonic_field', 'dual' : 't', } region_1000 = { 'name' : 'Omega', 'select' : 'all', } region_1 = { 'name' : 'Left', 'select' : 'vertices in (x < -0.499)', 'kind' : 'facet', } region_2 = { 'name' : 'Right', 'select' : 'vertices in (x > 0.499)', 'kind' : 'facet', } region_3 = { 'name' : 'Gamma', 'select' : 'vertices of surface', 'kind' : 'facet', } ebc_1 = { 'name' : 't_left', 'region' : 'Left', 'dofs' : {'t.0' : 5.0}, } ebc_2 = { 'name' : 't_right', 'region' : 'Right', 'dofs' : {'t.0' : 0.0}, } # 'Left' : ('T3', (30,), 'linear_y'), integral_1 = { 'name' : 'i', 'order' : 2, } equations = { 'Temperature' : """dw_laplace.i.Omega( coef.val, s, t ) = 0""" } solution = { 't' : '- 5.0 * (x - 0.5)', } solver_0 = { 'name' : 'ls', 'kind' : 'ls.scipy_direct', } solver_1 = { 'name' : 'newton', 'kind' : 'nls.newton', 'i_max' : 1, 'eps_a' : 1e-10, } lin_min, lin_max = 0.0, 2.0 ## # 31.05.2007, c def linear( bc, ts, coor, which ): vals = coor[:,which] min_val, max_val = vals.min(), vals.max() vals = (vals - min_val) / (max_val - min_val) * (lin_max - lin_min) + lin_min return vals ## # 31.05.2007, c def linear_x( bc, ts, coor ): return linear( bc, ts, coor, 0 ) def linear_y( bc, ts, coor ): return linear( bc, ts, coor, 1 ) def linear_z( bc, ts, coor ): return linear( bc, ts, coor, 2 ) from sfepy.base.testing import TestCommon ## # 30.05.2007, c class Test( TestCommon ): ## # 30.05.2007, c def from_conf( conf, options ): from sfepy.applications import solve_pde problem, state = solve_pde(conf, save_results=False) test = Test(problem=problem, state=state, conf=conf, options=options) return test from_conf = staticmethod( from_conf ) ## # 30.05.2007, c def test_solution( self ): sol = self.conf.solution vec = self.state() problem = self.problem variables = problem.get_variables() ok = True for var_name, expression in six.iteritems(sol): coor = variables[var_name].field.get_coor() ana_sol = self.eval_coor_expression( expression, coor ) num_sol = variables.get_state_part_view( vec, var_name ) ret = self.compare_vectors( ana_sol, num_sol, label1 = 'analytical %s' % var_name, label2 = 'numerical %s' % var_name ) if not ret: self.report( 'variable %s: failed' % var_name ) ok = ok and ret return ok ## # c: 30.05.2007, r: 19.02.2008 def test_boundary_fluxes( self ): import os.path as op from sfepy.linalg import rotation_matrix2d from sfepy.discrete.evaluate import BasicEvaluator from sfepy.discrete import Material problem = self.problem angles = [0, 30, 45] region_names = ['Left', 'Right', 'Gamma'] values = [5.0, -5.0, 0.0] variables = problem.get_variables() get_state = variables.get_state_part_view state = self.state.copy(deep=True) problem.time_update(ebcs={}, epbcs={}) # problem.save_ebc( 'aux.vtk' ) state.apply_ebc() ev = BasicEvaluator( problem ) aux = ev.eval_residual(state()) field = variables['t'].field conf_m = problem.conf.get_item_by_name('materials', 'm') m = Material.from_conf(conf_m, problem.functions) name = op.join( self.options.out_dir, op.split( problem.domain.mesh.name )[1] + '_%02d.mesh' ) orig_coors = problem.get_mesh_coors().copy() ok = True for ia, angle in enumerate( angles ): self.report( '%d: mesh rotation %d degrees' % (ia, angle) ) problem.domain.mesh.transform_coors( rotation_matrix2d( angle ), ref_coors = orig_coors ) problem.set_mesh_coors(problem.domain.mesh.coors, update_fields=True) problem.domain.mesh.write( name % angle, io = 'auto' ) for ii, region_name in enumerate( region_names ): flux_term = 'd_surface_flux.i.%s( m.K, t )' % region_name val1 = problem.evaluate(flux_term, t=variables['t'], m=m) rvec = get_state( aux, 't', True ) reg = problem.domain.regions[region_name] nods = field.get_dofs_in_region(reg, merge=True) val2 = rvec[nods].sum() # Assume 1 dof per node. ok = ok and ((abs( val1 - values[ii] ) < 1e-10) and (abs( val2 - values[ii] ) < 1e-10)) self.report( ' %d. %s: %e == %e == %e'\ % (ii, region_name, val1, val2, values[ii]) ) # Restore original coordinates. problem.domain.mesh.transform_coors(
rotation_matrix2d(0)
sfepy.linalg.rotation_matrix2d
import numpy as nm from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy import data_dir def mesh_hook(mesh, mode): if mode == 'read': mesh = gen_block_mesh([0.0098, 0.0011, 0.1], [5, 3, 17], [0, 0, 0.05], name='specimen', verbose=False) return mesh elif mode == 'write': pass def optimization_hook(pb): cnf = pb.conf out = [] yield pb, out state = out[-1][1].get_parts() coors = pb.domain.cmesh.coors displ = state['u'].reshape((coors.shape[0],3)) # elongation mcoors = coors[cnf.mnodes, 2] mdispl = displ[cnf.mnodes, 2] dl = (mdispl[1] - mdispl[0]) / (mcoors[1] - mcoors[0]) if hasattr(cnf, 'opt_data'): # compute slope of the force-elongation curve cnf.opt_data['k'] = cnf.F / dl yield None def get_mat(coors, mode, pb): if mode == 'qp': # get material data if hasattr(pb.conf, 'opt_data'): # from homogenization D = pb.conf.opt_data['D_homog'] else: # given values D = stiffness_from_youngpoisson(3, 150.0e9, 0.3) nqp = coors.shape[0] return {'D': nm.tile(D, (nqp, 1, 1))} def define(is_opt=False): filename_mesh =
UserMeshIO(mesh_hook)
sfepy.discrete.fem.meshio.UserMeshIO
import numpy as nm from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy import data_dir def mesh_hook(mesh, mode): if mode == 'read': mesh = gen_block_mesh([0.0098, 0.0011, 0.1], [5, 3, 17], [0, 0, 0.05], name='specimen', verbose=False) return mesh elif mode == 'write': pass def optimization_hook(pb): cnf = pb.conf out = [] yield pb, out state = out[-1][1].get_parts() coors = pb.domain.cmesh.coors displ = state['u'].reshape((coors.shape[0],3)) # elongation mcoors = coors[cnf.mnodes, 2] mdispl = displ[cnf.mnodes, 2] dl = (mdispl[1] - mdispl[0]) / (mcoors[1] - mcoors[0]) if hasattr(cnf, 'opt_data'): # compute slope of the force-elongation curve cnf.opt_data['k'] = cnf.F / dl yield None def get_mat(coors, mode, pb): if mode == 'qp': # get material data if hasattr(pb.conf, 'opt_data'): # from homogenization D = pb.conf.opt_data['D_homog'] else: # given values D =
stiffness_from_youngpoisson(3, 150.0e9, 0.3)
sfepy.mechanics.matcoefs.stiffness_from_youngpoisson
# -*- coding: utf-8 -*- """ Fields for Discontinous Galerkin method """ import numpy as nm import six from numpy.lib.stride_tricks import as_strided from six.moves import range from sfepy.base.base import (output, assert_, Struct) from sfepy.discrete import Integral, PolySpace from sfepy.discrete.common.fields import parse_shape from sfepy.discrete.fem.fields_base import FEField from sfepy.discrete.fem.mappings import VolumeMapping def get_unraveler(n_el_nod, n_cell): """Returns function for unraveling i.e. unpacking dof data from serialized array from shape (n_el_nod*n_cell, 1) to (n_cell, n_el_nod, 1). The unraveler returns non-writeable view into the input array. Parameters ---------- n_el_nod : int expected dimensions of dofs array n_cell : int Returns ------- unravel : callable """ def unravel(u): """Returns non-writeable view into the input array reshaped to (n*m, 1) to (m, n, 1) . Parameters ---------- u : array_like solution in shape (n*m, 1) Returns ------- u : ndarray unraveledsolution in shape (m, n, 1) """ ustride1 = u.strides[0] ur = as_strided(u, shape=(n_cell, n_el_nod, 1), strides=(n_el_nod * ustride1, ustride1, ustride1), writeable=False) return ur return unravel def get_raveler(n_el_nod, n_cell): """Returns function for raveling i.e. packing dof data from two dimensional array of shape (n_cell, n_el_nod, 1) to (n_el_nod*n_cell, 1) The raveler returns view into the input array. Parameters ---------- n_el_nod : param n_el_nod, n_cell: expected dimensions of dofs array n_cell : int Returns ------- ravel : callable """ def ravel(u): """Returns view into the input array reshaped from (m, n, 1) to (n*m, 1) to (m, n, 1) . Parameters ---------- u : array_like Returns ------- u : ndarray """ # ustride1 = u.strides[0] # ur = as_strided(u, shape=(n_el_nod*n_cell, 1), # strides=(n_cell*ustride1, ustride1)) ur = nm.ravel(u)[:, None] # possibly use according to # https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html # ur = u.reshape(-1) return ur return ravel # mapping between geometry element types # and their facets types # TODO move to sfepy/discrete/fem/geometry_element.py? cell_facet_gel_name = { "1_2": "0_1", "2_3": "1_2", "2_4": "1_2", "3_4": "2_3", "3_8": "2_4" } def get_gel(region): """ Parameters ---------- region : sfepy.discrete.common.region.Region Returns ------- gel : base geometry element of the region """ cmesh = region.domain.cmesh for key, gel in six.iteritems(region.domain.geom_els): ct = cmesh.cell_types if (ct[region.cells] == cmesh.key_to_index[gel.name]).all(): return gel else: raise ValueError('Region {} contains multiple' ' reference geometries!'.format(region)) class DGField(FEField): """Class for usage with DG terms, provides functionality for Discontinous Galerkin method like neighbour look up, projection to discontinuous basis and correct DOF treatment. """ family_name = 'volume_DG_legendre_discontinuous' is_surface = False def __init__(self, name, dtype, shape, region, space="H1", poly_space_base="legendre", approx_order=1, integral=None): """ Creates DGField, with Legendre polyspace and default integral corresponding to 2 * approx_order. Parameters ---------- name : string dtype : type shape : string 'vector', 'scalar' or something else region : sfepy.discrete.common.region.Region space : string default "H1" poly_space_base : PolySpace optionally force polyspace approx_order : 0 for FVM, default 1 integral : Integral if None integral of order 2*approx_order is created """ shape =
parse_shape(shape, region.domain.shape.dim)
sfepy.discrete.common.fields.parse_shape
# -*- coding: utf-8 -*- """ Fields for Discontinous Galerkin method """ import numpy as nm import six from numpy.lib.stride_tricks import as_strided from six.moves import range from sfepy.base.base import (output, assert_, Struct) from sfepy.discrete import Integral, PolySpace from sfepy.discrete.common.fields import parse_shape from sfepy.discrete.fem.fields_base import FEField from sfepy.discrete.fem.mappings import VolumeMapping def get_unraveler(n_el_nod, n_cell): """Returns function for unraveling i.e. unpacking dof data from serialized array from shape (n_el_nod*n_cell, 1) to (n_cell, n_el_nod, 1). The unraveler returns non-writeable view into the input array. Parameters ---------- n_el_nod : int expected dimensions of dofs array n_cell : int Returns ------- unravel : callable """ def unravel(u): """Returns non-writeable view into the input array reshaped to (n*m, 1) to (m, n, 1) . Parameters ---------- u : array_like solution in shape (n*m, 1) Returns ------- u : ndarray unraveledsolution in shape (m, n, 1) """ ustride1 = u.strides[0] ur = as_strided(u, shape=(n_cell, n_el_nod, 1), strides=(n_el_nod * ustride1, ustride1, ustride1), writeable=False) return ur return unravel def get_raveler(n_el_nod, n_cell): """Returns function for raveling i.e. packing dof data from two dimensional array of shape (n_cell, n_el_nod, 1) to (n_el_nod*n_cell, 1) The raveler returns view into the input array. Parameters ---------- n_el_nod : param n_el_nod, n_cell: expected dimensions of dofs array n_cell : int Returns ------- ravel : callable """ def ravel(u): """Returns view into the input array reshaped from (m, n, 1) to (n*m, 1) to (m, n, 1) . Parameters ---------- u : array_like Returns ------- u : ndarray """ # ustride1 = u.strides[0] # ur = as_strided(u, shape=(n_el_nod*n_cell, 1), # strides=(n_cell*ustride1, ustride1)) ur = nm.ravel(u)[:, None] # possibly use according to # https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html # ur = u.reshape(-1) return ur return ravel # mapping between geometry element types # and their facets types # TODO move to sfepy/discrete/fem/geometry_element.py? cell_facet_gel_name = { "1_2": "0_1", "2_3": "1_2", "2_4": "1_2", "3_4": "2_3", "3_8": "2_4" } def get_gel(region): """ Parameters ---------- region : sfepy.discrete.common.region.Region Returns ------- gel : base geometry element of the region """ cmesh = region.domain.cmesh for key, gel in six.iteritems(region.domain.geom_els): ct = cmesh.cell_types if (ct[region.cells] == cmesh.key_to_index[gel.name]).all(): return gel else: raise ValueError('Region {} contains multiple' ' reference geometries!'.format(region)) class DGField(FEField): """Class for usage with DG terms, provides functionality for Discontinous Galerkin method like neighbour look up, projection to discontinuous basis and correct DOF treatment. """ family_name = 'volume_DG_legendre_discontinuous' is_surface = False def __init__(self, name, dtype, shape, region, space="H1", poly_space_base="legendre", approx_order=1, integral=None): """ Creates DGField, with Legendre polyspace and default integral corresponding to 2 * approx_order. Parameters ---------- name : string dtype : type shape : string 'vector', 'scalar' or something else region : sfepy.discrete.common.region.Region space : string default "H1" poly_space_base : PolySpace optionally force polyspace approx_order : 0 for FVM, default 1 integral : Integral if None integral of order 2*approx_order is created """ shape = parse_shape(shape, region.domain.shape.dim) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) if isinstance(approx_order, tuple): self.approx_order = approx_order[0] else: self.approx_order = approx_order # geometry self.domain = region.domain self.region = region self.dim = region.tdim self._setup_geometry() self._setup_connectivity() # TODO treat domains embedded into higher dimensional spaces? self.n_el_facets = self.dim + 1 if self.gel.is_simplex else 2**self.dim # approximation space self.space = space self.poly_space_base = poly_space_base self.force_bubble = False self._create_interpolant() # DOFs self._setup_shape() self._setup_all_dofs() self.ravel_sol = get_raveler(self.n_el_nod, self.n_cell) self.unravel_sol = get_unraveler(self.n_el_nod, self.n_cell) # integral self.clear_qp_base() self.clear_facet_qp_base() if integral is None: self.integral = Integral("dg_fi", order = 2 * self.approx_order) else: self.integral = integral self.ori = None self.basis_transform = None # mapping self.mappings = {} self.mapping = self.create_mapping(self.region, self.integral, "volume", return_mapping=True)[1] self.mappings0 = {} # neighbour facet mapping and data caches # TODO use lru cache or different method? self.clear_facet_neighbour_idx_cache() self.clear_normals_cache() self.clear_facet_vols_cache() self.boundary_facet_local_idx = {} def _create_interpolant(self): name = self.gel.name + '_DG_legendre' ps = PolySpace.any_from_args(name, self.gel, self.approx_order, base=self.poly_space_base, force_bubble=False) self.poly_space = ps # 'legendre_simplex' is created for '1_2'. if self.gel.name in ["2_4", "3_8"]: self.extended = True else: self.extended = False def _setup_all_dofs(self): """Sets up all the differet kinds of DOFs, for DG only bubble DOFs""" self.n_el_nod = self.poly_space.n_nod self.n_vertex_dof = 0 # in DG we will propably never need vertex DOFs self.n_edge_dof = 0 # use facets DOFS for AFS methods self.n_face_dof = 0 # use facet DOF for AFS methods (self.n_bubble_dof, self.bubble_remap, self.bubble_dofs) = self._setup_bubble_dofs() self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof def _setup_bubble_dofs(self): """Creates DOF information for so called element, cell or bubble DOFs - the only DOFs used in DG n_dof = n_cells * n_el_nod remap optional remapping between cells dofs is mapping between dofs and cells Returns ------- n_dof : int remap : ndarray dofs : ndarray """ self.n_cell = self.region.get_n_cells(self.is_surface) n_dof = self.n_cell * self.n_el_nod dofs = nm.arange(n_dof, dtype=nm.int32)\ .reshape(self.n_cell, self.n_el_nod) remap = nm.arange(self.n_cell) self.econn = dofs self.dofs2cells = nm.repeat(nm.arange(self.n_cell), self.n_el_nod) return n_dof, remap, dofs def _setup_shape(self): """What is shape used for and what it really means. Does it represent shape of the problem? """ self.n_components = nm.prod(self.shape) self.val_shape = self.shape def _setup_geometry(self): """Setup the field region geometry.""" # get_gel extracts the highest dimension geometry from self.region self.gel = get_gel(self.region) def _setup_connectivity(self): """Forces self.domain.mesh to build necessary conductivities so they are available in self.get_nbrhd_dofs """ self.region.domain.mesh.cmesh.setup_connectivity(self.dim, self.dim) self.region.domain.mesh.cmesh.setup_connectivity(self.dim - 1, self.dim) self.region.domain.mesh.cmesh.setup_connectivity(self.dim, self.dim - 1) def get_coor(self, nods=None): """Returns coors for matching nodes # TODO revise DG_EPBC and EPBC matching? Parameters ---------- nods : if None use all nodes (Default value = None) Returns ------- coors : ndarray coors on surface """ if nods is None: nods = self.bubble_dofs cells = self.dofs2cells[nods] coors = self.domain.mesh.cmesh.get_centroids(self.dim)[cells] eps = min(self.domain.cmesh.get_volumes(self.dim)) / (self.n_el_nod + 2) if self.dim == 1: extended_coors = nm.zeros(nm.shape(coors)[:-1] + (2,)) extended_coors[:, 0] = coors[:, 0] coors = extended_coors # shift centroid coors to lie within cells but be different for each dof # use coors of facet QPs? coors += eps * nm.repeat(nm.arange(self.n_el_nod), len(nm.unique(cells)))[:, None] return coors def clear_facet_qp_base(self): """Clears facet_qp_base cache""" self.facet_bf = {} self.facet_qp = None self.facet_whs = None def _transform_qps_to_facets(self, qps, geo_name): """Transforms points given in qps to all facets of the reference element with geometry geo_name. Parameters ---------- qps : qps corresponding to facet dimension to be transformed geo_name : element type Returns ------- tqps : ndarray tqps is of shape shape(qps) + (n_el_facets, geo dim) """ if geo_name == "1_2": tqps = nm.zeros(nm.shape(qps) + (2, 1,)) tqps[..., 0, 0] = 0. tqps[..., 1, 0] = 1. elif geo_name == "2_3": tqps = nm.zeros(nm.shape(qps) + (3, 2,)) # 0. tqps[..., 0, 0] = qps # x = 0 + t tqps[..., 0, 1] = 0. # y = 0 # 1. tqps[..., 1, 0] = 1 - qps # x = 1 - t tqps[..., 1, 1] = qps # y = t # 2. tqps[..., 2, 0] = 0 # x = 0 tqps[..., 2, 1] = 1 - qps # y = 1 - t elif geo_name == "2_4": tqps = nm.zeros(nm.shape(qps) + (4, 2,)) # 0. tqps[..., 0, 0] = qps # x = t tqps[..., 0, 1] = 0. # y = 0 # 1. tqps[..., 1, 0] = 1 # x = 1 tqps[..., 1, 1] = qps # y = t # 2. tqps[..., 2, 0] = 1 - qps # x = 1 -t tqps[..., 2, 1] = 1 # y = 1 # 3. tqps[..., 3, 0] = 0 # x = 0 tqps[..., 3, 1] = 1 - qps # y = 1 - t elif geo_name == "3_4": # tqps = nm.zeros(nm.shape(qps) + (4, 3,)) raise NotImplementedError("Geometry {} not supported, yet" .format(geo_name)) elif geo_name == "3_8": # tqps = nm.zeros(nm.shape(qps) + (8, 3,)) raise NotImplementedError("Geometry {} not supported, yet" .format(geo_name)) else: raise NotImplementedError("Geometry {} not supported, yet" .format(geo_name)) return tqps def get_facet_qp(self): """Returns quadrature points on all facets of the reference element in array of shape (n_qp, 1 , n_el_facets, dim) Returns ------- qps : ndarray quadrature points weights : ndarray Still needs to be transformed to actual facets! """ if self.dim == 1: facet_qps = self._transform_qps_to_facets(nm.zeros((1, 1)), "1_2") weights = nm.ones((1, 1, 1)) else: qps, weights = self.integral.get_qp(cell_facet_gel_name[self.gel.name]) weights = weights[None, :, None] facet_qps = self._transform_qps_to_facets(qps, self.gel.name) return facet_qps, weights def get_facet_base(self, derivative=False, base_only=False): """ Returns values of base in facets quadrature points, data shape is a bit crazy right now: (number of qps, 1, n_el_facets, 1, n_el_nod) end for derivatine: (1, number of qps, (dim,) * derivative, n_el_facets, 1, n_el_nod) Parameters ---------- derivative: truthy or integer base_only: do not return weights Returns ------- facet_bf : ndarray values of basis functions in facet qps weights : ndarray, optionally weights of qps """ if derivative: diff = int(derivative) else: diff = 0 if diff in self.facet_bf: facet_bf = self.facet_bf[diff] whs = self.facet_whs else: qps, whs = self.get_facet_qp() ps = self.poly_space self.facet_qp = qps self.facet_whs = whs if derivative: facet_bf = nm.zeros((1,) + nm.shape(qps)[:-1] + (self.dim,) * diff + (self.n_el_nod,)) else: facet_bf = nm.zeros(nm.shape(qps)[:-1] + (1, self.n_el_nod,)) for i in range(self.n_el_facets): facet_bf[..., i, :, :] = \ ps.eval_base(qps[..., i, :], diff=diff, transform=self.basis_transform) self.facet_bf[diff] = facet_bf if base_only: return facet_bf else: return facet_bf, whs def clear_facet_neighbour_idx_cache(self, region=None): """ If region is None clear all! Parameters ---------- region : sfepy.discrete.common.region.Region If None clear all. """ if region is None: self.facet_neighbour_index = {} else: self.facet_neighbour_index.pop(region.name) def get_facet_neighbor_idx(self, region=None, eq_map=None): """ Returns index of cell neighbours sharing facet, along with local index of the facet within neighbour, also treats periodic boundary conditions i.e. plugs correct neighbours for cell on periodic boundary. Where there are no neighbours specified puts -1 instead of neighbour and facet id Cashes neighbour index in self.facet_neighbours Parameters ---------- region : sfepy.discrete.common.region.Region Main region, must contain cells. eq_map : eq_map from state variable containing information on EPBC and DG EPBC. (Default value = None) Returns ------- facet_neighbours : ndarray Shape is (n_cell, n_el_facet, 2), first value is index of the neighbouring cell, the second is index of the facet in said nb. cell. """ if region is None or eq_map is None: # HOTFIX enabling limiter to obtain connectivity data without # knowing eq_map or region if self.region.name in self.facet_neighbour_index: return self.facet_neighbour_index[self.region.name] else: raise ValueError("No facet neighbour mapping for main " + "region {}".format(self.region.name) + " cached yet, call with region and " + "eq_map first.") if region.name in self.facet_neighbour_index: return self.facet_neighbour_index[region.name] dim, n_cell, n_el_facets = self.get_region_info(region) cmesh = region.domain.mesh.cmesh cells = region.cells facet_neighbours = nm.zeros((n_cell, n_el_facets, 2), dtype=nm.int32) c2fi, c2fo = cmesh.get_incident(dim - 1, cells, dim, ret_offsets=True) for ic, o1 in enumerate(c2fo[:-1]): # loop over cells o2 = c2fo[ic + 1] # get neighbours per facet of the cell c2ci, c2co = cmesh.get_incident(dim, c2fi[o1:o2], dim - 1, ret_offsets=True) ii = cmesh.get_local_ids(c2fi[o1:o2], dim - 1, c2ci, c2co, dim) fis = nm.c_[c2ci, ii] nbrs = [] for ifa, of1 in enumerate(c2co[:-1]): # loop over facets of2 = c2co[ifa + 1] if of2 == (of1 + 1): # facet has only one cell # Surface facet. nbrs.append([-1, -1]) # c2ci[of1]) # append no neighbours else: if c2ci[of1] == cells[ic]: # do not append the cell itself nbrs.append(fis[of2 - 1]) else: nbrs.append(fis[of1]) facet_neighbours[ic, :, :] = nbrs facet_neighbours = \ self._set_fem_periodic_facet_neighbours(facet_neighbours, eq_map) facet_neighbours = \ self._set_dg_periodic_facet_neighbours(facet_neighbours, eq_map) # cache results self.facet_neighbour_index[region.name] = facet_neighbours return facet_neighbours def _set_dg_periodic_facet_neighbours(self, facet_neighbours, eq_map): """ Parameters ---------- facet_neighbours : array_like Shape is (n_cell, n_el_facet, 2), first value is index of the neighbouring cell the second is index of the facet in said nb. cell. eq_map : must contain dg_ep_bc a List with pairs of slave and master boundary cell boundary facet mapping Returns ------- facet_neighbours : ndarray Updated incidence array. """ # if eq_map. # treat DG EPBC - these are definitely preferred if eq_map.n_dg_epbc > 0 and self.gel.name not in ["1_2", "2_4", "3_6"]: raise ValueError( "Periodic boundary conditions not supported " + "for geometry {} elements.".format(self.gel.name)) dg_epbc = eq_map.dg_epbc for master_bc2bfi, slave_bc2bfi in dg_epbc: # set neighbours of periodic cells to one another facet_neighbours[master_bc2bfi[:, 0], master_bc2bfi[:, 1], 0] = \ slave_bc2bfi[:, 0] facet_neighbours[slave_bc2bfi[:, 0], slave_bc2bfi[:, 1], 0] = \ master_bc2bfi[:, 0] # set neighbours facets facet_neighbours[slave_bc2bfi[:, 0], slave_bc2bfi[:, 1], 1] = \ master_bc2bfi[:, 1] facet_neighbours[master_bc2bfi[:, 0], master_bc2bfi[:, 1], 1] =\ slave_bc2bfi[:, 1] return facet_neighbours def _set_fem_periodic_facet_neighbours(self, facet_neighbours, eq_map): """Maybe remove after DG EPBC revision in self.get_coor Parameters ---------- facet_neighbours : array_like Shape is (n_cell, n_el_facet, 2), first value is index of the neighbouring cell the second is index of the facet in said nb. cell. eq_map : eq_map from state variable containing information on EPBC and DG EPBC. Returns ------- facet_neighbours : ndarray Updated incidence array. """ # treat classical FEM EPBCs - we need to correct neighbours if eq_map.n_epbc > 0: # set neighbours of periodic cells to one another mcells = nm.unique(self.dofs2cells[eq_map.master]) scells = nm.unique(self.dofs2cells[eq_map.slave]) mcells_facets = nm.array( nm.where(facet_neighbours[mcells] == -1))[1, 0] # facets mcells scells_facets = nm.array( nm.where(facet_neighbours[scells] == -1))[1, 0] # facets scells # [1, 0] above, first we need second axis to get axis on which # facet indices are stored, second we drop axis with neighbour # local facet index, # # for multiple s/mcells this will have to be # something like 1 + 2*nm.arange(len(mcells)) - to skip double # entries for -1 tags in neighbours and neighbour local facet idx # set neighbours of mcells to scells facet_neighbours[mcells, mcells_facets, 0] = scells # set neighbour facets to facets of scell missing neighbour facet_neighbours[ mcells, mcells_facets, 1] = scells_facets # we do not need to distinguish EBC and EPBC cells, EBC overwrite # EPBC, we only need to fix shapes # set neighbours of scells to mcells facet_neighbours[scells, scells_facets, 0] = mcells # set neighbour facets to facets of mcell missing neighbour0 facet_neighbours[ scells, scells_facets, 1] = mcells_facets return facet_neighbours @staticmethod def get_region_info(region): """ Extracts information about region needed in various methods of DGField Parameters ---------- region : sfepy.discrete.common.region.Region Returns ------- dim, n_cell, n_el_facets """ if not region.has_cells(): raise ValueError("Region {} has no cells".format(region.name)) n_cell = region.get_n_cells() dim = region.tdim gel = get_gel(region) n_el_facets = dim + 1 if gel.is_simplex else 2 ** dim return dim, n_cell, n_el_facets def get_both_facet_state_vals(self, state, region, derivative=None, reduce_nod=True): """Computes values of the variable represented by dofs in quadrature points located at facets, returns both values - inner and outer, along with weights. Parameters ---------- state : state variable containing BC info region : sfepy.discrete.common.region.Region derivative : compute derivative if truthy, compute n-th derivative if a number (Default value = None) reduce_nod : if False DOES NOT sum nodes into values at QPs (Default value = True) Returns ------- inner_facet_values (n_cell, n_el_facets, n_qp), outer facet values (n_cell, n_el_facets, n_qp), weights, if derivative is True: inner_facet_values (n_cell, n_el_facets, dim, n_qp), outer_facet values (n_cell, n_el_facets, dim, n_qp) """ if derivative: diff = int(derivative) else: diff = 0 unreduce_nod = int(not reduce_nod) inner_base_vals, outer_base_vals, whs = \ self.get_both_facet_base_vals(state, region, derivative=derivative) dofs = self.unravel_sol(state.data[0]) n_qp = whs.shape[-1] outputs_shape = (self.n_cell, self.n_el_facets) + \ (self.n_el_nod,) * unreduce_nod + \ (self.dim,) * diff + \ (n_qp,) inner_facet_vals = nm.zeros(outputs_shape) if unreduce_nod: inner_facet_vals[:] = nm.einsum('id...,idf...->ifd...', dofs, inner_base_vals) else: inner_facet_vals[:] = nm.einsum('id...,id...->i...', dofs, inner_base_vals) per_facet_neighbours = self.get_facet_neighbor_idx(region, state.eq_map) outer_facet_vals = nm.zeros(outputs_shape) for facet_n in range(self.n_el_facets): if unreduce_nod: outer_facet_vals[:, facet_n, :] = \ nm.einsum('id...,id...->id...', dofs[per_facet_neighbours[:, facet_n, 0]], outer_base_vals[:, :, facet_n]) else: outer_facet_vals[:, facet_n, :] = \ nm.einsum('id...,id...->i...', dofs[per_facet_neighbours[:, facet_n, 0]], outer_base_vals[:, :, facet_n]) boundary_cells = nm.array(nm.where(per_facet_neighbours[:, :, 0] < 0)).T outer_facet_vals[boundary_cells[:, 0], boundary_cells[:, 1]] = 0.0 # TODO detect and print boundary cells without defined BCs? for ebc, ebc_vals in zip(state.eq_map.dg_ebc.get(diff, []), state.eq_map.dg_ebc_val.get(diff, [])): if unreduce_nod: raise NotImplementedError( "Unreduced DOFs are not available for boundary " + "outerfacets") outer_facet_vals[ebc[:, 0], ebc[:, 1], :] = \ nm.einsum("id,id...->id...", ebc_vals, inner_base_vals[0, :, ebc[:, 1]]) else: # fix flipping qp order to accomodate for # opposite facet orientation of neighbours outer_facet_vals[ebc[:, 0], ebc[:, 1], :] = ebc_vals[:, ::-1] # flip outer_facet_vals moved to get_both_facet_base_vals return inner_facet_vals, outer_facet_vals, whs def get_both_facet_base_vals(self, state, region, derivative=None): """Returns values of the basis function in quadrature points on facets broadcasted to all cells inner to the element as well as outer ones along with weights for the qps broadcasted and transformed to elements. Contains quick fix to flip facet QPs for right integration order. Parameters ---------- state : used to get EPBC info region : sfepy.discrete.common.region.Region for connectivity derivative : if u need derivative (Default value = None) Returns ------- outer_facet_base_vals: inner_facet_base_vals: shape (n_cell, n_el_nod, n_el_facet, n_qp) or (n_cell, n_el_nod, n_el_facet, dim, n_qp) when derivative is True or 1 whs: shape (n_cell, n_el_facet, n_qp) """ if derivative: diff = int(derivative) else: diff = 0 facet_bf, whs = self.get_facet_base(derivative=derivative) n_qp = nm.shape(whs)[1] facet_vols = self.get_facet_vols(region) whs = facet_vols * whs[None, :, :, 0] base_shape = (self.n_cell, self.n_el_nod, self.n_el_facets) + \ (self.dim,) * diff + \ (n_qp,) inner_facet_base_vals = nm.zeros(base_shape) outer_facet_base_vals = nm.zeros(base_shape) if derivative: inner_facet_base_vals[:] = facet_bf[0, :, 0, :, :, :]\ .swapaxes(-2, -3).T else: inner_facet_base_vals[:] = facet_bf[:, 0, :, 0, :].T per_facet_neighbours = self.get_facet_neighbor_idx(region, state.eq_map) # numpy prepends shape resulting from multiple # indexing before remaining shape if derivative: outer_facet_base_vals[:] = \ inner_facet_base_vals[0, :, per_facet_neighbours[:, :, 1]]\ .swapaxes(-3, -4) else: outer_facet_base_vals[:] = \ inner_facet_base_vals[0, :, per_facet_neighbours[:, :, 1]]\ .swapaxes(-2, -3) # fix to flip facet QPs for right integration order return inner_facet_base_vals, outer_facet_base_vals[..., ::-1], whs def clear_normals_cache(self, region=None): """Clears normals cache for given region or all regions. Parameters ---------- region : sfepy.discrete.common.region.Region region to clear cache or None to clear all """ if region is None: self.normals_cache = {} else: if isinstance(region, str): self.normals_cache.pop(region) else: self.normals_cache.pop(region.name) def get_cell_normals_per_facet(self, region): """Caches results, use clear_normals_cache to clear the cache. Parameters ---------- region: sfepy.discrete.common.region.Region Main region, must contain cells. Returns ------- normals: ndarray normals of facets in array of shape (n_cell, n_el_facets, dim) """ if region.name in self.normals_cache: return self.normals_cache[region.name] dim, n_cell, n_el_facets = self.get_region_info(region) cmesh = region.domain.mesh.cmesh normals = cmesh.get_facet_normals() normals_out = nm.zeros((n_cell, n_el_facets, dim)) c2f = cmesh.get_conn(dim, dim - 1) for ic, o1 in enumerate(c2f.offsets[:-1]): o2 = c2f.offsets[ic + 1] for ifal, ifa in enumerate(c2f.indices[o1:o2]): normals_out[ic, ifal] = normals[o1 + ifal] self.normals_cache[region.name] = normals_out return normals_out def clear_facet_vols_cache(self, region=None): """Clears facet volume cache for given region or all regions. Parameters ---------- region : sfepy.discrete.common.region.Region region to clear cache or None to clear all """ if region is None: self.facet_vols_cache = {} else: if isinstance(region, str): self.facet_vols_cache.pop(region) else: self.facet_vols_cache.pop(region.name) def get_facet_vols(self, region): """Caches results, use clear_facet_vols_cache to clear the cache Parameters ---------- region : sfepy.discrete.common.region.Region Returns ------- vols_out: ndarray volumes of the facets by cells shape (n_cell, n_el_facets, 1) """ if region.name in self.facet_vols_cache: return self.facet_vols_cache[region.name] dim, n_cell, n_el_facets = self.get_region_info(region) cmesh = region.domain.mesh.cmesh if dim == 1: vols = nm.ones((cmesh.num[0], 1)) else: vols = cmesh.get_volumes(dim - 1)[:, None] vols_out = nm.zeros((n_cell, n_el_facets, 1)) c2f = cmesh.get_conn(dim, dim - 1) for ic, o1 in enumerate(c2f.offsets[:-1]): o2 = c2f.offsets[ic + 1] for ifal, ifa in enumerate(c2f.indices[o1:o2]): vols_out[ic, ifal] = vols[ifa] self.facet_vols_cache[region.name] = vols_out return vols_out def get_data_shape(self, integral, integration='volume', region_name=None): """Returns data shape (n_nod, n_qp, self.gel.dim, self.n_el_nod) Parameters ---------- integral : integral used integration : 'volume' is only supported value (Default value = 'volume') region_name : not used (Default value = None) Returns ------- data_shape : tuple """ if integration in ('volume',): # from FEField.get_data_shape() _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (self.n_cell, n_qp, self.gel.dim, self.n_el_nod) # econn.shape[1] == n_el_nod i.e. number nod in element else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_econn(self, conn_type, region, is_trace=False, integration=None): """Getter for econn Parameters ---------- conn_type : string or Struct 'volume' is only supported region : sfepy.discrete.common.region.Region is_trace : ignored (Default value = False) integration : ignored (Default value = None) Returns ------- econn : ndarray connectivity information """ ct = conn_type.type if isinstance(conn_type, Struct) else conn_type if ct == 'volume': if region.name == self.region.name: conn = self.econn else: raise ValueError("Bad region for the field") else: raise ValueError('unknown connectivity type! (%s)' % ct) return conn def setup_extra_data(self, geometry, info, is_trace): """This is called in create_adof_conns(conn_info, var_indx=None, active_only=True, verbose=True) for each variable but has no effect. Parameters ---------- geometry : ignored info : set to self.info is_trace : set to self.trace """ # placeholder, what is this used for? # dct = info.dc_type.type self.info = info self.is_trace = is_trace def get_dofs_in_region(self, region, merge=True): """Return indices of DOFs that belong to the given region. Not Used in BC treatment Parameters ---------- region : sfepy.discrete.common.region.Region merge : bool merge dof tuple into one numpy array, default True Returns ------- dofs : ndarray """ dofs = [] if region.has_cells(): # main region or its part els = nm.ravel(self.bubble_remap[region.cells]) eldofs = self.bubble_dofs[els[els >= 0]] dofs.append(eldofs) else: # return indices of cells adjacent to boundary facets dim = self.dim cmesh = region.domain.mesh.cmesh bc_cells = cmesh.get_incident(dim, region.facets, dim - 1) bc_dofs = self.bubble_dofs[bc_cells] dofs.append(bc_dofs) if merge: dofs = nm.concatenate(dofs) return dofs def get_bc_facet_idx(self, region): """Caches results in self.boundary_facet_local_idx Parameters ---------- region : sfepy.discrete.common.region.Region surface region defining BCs Returns ------- bc2bfi : ndarray index of cells on boundary along with corresponding facets """ if region.name in self.boundary_facet_local_idx: return self.boundary_facet_local_idx[region.name] bc2bfi = region.get_facet_indices() self.boundary_facet_local_idx[region.name] = bc2bfi return bc2bfi def create_mapping(self, region, integral, integration, return_mapping=True): """Creates and returns mapping Parameters ---------- region : sfepy.discrete.common.region.Region integral : Integral integration : str 'volume' is only accepted option return_mapping : default True (Default value = True) Returns ------- mapping : VolumeMapping """ domain = self.domain coors = domain.get_mesh_coors(actual=True) dconn = domain.get_conn() # from FEField if integration == 'volume': qp = self.get_qp('v', integral) # qp = self.integral.get_qp(self.gel.name) iels = region.get_cells() geo_ps = self.gel.poly_space ps = self.poly_space bf = self.get_base('v', 0, integral, iels=iels) conn = nm.take(dconn, iels.astype(nm.int32), axis=0) mapping =
VolumeMapping(coors, conn, poly_space=geo_ps)
sfepy.discrete.fem.mappings.VolumeMapping
# -*- coding: utf-8 -*- """ Fields for Discontinous Galerkin method """ import numpy as nm import six from numpy.lib.stride_tricks import as_strided from six.moves import range from sfepy.base.base import (output, assert_, Struct) from sfepy.discrete import Integral, PolySpace from sfepy.discrete.common.fields import parse_shape from sfepy.discrete.fem.fields_base import FEField from sfepy.discrete.fem.mappings import VolumeMapping def get_unraveler(n_el_nod, n_cell): """Returns function for unraveling i.e. unpacking dof data from serialized array from shape (n_el_nod*n_cell, 1) to (n_cell, n_el_nod, 1). The unraveler returns non-writeable view into the input array. Parameters ---------- n_el_nod : int expected dimensions of dofs array n_cell : int Returns ------- unravel : callable """ def unravel(u): """Returns non-writeable view into the input array reshaped to (n*m, 1) to (m, n, 1) . Parameters ---------- u : array_like solution in shape (n*m, 1) Returns ------- u : ndarray unraveledsolution in shape (m, n, 1) """ ustride1 = u.strides[0] ur = as_strided(u, shape=(n_cell, n_el_nod, 1), strides=(n_el_nod * ustride1, ustride1, ustride1), writeable=False) return ur return unravel def get_raveler(n_el_nod, n_cell): """Returns function for raveling i.e. packing dof data from two dimensional array of shape (n_cell, n_el_nod, 1) to (n_el_nod*n_cell, 1) The raveler returns view into the input array. Parameters ---------- n_el_nod : param n_el_nod, n_cell: expected dimensions of dofs array n_cell : int Returns ------- ravel : callable """ def ravel(u): """Returns view into the input array reshaped from (m, n, 1) to (n*m, 1) to (m, n, 1) . Parameters ---------- u : array_like Returns ------- u : ndarray """ # ustride1 = u.strides[0] # ur = as_strided(u, shape=(n_el_nod*n_cell, 1), # strides=(n_cell*ustride1, ustride1)) ur = nm.ravel(u)[:, None] # possibly use according to # https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html # ur = u.reshape(-1) return ur return ravel # mapping between geometry element types # and their facets types # TODO move to sfepy/discrete/fem/geometry_element.py? cell_facet_gel_name = { "1_2": "0_1", "2_3": "1_2", "2_4": "1_2", "3_4": "2_3", "3_8": "2_4" } def get_gel(region): """ Parameters ---------- region : sfepy.discrete.common.region.Region Returns ------- gel : base geometry element of the region """ cmesh = region.domain.cmesh for key, gel in six.iteritems(region.domain.geom_els): ct = cmesh.cell_types if (ct[region.cells] == cmesh.key_to_index[gel.name]).all(): return gel else: raise ValueError('Region {} contains multiple' ' reference geometries!'.format(region)) class DGField(FEField): """Class for usage with DG terms, provides functionality for Discontinous Galerkin method like neighbour look up, projection to discontinuous basis and correct DOF treatment. """ family_name = 'volume_DG_legendre_discontinuous' is_surface = False def __init__(self, name, dtype, shape, region, space="H1", poly_space_base="legendre", approx_order=1, integral=None): """ Creates DGField, with Legendre polyspace and default integral corresponding to 2 * approx_order. Parameters ---------- name : string dtype : type shape : string 'vector', 'scalar' or something else region : sfepy.discrete.common.region.Region space : string default "H1" poly_space_base : PolySpace optionally force polyspace approx_order : 0 for FVM, default 1 integral : Integral if None integral of order 2*approx_order is created """ shape = parse_shape(shape, region.domain.shape.dim) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) if isinstance(approx_order, tuple): self.approx_order = approx_order[0] else: self.approx_order = approx_order # geometry self.domain = region.domain self.region = region self.dim = region.tdim self._setup_geometry() self._setup_connectivity() # TODO treat domains embedded into higher dimensional spaces? self.n_el_facets = self.dim + 1 if self.gel.is_simplex else 2**self.dim # approximation space self.space = space self.poly_space_base = poly_space_base self.force_bubble = False self._create_interpolant() # DOFs self._setup_shape() self._setup_all_dofs() self.ravel_sol = get_raveler(self.n_el_nod, self.n_cell) self.unravel_sol = get_unraveler(self.n_el_nod, self.n_cell) # integral self.clear_qp_base() self.clear_facet_qp_base() if integral is None: self.integral = Integral("dg_fi", order = 2 * self.approx_order) else: self.integral = integral self.ori = None self.basis_transform = None # mapping self.mappings = {} self.mapping = self.create_mapping(self.region, self.integral, "volume", return_mapping=True)[1] self.mappings0 = {} # neighbour facet mapping and data caches # TODO use lru cache or different method? self.clear_facet_neighbour_idx_cache() self.clear_normals_cache() self.clear_facet_vols_cache() self.boundary_facet_local_idx = {} def _create_interpolant(self): name = self.gel.name + '_DG_legendre' ps = PolySpace.any_from_args(name, self.gel, self.approx_order, base=self.poly_space_base, force_bubble=False) self.poly_space = ps # 'legendre_simplex' is created for '1_2'. if self.gel.name in ["2_4", "3_8"]: self.extended = True else: self.extended = False def _setup_all_dofs(self): """Sets up all the differet kinds of DOFs, for DG only bubble DOFs""" self.n_el_nod = self.poly_space.n_nod self.n_vertex_dof = 0 # in DG we will propably never need vertex DOFs self.n_edge_dof = 0 # use facets DOFS for AFS methods self.n_face_dof = 0 # use facet DOF for AFS methods (self.n_bubble_dof, self.bubble_remap, self.bubble_dofs) = self._setup_bubble_dofs() self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof def _setup_bubble_dofs(self): """Creates DOF information for so called element, cell or bubble DOFs - the only DOFs used in DG n_dof = n_cells * n_el_nod remap optional remapping between cells dofs is mapping between dofs and cells Returns ------- n_dof : int remap : ndarray dofs : ndarray """ self.n_cell = self.region.get_n_cells(self.is_surface) n_dof = self.n_cell * self.n_el_nod dofs = nm.arange(n_dof, dtype=nm.int32)\ .reshape(self.n_cell, self.n_el_nod) remap = nm.arange(self.n_cell) self.econn = dofs self.dofs2cells = nm.repeat(nm.arange(self.n_cell), self.n_el_nod) return n_dof, remap, dofs def _setup_shape(self): """What is shape used for and what it really means. Does it represent shape of the problem? """ self.n_components = nm.prod(self.shape) self.val_shape = self.shape def _setup_geometry(self): """Setup the field region geometry.""" # get_gel extracts the highest dimension geometry from self.region self.gel = get_gel(self.region) def _setup_connectivity(self): """Forces self.domain.mesh to build necessary conductivities so they are available in self.get_nbrhd_dofs """ self.region.domain.mesh.cmesh.setup_connectivity(self.dim, self.dim) self.region.domain.mesh.cmesh.setup_connectivity(self.dim - 1, self.dim) self.region.domain.mesh.cmesh.setup_connectivity(self.dim, self.dim - 1) def get_coor(self, nods=None): """Returns coors for matching nodes # TODO revise DG_EPBC and EPBC matching? Parameters ---------- nods : if None use all nodes (Default value = None) Returns ------- coors : ndarray coors on surface """ if nods is None: nods = self.bubble_dofs cells = self.dofs2cells[nods] coors = self.domain.mesh.cmesh.get_centroids(self.dim)[cells] eps = min(self.domain.cmesh.get_volumes(self.dim)) / (self.n_el_nod + 2) if self.dim == 1: extended_coors = nm.zeros(nm.shape(coors)[:-1] + (2,)) extended_coors[:, 0] = coors[:, 0] coors = extended_coors # shift centroid coors to lie within cells but be different for each dof # use coors of facet QPs? coors += eps * nm.repeat(nm.arange(self.n_el_nod), len(nm.unique(cells)))[:, None] return coors def clear_facet_qp_base(self): """Clears facet_qp_base cache""" self.facet_bf = {} self.facet_qp = None self.facet_whs = None def _transform_qps_to_facets(self, qps, geo_name): """Transforms points given in qps to all facets of the reference element with geometry geo_name. Parameters ---------- qps : qps corresponding to facet dimension to be transformed geo_name : element type Returns ------- tqps : ndarray tqps is of shape shape(qps) + (n_el_facets, geo dim) """ if geo_name == "1_2": tqps = nm.zeros(nm.shape(qps) + (2, 1,)) tqps[..., 0, 0] = 0. tqps[..., 1, 0] = 1. elif geo_name == "2_3": tqps = nm.zeros(nm.shape(qps) + (3, 2,)) # 0. tqps[..., 0, 0] = qps # x = 0 + t tqps[..., 0, 1] = 0. # y = 0 # 1. tqps[..., 1, 0] = 1 - qps # x = 1 - t tqps[..., 1, 1] = qps # y = t # 2. tqps[..., 2, 0] = 0 # x = 0 tqps[..., 2, 1] = 1 - qps # y = 1 - t elif geo_name == "2_4": tqps = nm.zeros(nm.shape(qps) + (4, 2,)) # 0. tqps[..., 0, 0] = qps # x = t tqps[..., 0, 1] = 0. # y = 0 # 1. tqps[..., 1, 0] = 1 # x = 1 tqps[..., 1, 1] = qps # y = t # 2. tqps[..., 2, 0] = 1 - qps # x = 1 -t tqps[..., 2, 1] = 1 # y = 1 # 3. tqps[..., 3, 0] = 0 # x = 0 tqps[..., 3, 1] = 1 - qps # y = 1 - t elif geo_name == "3_4": # tqps = nm.zeros(nm.shape(qps) + (4, 3,)) raise NotImplementedError("Geometry {} not supported, yet" .format(geo_name)) elif geo_name == "3_8": # tqps = nm.zeros(nm.shape(qps) + (8, 3,)) raise NotImplementedError("Geometry {} not supported, yet" .format(geo_name)) else: raise NotImplementedError("Geometry {} not supported, yet" .format(geo_name)) return tqps def get_facet_qp(self): """Returns quadrature points on all facets of the reference element in array of shape (n_qp, 1 , n_el_facets, dim) Returns ------- qps : ndarray quadrature points weights : ndarray Still needs to be transformed to actual facets! """ if self.dim == 1: facet_qps = self._transform_qps_to_facets(nm.zeros((1, 1)), "1_2") weights = nm.ones((1, 1, 1)) else: qps, weights = self.integral.get_qp(cell_facet_gel_name[self.gel.name]) weights = weights[None, :, None] facet_qps = self._transform_qps_to_facets(qps, self.gel.name) return facet_qps, weights def get_facet_base(self, derivative=False, base_only=False): """ Returns values of base in facets quadrature points, data shape is a bit crazy right now: (number of qps, 1, n_el_facets, 1, n_el_nod) end for derivatine: (1, number of qps, (dim,) * derivative, n_el_facets, 1, n_el_nod) Parameters ---------- derivative: truthy or integer base_only: do not return weights Returns ------- facet_bf : ndarray values of basis functions in facet qps weights : ndarray, optionally weights of qps """ if derivative: diff = int(derivative) else: diff = 0 if diff in self.facet_bf: facet_bf = self.facet_bf[diff] whs = self.facet_whs else: qps, whs = self.get_facet_qp() ps = self.poly_space self.facet_qp = qps self.facet_whs = whs if derivative: facet_bf = nm.zeros((1,) + nm.shape(qps)[:-1] + (self.dim,) * diff + (self.n_el_nod,)) else: facet_bf = nm.zeros(nm.shape(qps)[:-1] + (1, self.n_el_nod,)) for i in range(self.n_el_facets): facet_bf[..., i, :, :] = \ ps.eval_base(qps[..., i, :], diff=diff, transform=self.basis_transform) self.facet_bf[diff] = facet_bf if base_only: return facet_bf else: return facet_bf, whs def clear_facet_neighbour_idx_cache(self, region=None): """ If region is None clear all! Parameters ---------- region : sfepy.discrete.common.region.Region If None clear all. """ if region is None: self.facet_neighbour_index = {} else: self.facet_neighbour_index.pop(region.name) def get_facet_neighbor_idx(self, region=None, eq_map=None): """ Returns index of cell neighbours sharing facet, along with local index of the facet within neighbour, also treats periodic boundary conditions i.e. plugs correct neighbours for cell on periodic boundary. Where there are no neighbours specified puts -1 instead of neighbour and facet id Cashes neighbour index in self.facet_neighbours Parameters ---------- region : sfepy.discrete.common.region.Region Main region, must contain cells. eq_map : eq_map from state variable containing information on EPBC and DG EPBC. (Default value = None) Returns ------- facet_neighbours : ndarray Shape is (n_cell, n_el_facet, 2), first value is index of the neighbouring cell, the second is index of the facet in said nb. cell. """ if region is None or eq_map is None: # HOTFIX enabling limiter to obtain connectivity data without # knowing eq_map or region if self.region.name in self.facet_neighbour_index: return self.facet_neighbour_index[self.region.name] else: raise ValueError("No facet neighbour mapping for main " + "region {}".format(self.region.name) + " cached yet, call with region and " + "eq_map first.") if region.name in self.facet_neighbour_index: return self.facet_neighbour_index[region.name] dim, n_cell, n_el_facets = self.get_region_info(region) cmesh = region.domain.mesh.cmesh cells = region.cells facet_neighbours = nm.zeros((n_cell, n_el_facets, 2), dtype=nm.int32) c2fi, c2fo = cmesh.get_incident(dim - 1, cells, dim, ret_offsets=True) for ic, o1 in enumerate(c2fo[:-1]): # loop over cells o2 = c2fo[ic + 1] # get neighbours per facet of the cell c2ci, c2co = cmesh.get_incident(dim, c2fi[o1:o2], dim - 1, ret_offsets=True) ii = cmesh.get_local_ids(c2fi[o1:o2], dim - 1, c2ci, c2co, dim) fis = nm.c_[c2ci, ii] nbrs = [] for ifa, of1 in enumerate(c2co[:-1]): # loop over facets of2 = c2co[ifa + 1] if of2 == (of1 + 1): # facet has only one cell # Surface facet. nbrs.append([-1, -1]) # c2ci[of1]) # append no neighbours else: if c2ci[of1] == cells[ic]: # do not append the cell itself nbrs.append(fis[of2 - 1]) else: nbrs.append(fis[of1]) facet_neighbours[ic, :, :] = nbrs facet_neighbours = \ self._set_fem_periodic_facet_neighbours(facet_neighbours, eq_map) facet_neighbours = \ self._set_dg_periodic_facet_neighbours(facet_neighbours, eq_map) # cache results self.facet_neighbour_index[region.name] = facet_neighbours return facet_neighbours def _set_dg_periodic_facet_neighbours(self, facet_neighbours, eq_map): """ Parameters ---------- facet_neighbours : array_like Shape is (n_cell, n_el_facet, 2), first value is index of the neighbouring cell the second is index of the facet in said nb. cell. eq_map : must contain dg_ep_bc a List with pairs of slave and master boundary cell boundary facet mapping Returns ------- facet_neighbours : ndarray Updated incidence array. """ # if eq_map. # treat DG EPBC - these are definitely preferred if eq_map.n_dg_epbc > 0 and self.gel.name not in ["1_2", "2_4", "3_6"]: raise ValueError( "Periodic boundary conditions not supported " + "for geometry {} elements.".format(self.gel.name)) dg_epbc = eq_map.dg_epbc for master_bc2bfi, slave_bc2bfi in dg_epbc: # set neighbours of periodic cells to one another facet_neighbours[master_bc2bfi[:, 0], master_bc2bfi[:, 1], 0] = \ slave_bc2bfi[:, 0] facet_neighbours[slave_bc2bfi[:, 0], slave_bc2bfi[:, 1], 0] = \ master_bc2bfi[:, 0] # set neighbours facets facet_neighbours[slave_bc2bfi[:, 0], slave_bc2bfi[:, 1], 1] = \ master_bc2bfi[:, 1] facet_neighbours[master_bc2bfi[:, 0], master_bc2bfi[:, 1], 1] =\ slave_bc2bfi[:, 1] return facet_neighbours def _set_fem_periodic_facet_neighbours(self, facet_neighbours, eq_map): """Maybe remove after DG EPBC revision in self.get_coor Parameters ---------- facet_neighbours : array_like Shape is (n_cell, n_el_facet, 2), first value is index of the neighbouring cell the second is index of the facet in said nb. cell. eq_map : eq_map from state variable containing information on EPBC and DG EPBC. Returns ------- facet_neighbours : ndarray Updated incidence array. """ # treat classical FEM EPBCs - we need to correct neighbours if eq_map.n_epbc > 0: # set neighbours of periodic cells to one another mcells = nm.unique(self.dofs2cells[eq_map.master]) scells = nm.unique(self.dofs2cells[eq_map.slave]) mcells_facets = nm.array( nm.where(facet_neighbours[mcells] == -1))[1, 0] # facets mcells scells_facets = nm.array( nm.where(facet_neighbours[scells] == -1))[1, 0] # facets scells # [1, 0] above, first we need second axis to get axis on which # facet indices are stored, second we drop axis with neighbour # local facet index, # # for multiple s/mcells this will have to be # something like 1 + 2*nm.arange(len(mcells)) - to skip double # entries for -1 tags in neighbours and neighbour local facet idx # set neighbours of mcells to scells facet_neighbours[mcells, mcells_facets, 0] = scells # set neighbour facets to facets of scell missing neighbour facet_neighbours[ mcells, mcells_facets, 1] = scells_facets # we do not need to distinguish EBC and EPBC cells, EBC overwrite # EPBC, we only need to fix shapes # set neighbours of scells to mcells facet_neighbours[scells, scells_facets, 0] = mcells # set neighbour facets to facets of mcell missing neighbour0 facet_neighbours[ scells, scells_facets, 1] = mcells_facets return facet_neighbours @staticmethod def get_region_info(region): """ Extracts information about region needed in various methods of DGField Parameters ---------- region : sfepy.discrete.common.region.Region Returns ------- dim, n_cell, n_el_facets """ if not region.has_cells(): raise ValueError("Region {} has no cells".format(region.name)) n_cell = region.get_n_cells() dim = region.tdim gel = get_gel(region) n_el_facets = dim + 1 if gel.is_simplex else 2 ** dim return dim, n_cell, n_el_facets def get_both_facet_state_vals(self, state, region, derivative=None, reduce_nod=True): """Computes values of the variable represented by dofs in quadrature points located at facets, returns both values - inner and outer, along with weights. Parameters ---------- state : state variable containing BC info region : sfepy.discrete.common.region.Region derivative : compute derivative if truthy, compute n-th derivative if a number (Default value = None) reduce_nod : if False DOES NOT sum nodes into values at QPs (Default value = True) Returns ------- inner_facet_values (n_cell, n_el_facets, n_qp), outer facet values (n_cell, n_el_facets, n_qp), weights, if derivative is True: inner_facet_values (n_cell, n_el_facets, dim, n_qp), outer_facet values (n_cell, n_el_facets, dim, n_qp) """ if derivative: diff = int(derivative) else: diff = 0 unreduce_nod = int(not reduce_nod) inner_base_vals, outer_base_vals, whs = \ self.get_both_facet_base_vals(state, region, derivative=derivative) dofs = self.unravel_sol(state.data[0]) n_qp = whs.shape[-1] outputs_shape = (self.n_cell, self.n_el_facets) + \ (self.n_el_nod,) * unreduce_nod + \ (self.dim,) * diff + \ (n_qp,) inner_facet_vals = nm.zeros(outputs_shape) if unreduce_nod: inner_facet_vals[:] = nm.einsum('id...,idf...->ifd...', dofs, inner_base_vals) else: inner_facet_vals[:] = nm.einsum('id...,id...->i...', dofs, inner_base_vals) per_facet_neighbours = self.get_facet_neighbor_idx(region, state.eq_map) outer_facet_vals = nm.zeros(outputs_shape) for facet_n in range(self.n_el_facets): if unreduce_nod: outer_facet_vals[:, facet_n, :] = \ nm.einsum('id...,id...->id...', dofs[per_facet_neighbours[:, facet_n, 0]], outer_base_vals[:, :, facet_n]) else: outer_facet_vals[:, facet_n, :] = \ nm.einsum('id...,id...->i...', dofs[per_facet_neighbours[:, facet_n, 0]], outer_base_vals[:, :, facet_n]) boundary_cells = nm.array(nm.where(per_facet_neighbours[:, :, 0] < 0)).T outer_facet_vals[boundary_cells[:, 0], boundary_cells[:, 1]] = 0.0 # TODO detect and print boundary cells without defined BCs? for ebc, ebc_vals in zip(state.eq_map.dg_ebc.get(diff, []), state.eq_map.dg_ebc_val.get(diff, [])): if unreduce_nod: raise NotImplementedError( "Unreduced DOFs are not available for boundary " + "outerfacets") outer_facet_vals[ebc[:, 0], ebc[:, 1], :] = \ nm.einsum("id,id...->id...", ebc_vals, inner_base_vals[0, :, ebc[:, 1]]) else: # fix flipping qp order to accomodate for # opposite facet orientation of neighbours outer_facet_vals[ebc[:, 0], ebc[:, 1], :] = ebc_vals[:, ::-1] # flip outer_facet_vals moved to get_both_facet_base_vals return inner_facet_vals, outer_facet_vals, whs def get_both_facet_base_vals(self, state, region, derivative=None): """Returns values of the basis function in quadrature points on facets broadcasted to all cells inner to the element as well as outer ones along with weights for the qps broadcasted and transformed to elements. Contains quick fix to flip facet QPs for right integration order. Parameters ---------- state : used to get EPBC info region : sfepy.discrete.common.region.Region for connectivity derivative : if u need derivative (Default value = None) Returns ------- outer_facet_base_vals: inner_facet_base_vals: shape (n_cell, n_el_nod, n_el_facet, n_qp) or (n_cell, n_el_nod, n_el_facet, dim, n_qp) when derivative is True or 1 whs: shape (n_cell, n_el_facet, n_qp) """ if derivative: diff = int(derivative) else: diff = 0 facet_bf, whs = self.get_facet_base(derivative=derivative) n_qp = nm.shape(whs)[1] facet_vols = self.get_facet_vols(region) whs = facet_vols * whs[None, :, :, 0] base_shape = (self.n_cell, self.n_el_nod, self.n_el_facets) + \ (self.dim,) * diff + \ (n_qp,) inner_facet_base_vals = nm.zeros(base_shape) outer_facet_base_vals = nm.zeros(base_shape) if derivative: inner_facet_base_vals[:] = facet_bf[0, :, 0, :, :, :]\ .swapaxes(-2, -3).T else: inner_facet_base_vals[:] = facet_bf[:, 0, :, 0, :].T per_facet_neighbours = self.get_facet_neighbor_idx(region, state.eq_map) # numpy prepends shape resulting from multiple # indexing before remaining shape if derivative: outer_facet_base_vals[:] = \ inner_facet_base_vals[0, :, per_facet_neighbours[:, :, 1]]\ .swapaxes(-3, -4) else: outer_facet_base_vals[:] = \ inner_facet_base_vals[0, :, per_facet_neighbours[:, :, 1]]\ .swapaxes(-2, -3) # fix to flip facet QPs for right integration order return inner_facet_base_vals, outer_facet_base_vals[..., ::-1], whs def clear_normals_cache(self, region=None): """Clears normals cache for given region or all regions. Parameters ---------- region : sfepy.discrete.common.region.Region region to clear cache or None to clear all """ if region is None: self.normals_cache = {} else: if isinstance(region, str): self.normals_cache.pop(region) else: self.normals_cache.pop(region.name) def get_cell_normals_per_facet(self, region): """Caches results, use clear_normals_cache to clear the cache. Parameters ---------- region: sfepy.discrete.common.region.Region Main region, must contain cells. Returns ------- normals: ndarray normals of facets in array of shape (n_cell, n_el_facets, dim) """ if region.name in self.normals_cache: return self.normals_cache[region.name] dim, n_cell, n_el_facets = self.get_region_info(region) cmesh = region.domain.mesh.cmesh normals = cmesh.get_facet_normals() normals_out = nm.zeros((n_cell, n_el_facets, dim)) c2f = cmesh.get_conn(dim, dim - 1) for ic, o1 in enumerate(c2f.offsets[:-1]): o2 = c2f.offsets[ic + 1] for ifal, ifa in enumerate(c2f.indices[o1:o2]): normals_out[ic, ifal] = normals[o1 + ifal] self.normals_cache[region.name] = normals_out return normals_out def clear_facet_vols_cache(self, region=None): """Clears facet volume cache for given region or all regions. Parameters ---------- region : sfepy.discrete.common.region.Region region to clear cache or None to clear all """ if region is None: self.facet_vols_cache = {} else: if isinstance(region, str): self.facet_vols_cache.pop(region) else: self.facet_vols_cache.pop(region.name) def get_facet_vols(self, region): """Caches results, use clear_facet_vols_cache to clear the cache Parameters ---------- region : sfepy.discrete.common.region.Region Returns ------- vols_out: ndarray volumes of the facets by cells shape (n_cell, n_el_facets, 1) """ if region.name in self.facet_vols_cache: return self.facet_vols_cache[region.name] dim, n_cell, n_el_facets = self.get_region_info(region) cmesh = region.domain.mesh.cmesh if dim == 1: vols = nm.ones((cmesh.num[0], 1)) else: vols = cmesh.get_volumes(dim - 1)[:, None] vols_out = nm.zeros((n_cell, n_el_facets, 1)) c2f = cmesh.get_conn(dim, dim - 1) for ic, o1 in enumerate(c2f.offsets[:-1]): o2 = c2f.offsets[ic + 1] for ifal, ifa in enumerate(c2f.indices[o1:o2]): vols_out[ic, ifal] = vols[ifa] self.facet_vols_cache[region.name] = vols_out return vols_out def get_data_shape(self, integral, integration='volume', region_name=None): """Returns data shape (n_nod, n_qp, self.gel.dim, self.n_el_nod) Parameters ---------- integral : integral used integration : 'volume' is only supported value (Default value = 'volume') region_name : not used (Default value = None) Returns ------- data_shape : tuple """ if integration in ('volume',): # from FEField.get_data_shape() _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (self.n_cell, n_qp, self.gel.dim, self.n_el_nod) # econn.shape[1] == n_el_nod i.e. number nod in element else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_econn(self, conn_type, region, is_trace=False, integration=None): """Getter for econn Parameters ---------- conn_type : string or Struct 'volume' is only supported region : sfepy.discrete.common.region.Region is_trace : ignored (Default value = False) integration : ignored (Default value = None) Returns ------- econn : ndarray connectivity information """ ct = conn_type.type if isinstance(conn_type, Struct) else conn_type if ct == 'volume': if region.name == self.region.name: conn = self.econn else: raise ValueError("Bad region for the field") else: raise ValueError('unknown connectivity type! (%s)' % ct) return conn def setup_extra_data(self, geometry, info, is_trace): """This is called in create_adof_conns(conn_info, var_indx=None, active_only=True, verbose=True) for each variable but has no effect. Parameters ---------- geometry : ignored info : set to self.info is_trace : set to self.trace """ # placeholder, what is this used for? # dct = info.dc_type.type self.info = info self.is_trace = is_trace def get_dofs_in_region(self, region, merge=True): """Return indices of DOFs that belong to the given region. Not Used in BC treatment Parameters ---------- region : sfepy.discrete.common.region.Region merge : bool merge dof tuple into one numpy array, default True Returns ------- dofs : ndarray """ dofs = [] if region.has_cells(): # main region or its part els = nm.ravel(self.bubble_remap[region.cells]) eldofs = self.bubble_dofs[els[els >= 0]] dofs.append(eldofs) else: # return indices of cells adjacent to boundary facets dim = self.dim cmesh = region.domain.mesh.cmesh bc_cells = cmesh.get_incident(dim, region.facets, dim - 1) bc_dofs = self.bubble_dofs[bc_cells] dofs.append(bc_dofs) if merge: dofs = nm.concatenate(dofs) return dofs def get_bc_facet_idx(self, region): """Caches results in self.boundary_facet_local_idx Parameters ---------- region : sfepy.discrete.common.region.Region surface region defining BCs Returns ------- bc2bfi : ndarray index of cells on boundary along with corresponding facets """ if region.name in self.boundary_facet_local_idx: return self.boundary_facet_local_idx[region.name] bc2bfi = region.get_facet_indices() self.boundary_facet_local_idx[region.name] = bc2bfi return bc2bfi def create_mapping(self, region, integral, integration, return_mapping=True): """Creates and returns mapping Parameters ---------- region : sfepy.discrete.common.region.Region integral : Integral integration : str 'volume' is only accepted option return_mapping : default True (Default value = True) Returns ------- mapping : VolumeMapping """ domain = self.domain coors = domain.get_mesh_coors(actual=True) dconn = domain.get_conn() # from FEField if integration == 'volume': qp = self.get_qp('v', integral) # qp = self.integral.get_qp(self.gel.name) iels = region.get_cells() geo_ps = self.gel.poly_space ps = self.poly_space bf = self.get_base('v', 0, integral, iels=iels) conn = nm.take(dconn, iels.astype(nm.int32), axis=0) mapping = VolumeMapping(coors, conn, poly_space=geo_ps) vg = mapping.get_mapping(qp.vals, qp.weights, poly_space=ps, ori=self.ori, transform=self.basis_transform) out = vg else: raise ValueError('unsupported integration geometry type: %s' % integration) if out is not None: # Store the integral used. out.integral = integral out.qp = qp out.ps = ps # Update base. out.bf[:] = bf if return_mapping: out = (out, mapping) return out def set_dofs(self, fun=0.0, region=None, dpn=None, warn=None): """Compute projection of fun into the basis, alternatively set DOFs directly to provided value or values either in main volume region or in boundary region. Parameters ---------- fun : callable, scalar or array corresponding to dofs (Default value = 0.0) region : sfepy.discrete.common.region.Region region to set DOFs on (Default value = None) dpn : number of dofs per element (Default value = None) warn : (Default value = None) Returns ------- nods : ndarray vals : ndarray """ if region is None: region = self.region return self.set_cell_dofs(fun, region, dpn, warn) elif region.has_cells(): return self.set_cell_dofs(fun, region, dpn, warn) elif region.kind_tdim == self.dim - 1: nods, vals = self.set_facet_dofs(fun, region, dpn, warn) return nods, vals def set_cell_dofs(self, fun=0.0, region=None, dpn=None, warn=None): """ Compute projection of fun onto the basis, in main region, alternatively set DOFs directly to provided value or values Parameters ---------- fun : callable, scallar or array corresponding to dofs (Default value = 0.0) region : sfepy.discrete.common.region.Region region to set DOFs on (Default value = None) dpn : number of dofs per element (Default value = None) warn : not used (Default value = None) Returns ------- nods : ndarray vals : ndarray """ aux = self.get_dofs_in_region(region) nods = nm.unique(nm.hstack(aux)) if nm.isscalar(fun): vals = nm.zeros(aux.shape) vals[:, 0] = fun vals = nm.hstack(vals) elif isinstance(fun, nm.ndarray): # useful for testing, allows to pass complete array of dofs as IC if nm.shape(fun) == nm.shape(nods): vals = fun elif callable(fun): qp, weights = self.integral.get_qp(self.gel.name) coors = self.mapping.get_physical_qps(qp) base_vals_qp = self.poly_space.eval_base(qp)[:, 0, :] # this drops redundant axis that is returned by eval_base due to # consistency with derivatives # left hand, so far only orthogonal basis # for legendre base this can be calculated exactly # in 1D it is: 1 / (2 * nm.arange(self.n_el_nod) + 1) lhs_diag = nm.einsum("q,q...->...", weights, base_vals_qp ** 2) rhs_vec = nm.einsum("q,q...,iq...->i...", weights, base_vals_qp, fun(coors)) vals = (rhs_vec / lhs_diag) # plot for 1D # from utils.visualizer import plot1D_legendre_dofs, reconstruct # _legendre_dofs # import matplotlib.pyplot as plt # plot1D_legendre_dofs(self.domain.mesh.coors, (vals,), fun) # ww, xx = reconstruct_legendre_dofs(self.domain.mesh.coors, 1, # vals.T[..., None, None]) # plt.plot(xx, ww[:, 0], label="reconstructed dofs") # plt.show() return nods, vals def set_facet_dofs(self, fun, region, dpn, warn): """Compute projection of fun onto the basis on facets, alternatively set DOFs directly to provided value or values Parameters ---------- fun : callable, scalar or array corresponding to dofs region : sfepy.discrete.common.region.Region region to set DOFs on dpn : int number of dofs per element warn : not used Returns ------- nods : ndarray vals : ndarray """ raise NotImplementedError( "Setting facet DOFs is not supported with DGField, " + "use values at qp directly. " + "This is usually result of using ebc instead of dgebc") aux = self.get_dofs_in_region(region) nods = nm.unique(nm.hstack(aux)) if nm.isscalar(fun): vals = nm.zeros(aux.shape) vals[:, 0] = fun vals = nm.hstack(vals) elif isinstance(fun, nm.ndarray): assert_(len(fun) == dpn) vals = nm.zeros(aux.shape) vals[:, 0] = nm.repeat(fun, vals.shape[0]) elif callable(fun): vals = nm.zeros(aux.shape) # set zero DOF to value fun, set other DOFs to zero # get facets QPs qp, weights = self.get_facet_qp() weights = weights[0, :, 0] qp = qp[:, 0, :, :] # get facets weights ? # get coors bc2bfi = self.get_bc_facet_idx(region) coors = self.mapping.get_physical_qps(qp) # get_physical_qps returns data in strange format, swapping # some axis and flipping qps order bcoors = coors[bc2bfi[:, 1], ::-1, bc2bfi[:, 0], :] # get facet basis vals base_vals_qp = self.poly_space.eval_base(qp)[:, 0, 0, :] # solve for boundary cell DOFs bc_val = fun(bcoors) # this returns singular matrix - projection on the boundary should # be into facet dim space #lhs = nm.einsum("q,qd,qc->dc", weights, base_vals_qp, base_vals_qp) # inv_lhs = nm.linalg.inv(lhs) # rhs_vec = nm.einsum("q,q...,iq...->i...", # weights, base_vals_qp, bc_val) return nods, vals def get_bc_facet_values(self, fun, region, ret_coors=False, diff=0): """Returns values of fun in facet QPs of the region Parameters ---------- diff: derivative 0 or 1 supported fun: Function value or values to set qps values to region : sfepy.discrete.common.region.Region boundary region ret_coors: default False, Return physical coors of qps in shape (n_cell, n_qp, dim). Returns ------- vals : ndarray In shape (n_cell,) + (self.dim,) * diff + (n_qp,) """ if region.has_cells(): raise NotImplementedError( "Region {} has cells and can't be used as boundary region". format(region)) # get facets QPs qp, weights = self.get_facet_qp() weights = weights[0, :, 0] qp = qp[:, 0, :, :] n_qp = qp.shape[0] # get facets weights ? # get physical coors bc2bfi = self.get_bc_facet_idx(region) n_cell = bc2bfi.shape[0] coors = self.mapping.get_physical_qps(qp) # get_physical_qps returns data in strange format, # swapping some axis and flipping qps order # to get coors in shape (n_facet, n_qp, n_cell, dim) if len(coors.shape) == 3: coors = coors[:, None, :, :] # add axis for qps when it is missing coors = coors.swapaxes(0, 2) bcoors = coors[bc2bfi[:, 1], ::-1, bc2bfi[:, 0], :] diff_shape = (self.dim,) * diff output_shape = (n_cell,) + diff_shape + (n_qp,) vals = nm.zeros(output_shape) # we do not need last axis of coors, values are scalars if nm.isscalar(fun): if sum(diff_shape) > 1: output(("Warning: Setting gradient of shape {} " "in region {} with scalar value {}") .format(diff_shape, region.name, fun)) vals[:] = fun elif isinstance(fun, nm.ndarray): try: vals[:] = fun[:, None] except ValueError: raise ValueError(("Provided values of shape {} could not" + " be used to set BC qps of shape {} in " + "region {}") .format(fun.shape, vals.shape, region.name)) elif callable(fun): # get boundary values vals[:] = fun(bcoors) if ret_coors: return bcoors, vals return vals def get_nodal_values(self, dofs, region, ref_nodes=None): """Computes nodal representation of the DOFs Parameters --------- dofs : array_like dofs to transform to nodes region : ignored ref_nodes: reference node to use instead of default qps Parameters ---------- dofs : array_like region : Region ref_nodes : array_like (Default value = None) Returns ------- nodes : ndarray nodal_vals : ndarray """ if ref_nodes is None: # poly_space could provide special nodes ref_nodes = self.get_qp('v', self.integral).vals base_vals_node = self.poly_space.eval_base(ref_nodes)[:, 0, :] dofs = self.unravel_sol(dofs[:, 0]) nodal_vals = nm.sum(dofs * base_vals_node.T, axis=1) nodes = self.mapping.get_physical_qps(ref_nodes) # import matplotlib.pyplot as plt # plt.plot(nodes[:, 0], nodal_vals) # plt.show() return nodes, nodal_vals def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """Converts the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). For 1D puts DOFs into vairables u_modal{0} ... u_modal{n}, where n = approx_order and marks them for writing as cell data. For 2+D puts dofs into name_cell_nodes and creates sturct with: mode = "cell_nodes", data and iterpolation scheme. Also get node values and adds them to dictionary as cell_nodes Parameters ---------- dofs : ndarray, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. var_name : str The variable name corresponding to `dofs`. dof_names : tuple of str The names of DOF components. (Default value = None) key : str, optional The key to be used in the output dictionary instead of the variable name. (Default value = None) extend : bool, not used Extend the DOF values to cover the whole domain. (Default value = True) fill_value : float or complex, not used The value used to fill the missing DOF values if `extend` is True. (Default value = None) linearization : Struct or None, not used The linearization configuration for higher order approximations. (Default value = None) Returns ------- out : dict """ out = {} udofs = self.unravel_sol(dofs) name = var_name if key is None else key if self.dim == 1: for i in range(self.n_el_nod): out[name + "_modal{}".format(i)] = \
Struct(mode="cell", data=udofs[:, i, None, None])
sfepy.base.base.Struct
from __future__ import absolute_import input_name = '../examples/multi_physics/piezo_elasticity.py' output_name = 'test_piezo_elasticity.vtk' from tests_basic import TestInput class Test( TestInput ): def from_conf( conf, options ): return TestInput.from_conf( conf, options, cls = Test ) from_conf = staticmethod( from_conf ) def test_ebc( self ): import numpy as nm from sfepy.discrete import Problem pb =
Problem.from_conf(self.test_conf)
sfepy.discrete.Problem.from_conf
""" Finite element reference mappings. """ import numpy as nm from sfepy import Config from sfepy.base.base import get_default, output from sfepy.base.mem_usage import raise_if_too_large from sfepy.discrete.common.mappings import Mapping from sfepy.discrete.common.extmods.mappings import CMapping from sfepy.discrete import PolySpace class FEMapping(Mapping): """ Base class for finite element mappings. """ def __init__(self, coors, conn, poly_space=None, gel=None, order=1): self.coors = coors self.conn = conn try: nm.take(self.coors, self.conn) except IndexError: output('coordinates shape: %s' % list(coors.shape)) output('connectivity: min: %d, max: %d' % (conn.min(), conn.max())) msg = 'incompatible connectivity and coordinates (see above)' raise IndexError(msg) self.n_el, self.n_ep = conn.shape self.dim = self.coors.shape[1] if poly_space is None: poly_space = PolySpace.any_from_args(None, gel, order, base='lagrange', force_bubble=False) self.poly_space = poly_space self.indices = slice(None) def get_geometry(self): """ Return reference element geometry as a GeometryElement instance. """ return self.poly_space.geometry def get_base(self, coors, diff=False): """ Get base functions or their gradient evaluated in given coordinates. """ bf = self.poly_space.eval_base(coors, diff=diff) return bf def get_physical_qps(self, qp_coors): """ Get physical quadrature points corresponding to given reference element quadrature points. Returns ------- qps : array The physical quadrature points ordered element by element, i.e. with shape (n_el, n_qp, dim). """ bf = self.get_base(qp_coors) qps = nm.dot(nm.atleast_2d(bf.squeeze()), self.coors[self.conn]) # Reorder so that qps are really element by element. qps = nm.ascontiguousarray(nm.swapaxes(qps, 0, 1)) return qps class VolumeMapping(FEMapping): """ Mapping from reference domain to physical domain of the same space dimension. """ def get_mapping(self, qp_coors, weights, poly_space=None, ori=None, transform=None): """ Get the mapping for given quadrature points, weights, and polynomial space. Returns ------- cmap : CMapping instance The volume mapping. """ poly_space =
get_default(poly_space, self.poly_space)
sfepy.base.base.get_default
""" Finite element reference mappings. """ import numpy as nm from sfepy import Config from sfepy.base.base import get_default, output from sfepy.base.mem_usage import raise_if_too_large from sfepy.discrete.common.mappings import Mapping from sfepy.discrete.common.extmods.mappings import CMapping from sfepy.discrete import PolySpace class FEMapping(Mapping): """ Base class for finite element mappings. """ def __init__(self, coors, conn, poly_space=None, gel=None, order=1): self.coors = coors self.conn = conn try: nm.take(self.coors, self.conn) except IndexError: output('coordinates shape: %s' % list(coors.shape)) output('connectivity: min: %d, max: %d' % (conn.min(), conn.max())) msg = 'incompatible connectivity and coordinates (see above)' raise IndexError(msg) self.n_el, self.n_ep = conn.shape self.dim = self.coors.shape[1] if poly_space is None: poly_space = PolySpace.any_from_args(None, gel, order, base='lagrange', force_bubble=False) self.poly_space = poly_space self.indices = slice(None) def get_geometry(self): """ Return reference element geometry as a GeometryElement instance. """ return self.poly_space.geometry def get_base(self, coors, diff=False): """ Get base functions or their gradient evaluated in given coordinates. """ bf = self.poly_space.eval_base(coors, diff=diff) return bf def get_physical_qps(self, qp_coors): """ Get physical quadrature points corresponding to given reference element quadrature points. Returns ------- qps : array The physical quadrature points ordered element by element, i.e. with shape (n_el, n_qp, dim). """ bf = self.get_base(qp_coors) qps = nm.dot(nm.atleast_2d(bf.squeeze()), self.coors[self.conn]) # Reorder so that qps are really element by element. qps = nm.ascontiguousarray(nm.swapaxes(qps, 0, 1)) return qps class VolumeMapping(FEMapping): """ Mapping from reference domain to physical domain of the same space dimension. """ def get_mapping(self, qp_coors, weights, poly_space=None, ori=None, transform=None): """ Get the mapping for given quadrature points, weights, and polynomial space. Returns ------- cmap : CMapping instance The volume mapping. """ poly_space = get_default(poly_space, self.poly_space) bf_g = self.get_base(qp_coors, diff=True) ebf_g = poly_space.eval_base(qp_coors, diff=True, ori=ori, force_axis=True, transform=transform) size = ebf_g.nbytes * self.n_el site_config =
Config()
sfepy.Config
""" Finite element reference mappings. """ import numpy as nm from sfepy import Config from sfepy.base.base import get_default, output from sfepy.base.mem_usage import raise_if_too_large from sfepy.discrete.common.mappings import Mapping from sfepy.discrete.common.extmods.mappings import CMapping from sfepy.discrete import PolySpace class FEMapping(Mapping): """ Base class for finite element mappings. """ def __init__(self, coors, conn, poly_space=None, gel=None, order=1): self.coors = coors self.conn = conn try: nm.take(self.coors, self.conn) except IndexError: output('coordinates shape: %s' % list(coors.shape)) output('connectivity: min: %d, max: %d' % (conn.min(), conn.max())) msg = 'incompatible connectivity and coordinates (see above)' raise IndexError(msg) self.n_el, self.n_ep = conn.shape self.dim = self.coors.shape[1] if poly_space is None: poly_space = PolySpace.any_from_args(None, gel, order, base='lagrange', force_bubble=False) self.poly_space = poly_space self.indices = slice(None) def get_geometry(self): """ Return reference element geometry as a GeometryElement instance. """ return self.poly_space.geometry def get_base(self, coors, diff=False): """ Get base functions or their gradient evaluated in given coordinates. """ bf = self.poly_space.eval_base(coors, diff=diff) return bf def get_physical_qps(self, qp_coors): """ Get physical quadrature points corresponding to given reference element quadrature points. Returns ------- qps : array The physical quadrature points ordered element by element, i.e. with shape (n_el, n_qp, dim). """ bf = self.get_base(qp_coors) qps = nm.dot(nm.atleast_2d(bf.squeeze()), self.coors[self.conn]) # Reorder so that qps are really element by element. qps = nm.ascontiguousarray(nm.swapaxes(qps, 0, 1)) return qps class VolumeMapping(FEMapping): """ Mapping from reference domain to physical domain of the same space dimension. """ def get_mapping(self, qp_coors, weights, poly_space=None, ori=None, transform=None): """ Get the mapping for given quadrature points, weights, and polynomial space. Returns ------- cmap : CMapping instance The volume mapping. """ poly_space = get_default(poly_space, self.poly_space) bf_g = self.get_base(qp_coors, diff=True) ebf_g = poly_space.eval_base(qp_coors, diff=True, ori=ori, force_axis=True, transform=transform) size = ebf_g.nbytes * self.n_el site_config = Config() raise_if_too_large(size, site_config.refmap_memory_factor()) flag = (ori is not None) or (ebf_g.shape[0] > 1) cmap = CMapping(self.n_el, qp_coors.shape[0], self.dim, poly_space.n_nod, mode='volume', flag=flag) cmap.describe(self.coors, self.conn, bf_g, ebf_g, weights) return cmap class SurfaceMapping(FEMapping): """ Mapping from reference domain to physical domain of the space dimension higher by one. """ def set_basis_indices(self, indices): """ Set indices to cell-based basis that give the facet-based basis. """ self.indices = indices def get_base(self, coors, diff=False): """ Get base functions or their gradient evaluated in given coordinates. """ bf = self.poly_space.eval_base(coors, diff=diff) ii = max(self.dim - 1, 1) return nm.ascontiguousarray(bf[..., :ii:, self.indices]) def get_mapping(self, qp_coors, weights, poly_space=None, mode='surface'): """ Get the mapping for given quadrature points, weights, and polynomial space. Returns ------- cmap : CMapping instance The surface mapping. """ poly_space =
get_default(poly_space, self.poly_space)
sfepy.base.base.get_default
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` boundary conditions as well as `edge direction` boundary conditions together with Navier or slip boundary conditions. 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. Optionally, Dirichlet boundary conditions can be applied on the inlet, see the code below. The mesh is created by ``gen_block_mesh()`` function - try different mesh dimensions and resolutions below. For large meshes use the ``'ls_i'`` linear solver - PETSc + petsc4py is needed in that case. """ import numpy as nm from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.homogenization.utils import define_box_regions # Mesh dimensions. dims = nm.array([3, 1, 0.5]) # Mesh resolution: increase to improve accuracy. shape = [11, 15, 15] 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` boundary conditions as well as `edge direction` boundary conditions together with Navier or slip boundary conditions. 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. Optionally, Dirichlet boundary conditions can be applied on the inlet, see the code below. The mesh is created by ``gen_block_mesh()`` function - try different mesh dimensions and resolutions below. For large meshes use the ``'ls_i'`` linear solver - PETSc + petsc4py is needed in that case. """ import numpy as nm from sfepy.discrete.fem.meshio import UserMeshIO from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.homogenization.utils import define_box_regions # Mesh dimensions. dims = nm.array([3, 1, 0.5]) # Mesh resolution: increase to improve accuracy. shape = [11, 15, 15] 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
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf =
get_default(conf, self.conf)
sfepy.base.base.get_default
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m =
get_default(mtx_m, self.mtx_m)
sfepy.base.base.get_default
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d =
get_default(mtx_d, self.mtx_d)
sfepy.base.base.get_default
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k =
get_default(mtx_k, self.mtx_k)
sfepy.base.base.get_default
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs =
get_default(n_eigs, self.n_eigs)
sfepy.base.base.get_default
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs = get_default(n_eigs, self.n_eigs) eigenvectors =
get_default(eigenvectors, self.eigenvectors)
sfepy.base.base.get_default
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs = get_default(n_eigs, self.n_eigs) eigenvectors = get_default(eigenvectors, self.eigenvectors) status =
get_default(status, self.status)
sfepy.base.base.get_default
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs = get_default(n_eigs, self.n_eigs) eigenvectors = get_default(eigenvectors, self.eigenvectors) status = get_default(status, self.status) result = call(self, mtx_m, mtx_d, mtx_k, n_eigs, eigenvectors, status, conf, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed return result return _standard_call class LQuadraticEVPSolver(QuadraticEVPSolver): """ Quadratic eigenvalue problem solver based on the problem linearization. (w^2 M + w D + K) x = 0. """ name = 'eig.qevp' _parameters = [ ('method', "{'companion', 'cholesky'}", 'companion', False, 'The linearization method.'), ('solver', 'dict', {'kind': 'eig.scipy', 'method': 'eig'}, False, """The configuration of an eigenvalue solver for the linearized problem (A - w B) x = 0."""), ('mode', "{'normal', 'inverted'}", 'normal', False, 'Solve either A - w B (normal), or B - 1/w A (inverted).'), ('debug', 'bool', False, False, 'If True, print debugging information.'), ] @standard_call def __call__(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None): if conf.debug: ssym = status['matrix_info'] = {} ssym['|M - M^T|'] =
max_diff_csr(mtx_m, mtx_m.T)
sfepy.linalg.utils.max_diff_csr
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs = get_default(n_eigs, self.n_eigs) eigenvectors = get_default(eigenvectors, self.eigenvectors) status = get_default(status, self.status) result = call(self, mtx_m, mtx_d, mtx_k, n_eigs, eigenvectors, status, conf, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed return result return _standard_call class LQuadraticEVPSolver(QuadraticEVPSolver): """ Quadratic eigenvalue problem solver based on the problem linearization. (w^2 M + w D + K) x = 0. """ name = 'eig.qevp' _parameters = [ ('method', "{'companion', 'cholesky'}", 'companion', False, 'The linearization method.'), ('solver', 'dict', {'kind': 'eig.scipy', 'method': 'eig'}, False, """The configuration of an eigenvalue solver for the linearized problem (A - w B) x = 0."""), ('mode', "{'normal', 'inverted'}", 'normal', False, 'Solve either A - w B (normal), or B - 1/w A (inverted).'), ('debug', 'bool', False, False, 'If True, print debugging information.'), ] @standard_call def __call__(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None): if conf.debug: ssym = status['matrix_info'] = {} ssym['|M - M^T|'] = max_diff_csr(mtx_m, mtx_m.T) ssym['|D - D^T|'] =
max_diff_csr(mtx_d, mtx_d.T)
sfepy.linalg.utils.max_diff_csr
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs = get_default(n_eigs, self.n_eigs) eigenvectors = get_default(eigenvectors, self.eigenvectors) status = get_default(status, self.status) result = call(self, mtx_m, mtx_d, mtx_k, n_eigs, eigenvectors, status, conf, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed return result return _standard_call class LQuadraticEVPSolver(QuadraticEVPSolver): """ Quadratic eigenvalue problem solver based on the problem linearization. (w^2 M + w D + K) x = 0. """ name = 'eig.qevp' _parameters = [ ('method', "{'companion', 'cholesky'}", 'companion', False, 'The linearization method.'), ('solver', 'dict', {'kind': 'eig.scipy', 'method': 'eig'}, False, """The configuration of an eigenvalue solver for the linearized problem (A - w B) x = 0."""), ('mode', "{'normal', 'inverted'}", 'normal', False, 'Solve either A - w B (normal), or B - 1/w A (inverted).'), ('debug', 'bool', False, False, 'If True, print debugging information.'), ] @standard_call def __call__(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None): if conf.debug: ssym = status['matrix_info'] = {} ssym['|M - M^T|'] = max_diff_csr(mtx_m, mtx_m.T) ssym['|D - D^T|'] = max_diff_csr(mtx_d, mtx_d.T) ssym['|K - K^T|'] =
max_diff_csr(mtx_k, mtx_k.T)
sfepy.linalg.utils.max_diff_csr
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs = get_default(n_eigs, self.n_eigs) eigenvectors = get_default(eigenvectors, self.eigenvectors) status = get_default(status, self.status) result = call(self, mtx_m, mtx_d, mtx_k, n_eigs, eigenvectors, status, conf, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed return result return _standard_call class LQuadraticEVPSolver(QuadraticEVPSolver): """ Quadratic eigenvalue problem solver based on the problem linearization. (w^2 M + w D + K) x = 0. """ name = 'eig.qevp' _parameters = [ ('method', "{'companion', 'cholesky'}", 'companion', False, 'The linearization method.'), ('solver', 'dict', {'kind': 'eig.scipy', 'method': 'eig'}, False, """The configuration of an eigenvalue solver for the linearized problem (A - w B) x = 0."""), ('mode', "{'normal', 'inverted'}", 'normal', False, 'Solve either A - w B (normal), or B - 1/w A (inverted).'), ('debug', 'bool', False, False, 'If True, print debugging information.'), ] @standard_call def __call__(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None): if conf.debug: ssym = status['matrix_info'] = {} ssym['|M - M^T|'] = max_diff_csr(mtx_m, mtx_m.T) ssym['|D - D^T|'] = max_diff_csr(mtx_d, mtx_d.T) ssym['|K - K^T|'] = max_diff_csr(mtx_k, mtx_k.T) ssym['|M - M^H|'] =
max_diff_csr(mtx_m, mtx_m.H)
sfepy.linalg.utils.max_diff_csr
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs = get_default(n_eigs, self.n_eigs) eigenvectors = get_default(eigenvectors, self.eigenvectors) status = get_default(status, self.status) result = call(self, mtx_m, mtx_d, mtx_k, n_eigs, eigenvectors, status, conf, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed return result return _standard_call class LQuadraticEVPSolver(QuadraticEVPSolver): """ Quadratic eigenvalue problem solver based on the problem linearization. (w^2 M + w D + K) x = 0. """ name = 'eig.qevp' _parameters = [ ('method', "{'companion', 'cholesky'}", 'companion', False, 'The linearization method.'), ('solver', 'dict', {'kind': 'eig.scipy', 'method': 'eig'}, False, """The configuration of an eigenvalue solver for the linearized problem (A - w B) x = 0."""), ('mode', "{'normal', 'inverted'}", 'normal', False, 'Solve either A - w B (normal), or B - 1/w A (inverted).'), ('debug', 'bool', False, False, 'If True, print debugging information.'), ] @standard_call def __call__(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None): if conf.debug: ssym = status['matrix_info'] = {} ssym['|M - M^T|'] = max_diff_csr(mtx_m, mtx_m.T) ssym['|D - D^T|'] = max_diff_csr(mtx_d, mtx_d.T) ssym['|K - K^T|'] = max_diff_csr(mtx_k, mtx_k.T) ssym['|M - M^H|'] = max_diff_csr(mtx_m, mtx_m.H) ssym['|D - D^H|'] =
max_diff_csr(mtx_d, mtx_d.H)
sfepy.linalg.utils.max_diff_csr
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs = get_default(n_eigs, self.n_eigs) eigenvectors = get_default(eigenvectors, self.eigenvectors) status = get_default(status, self.status) result = call(self, mtx_m, mtx_d, mtx_k, n_eigs, eigenvectors, status, conf, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed return result return _standard_call class LQuadraticEVPSolver(QuadraticEVPSolver): """ Quadratic eigenvalue problem solver based on the problem linearization. (w^2 M + w D + K) x = 0. """ name = 'eig.qevp' _parameters = [ ('method', "{'companion', 'cholesky'}", 'companion', False, 'The linearization method.'), ('solver', 'dict', {'kind': 'eig.scipy', 'method': 'eig'}, False, """The configuration of an eigenvalue solver for the linearized problem (A - w B) x = 0."""), ('mode', "{'normal', 'inverted'}", 'normal', False, 'Solve either A - w B (normal), or B - 1/w A (inverted).'), ('debug', 'bool', False, False, 'If True, print debugging information.'), ] @standard_call def __call__(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None): if conf.debug: ssym = status['matrix_info'] = {} ssym['|M - M^T|'] = max_diff_csr(mtx_m, mtx_m.T) ssym['|D - D^T|'] = max_diff_csr(mtx_d, mtx_d.T) ssym['|K - K^T|'] = max_diff_csr(mtx_k, mtx_k.T) ssym['|M - M^H|'] = max_diff_csr(mtx_m, mtx_m.H) ssym['|D - D^H|'] = max_diff_csr(mtx_d, mtx_d.H) ssym['|K - K^H|'] =
max_diff_csr(mtx_k, mtx_k.H)
sfepy.linalg.utils.max_diff_csr
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs = get_default(n_eigs, self.n_eigs) eigenvectors = get_default(eigenvectors, self.eigenvectors) status = get_default(status, self.status) result = call(self, mtx_m, mtx_d, mtx_k, n_eigs, eigenvectors, status, conf, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed return result return _standard_call class LQuadraticEVPSolver(QuadraticEVPSolver): """ Quadratic eigenvalue problem solver based on the problem linearization. (w^2 M + w D + K) x = 0. """ name = 'eig.qevp' _parameters = [ ('method', "{'companion', 'cholesky'}", 'companion', False, 'The linearization method.'), ('solver', 'dict', {'kind': 'eig.scipy', 'method': 'eig'}, False, """The configuration of an eigenvalue solver for the linearized problem (A - w B) x = 0."""), ('mode', "{'normal', 'inverted'}", 'normal', False, 'Solve either A - w B (normal), or B - 1/w A (inverted).'), ('debug', 'bool', False, False, 'If True, print debugging information.'), ] @standard_call def __call__(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None): if conf.debug: ssym = status['matrix_info'] = {} ssym['|M - M^T|'] = max_diff_csr(mtx_m, mtx_m.T) ssym['|D - D^T|'] = max_diff_csr(mtx_d, mtx_d.T) ssym['|K - K^T|'] = max_diff_csr(mtx_k, mtx_k.T) ssym['|M - M^H|'] = max_diff_csr(mtx_m, mtx_m.H) ssym['|D - D^H|'] = max_diff_csr(mtx_d, mtx_d.H) ssym['|K - K^H|'] = max_diff_csr(mtx_k, mtx_k.H) if conf.method == 'companion': mtx_eye = -sps.eye(mtx_m.shape[0], dtype=mtx_m.dtype) mtx_a = sps.bmat([[mtx_d, mtx_k], [mtx_eye, None]]) mtx_b = sps.bmat([[-mtx_m, None], [None, mtx_eye]]) elif conf.method == 'cholesky': from sksparse.cholmod import cholesky factor = cholesky(mtx_m) perm = factor.P() ir = nm.arange(len(perm)) mtx_p = sps.coo_matrix((nm.ones_like(perm), (ir, perm))) mtx_l = mtx_p.T * factor.L() if conf.debug: ssym['|S - LL^T|'] = max_diff_csr(mtx_m, mtx_l * mtx_l.T) mtx_eye = sps.eye(mtx_l.shape[0], dtype=nm.float64) mtx_a = sps.bmat([[-mtx_k, None], [None, mtx_eye]]) mtx_b = sps.bmat([[mtx_d, mtx_l], [mtx_l.T, None]]) else: raise ValueError('unknown method! (%s)' % conf.method) if conf.debug: ssym['|A - A^T|'] =
max_diff_csr(mtx_a, mtx_a.T)
sfepy.linalg.utils.max_diff_csr
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs = get_default(n_eigs, self.n_eigs) eigenvectors = get_default(eigenvectors, self.eigenvectors) status = get_default(status, self.status) result = call(self, mtx_m, mtx_d, mtx_k, n_eigs, eigenvectors, status, conf, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed return result return _standard_call class LQuadraticEVPSolver(QuadraticEVPSolver): """ Quadratic eigenvalue problem solver based on the problem linearization. (w^2 M + w D + K) x = 0. """ name = 'eig.qevp' _parameters = [ ('method', "{'companion', 'cholesky'}", 'companion', False, 'The linearization method.'), ('solver', 'dict', {'kind': 'eig.scipy', 'method': 'eig'}, False, """The configuration of an eigenvalue solver for the linearized problem (A - w B) x = 0."""), ('mode', "{'normal', 'inverted'}", 'normal', False, 'Solve either A - w B (normal), or B - 1/w A (inverted).'), ('debug', 'bool', False, False, 'If True, print debugging information.'), ] @standard_call def __call__(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None): if conf.debug: ssym = status['matrix_info'] = {} ssym['|M - M^T|'] = max_diff_csr(mtx_m, mtx_m.T) ssym['|D - D^T|'] = max_diff_csr(mtx_d, mtx_d.T) ssym['|K - K^T|'] = max_diff_csr(mtx_k, mtx_k.T) ssym['|M - M^H|'] = max_diff_csr(mtx_m, mtx_m.H) ssym['|D - D^H|'] = max_diff_csr(mtx_d, mtx_d.H) ssym['|K - K^H|'] = max_diff_csr(mtx_k, mtx_k.H) if conf.method == 'companion': mtx_eye = -sps.eye(mtx_m.shape[0], dtype=mtx_m.dtype) mtx_a = sps.bmat([[mtx_d, mtx_k], [mtx_eye, None]]) mtx_b = sps.bmat([[-mtx_m, None], [None, mtx_eye]]) elif conf.method == 'cholesky': from sksparse.cholmod import cholesky factor = cholesky(mtx_m) perm = factor.P() ir = nm.arange(len(perm)) mtx_p = sps.coo_matrix((nm.ones_like(perm), (ir, perm))) mtx_l = mtx_p.T * factor.L() if conf.debug: ssym['|S - LL^T|'] = max_diff_csr(mtx_m, mtx_l * mtx_l.T) mtx_eye = sps.eye(mtx_l.shape[0], dtype=nm.float64) mtx_a = sps.bmat([[-mtx_k, None], [None, mtx_eye]]) mtx_b = sps.bmat([[mtx_d, mtx_l], [mtx_l.T, None]]) else: raise ValueError('unknown method! (%s)' % conf.method) if conf.debug: ssym['|A - A^T|'] = max_diff_csr(mtx_a, mtx_a.T) ssym['|A - A^H|'] =
max_diff_csr(mtx_a, mtx_a.H)
sfepy.linalg.utils.max_diff_csr
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs = get_default(n_eigs, self.n_eigs) eigenvectors = get_default(eigenvectors, self.eigenvectors) status = get_default(status, self.status) result = call(self, mtx_m, mtx_d, mtx_k, n_eigs, eigenvectors, status, conf, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed return result return _standard_call class LQuadraticEVPSolver(QuadraticEVPSolver): """ Quadratic eigenvalue problem solver based on the problem linearization. (w^2 M + w D + K) x = 0. """ name = 'eig.qevp' _parameters = [ ('method', "{'companion', 'cholesky'}", 'companion', False, 'The linearization method.'), ('solver', 'dict', {'kind': 'eig.scipy', 'method': 'eig'}, False, """The configuration of an eigenvalue solver for the linearized problem (A - w B) x = 0."""), ('mode', "{'normal', 'inverted'}", 'normal', False, 'Solve either A - w B (normal), or B - 1/w A (inverted).'), ('debug', 'bool', False, False, 'If True, print debugging information.'), ] @standard_call def __call__(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None): if conf.debug: ssym = status['matrix_info'] = {} ssym['|M - M^T|'] = max_diff_csr(mtx_m, mtx_m.T) ssym['|D - D^T|'] = max_diff_csr(mtx_d, mtx_d.T) ssym['|K - K^T|'] = max_diff_csr(mtx_k, mtx_k.T) ssym['|M - M^H|'] = max_diff_csr(mtx_m, mtx_m.H) ssym['|D - D^H|'] = max_diff_csr(mtx_d, mtx_d.H) ssym['|K - K^H|'] = max_diff_csr(mtx_k, mtx_k.H) if conf.method == 'companion': mtx_eye = -sps.eye(mtx_m.shape[0], dtype=mtx_m.dtype) mtx_a = sps.bmat([[mtx_d, mtx_k], [mtx_eye, None]]) mtx_b = sps.bmat([[-mtx_m, None], [None, mtx_eye]]) elif conf.method == 'cholesky': from sksparse.cholmod import cholesky factor = cholesky(mtx_m) perm = factor.P() ir = nm.arange(len(perm)) mtx_p = sps.coo_matrix((nm.ones_like(perm), (ir, perm))) mtx_l = mtx_p.T * factor.L() if conf.debug: ssym['|S - LL^T|'] = max_diff_csr(mtx_m, mtx_l * mtx_l.T) mtx_eye = sps.eye(mtx_l.shape[0], dtype=nm.float64) mtx_a = sps.bmat([[-mtx_k, None], [None, mtx_eye]]) mtx_b = sps.bmat([[mtx_d, mtx_l], [mtx_l.T, None]]) else: raise ValueError('unknown method! (%s)' % conf.method) if conf.debug: ssym['|A - A^T|'] = max_diff_csr(mtx_a, mtx_a.T) ssym['|A - A^H|'] = max_diff_csr(mtx_a, mtx_a.H) ssym['|B - B^T|'] =
max_diff_csr(mtx_b, mtx_b.T)
sfepy.linalg.utils.max_diff_csr
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs = get_default(n_eigs, self.n_eigs) eigenvectors = get_default(eigenvectors, self.eigenvectors) status = get_default(status, self.status) result = call(self, mtx_m, mtx_d, mtx_k, n_eigs, eigenvectors, status, conf, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed return result return _standard_call class LQuadraticEVPSolver(QuadraticEVPSolver): """ Quadratic eigenvalue problem solver based on the problem linearization. (w^2 M + w D + K) x = 0. """ name = 'eig.qevp' _parameters = [ ('method', "{'companion', 'cholesky'}", 'companion', False, 'The linearization method.'), ('solver', 'dict', {'kind': 'eig.scipy', 'method': 'eig'}, False, """The configuration of an eigenvalue solver for the linearized problem (A - w B) x = 0."""), ('mode', "{'normal', 'inverted'}", 'normal', False, 'Solve either A - w B (normal), or B - 1/w A (inverted).'), ('debug', 'bool', False, False, 'If True, print debugging information.'), ] @standard_call def __call__(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None): if conf.debug: ssym = status['matrix_info'] = {} ssym['|M - M^T|'] = max_diff_csr(mtx_m, mtx_m.T) ssym['|D - D^T|'] = max_diff_csr(mtx_d, mtx_d.T) ssym['|K - K^T|'] = max_diff_csr(mtx_k, mtx_k.T) ssym['|M - M^H|'] = max_diff_csr(mtx_m, mtx_m.H) ssym['|D - D^H|'] = max_diff_csr(mtx_d, mtx_d.H) ssym['|K - K^H|'] = max_diff_csr(mtx_k, mtx_k.H) if conf.method == 'companion': mtx_eye = -sps.eye(mtx_m.shape[0], dtype=mtx_m.dtype) mtx_a = sps.bmat([[mtx_d, mtx_k], [mtx_eye, None]]) mtx_b = sps.bmat([[-mtx_m, None], [None, mtx_eye]]) elif conf.method == 'cholesky': from sksparse.cholmod import cholesky factor = cholesky(mtx_m) perm = factor.P() ir = nm.arange(len(perm)) mtx_p = sps.coo_matrix((nm.ones_like(perm), (ir, perm))) mtx_l = mtx_p.T * factor.L() if conf.debug: ssym['|S - LL^T|'] = max_diff_csr(mtx_m, mtx_l * mtx_l.T) mtx_eye = sps.eye(mtx_l.shape[0], dtype=nm.float64) mtx_a = sps.bmat([[-mtx_k, None], [None, mtx_eye]]) mtx_b = sps.bmat([[mtx_d, mtx_l], [mtx_l.T, None]]) else: raise ValueError('unknown method! (%s)' % conf.method) if conf.debug: ssym['|A - A^T|'] = max_diff_csr(mtx_a, mtx_a.T) ssym['|A - A^H|'] = max_diff_csr(mtx_a, mtx_a.H) ssym['|B - B^T|'] = max_diff_csr(mtx_b, mtx_b.T) ssym['|B - B^H|'] =
max_diff_csr(mtx_b, mtx_b.H)
sfepy.linalg.utils.max_diff_csr
""" Quadratic eigenvalue problem solvers. """ from __future__ import absolute_import import time import numpy as nm import scipy.sparse as sps from sfepy.base.base import output, get_default from sfepy.linalg.utils import max_diff_csr from sfepy.solvers.solvers import QuadraticEVPSolver def standard_call(call): """ Decorator handling argument preparation and timing for quadratic eigensolvers. """ def _standard_call(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx_m = get_default(mtx_m, self.mtx_m) mtx_d = get_default(mtx_d, self.mtx_d) mtx_k = get_default(mtx_k, self.mtx_k) n_eigs = get_default(n_eigs, self.n_eigs) eigenvectors = get_default(eigenvectors, self.eigenvectors) status = get_default(status, self.status) result = call(self, mtx_m, mtx_d, mtx_k, n_eigs, eigenvectors, status, conf, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed return result return _standard_call class LQuadraticEVPSolver(QuadraticEVPSolver): """ Quadratic eigenvalue problem solver based on the problem linearization. (w^2 M + w D + K) x = 0. """ name = 'eig.qevp' _parameters = [ ('method', "{'companion', 'cholesky'}", 'companion', False, 'The linearization method.'), ('solver', 'dict', {'kind': 'eig.scipy', 'method': 'eig'}, False, """The configuration of an eigenvalue solver for the linearized problem (A - w B) x = 0."""), ('mode', "{'normal', 'inverted'}", 'normal', False, 'Solve either A - w B (normal), or B - 1/w A (inverted).'), ('debug', 'bool', False, False, 'If True, print debugging information.'), ] @standard_call def __call__(self, mtx_m, mtx_d, mtx_k, n_eigs=None, eigenvectors=None, status=None, conf=None): if conf.debug: ssym = status['matrix_info'] = {} ssym['|M - M^T|'] = max_diff_csr(mtx_m, mtx_m.T) ssym['|D - D^T|'] = max_diff_csr(mtx_d, mtx_d.T) ssym['|K - K^T|'] = max_diff_csr(mtx_k, mtx_k.T) ssym['|M - M^H|'] = max_diff_csr(mtx_m, mtx_m.H) ssym['|D - D^H|'] = max_diff_csr(mtx_d, mtx_d.H) ssym['|K - K^H|'] = max_diff_csr(mtx_k, mtx_k.H) if conf.method == 'companion': mtx_eye = -sps.eye(mtx_m.shape[0], dtype=mtx_m.dtype) mtx_a = sps.bmat([[mtx_d, mtx_k], [mtx_eye, None]]) mtx_b = sps.bmat([[-mtx_m, None], [None, mtx_eye]]) elif conf.method == 'cholesky': from sksparse.cholmod import cholesky factor = cholesky(mtx_m) perm = factor.P() ir = nm.arange(len(perm)) mtx_p = sps.coo_matrix((nm.ones_like(perm), (ir, perm))) mtx_l = mtx_p.T * factor.L() if conf.debug: ssym['|S - LL^T|'] =
max_diff_csr(mtx_m, mtx_l * mtx_l.T)
sfepy.linalg.utils.max_diff_csr
from sfepy.terms.terms import * from sfepy.linalg import dot_sequences class NonPenetrationTerm(Term): r""" :Description: Non-penetration condition in the weak sense. :Definition: .. math:: \int_{\Gamma} \lambda \ul{n} \cdot \ul{v} \mbox{ , } \int_{\Gamma} \hat\lambda \ul{n} \cdot \ul{u} :Arguments 1: virtual : :math:`\ul{v}`, state : :math:`\lambda` :Arguments 2: state : :math:`\ul{u}`, virtual : :math:`\hat\lambda` """ name = 'dw_non_penetration' arg_types = (('virtual', 'state'), ('state', 'virtual')) modes = ('grad', 'div') integration = 'surface' use_caches = {'state_in_surface_qp' : [['state']]} def __call__(self, diff_var=None, **kwargs): if self.mode == 'grad': virtual, state = self.get_args(**kwargs) ap, sg = self.get_approximation(virtual) cache = self.get_cache('state_in_surface_qp', 0) else: state, virtual = self.get_args(**kwargs) ap, sg = self.get_approximation(state) cache = self.get_cache('state_in_surface_qp', 0) n_fa, n_qp, dim, n_fp = ap.get_s_data_shape(self.integral, self.region.name) rdim, cdim = virtual.n_components, state.n_components if diff_var is None: shape = (n_fa, 1, rdim * n_fp, 1) elif diff_var == self.get_arg_name('state'): shape = (n_fa, 1, rdim * n_fp, cdim * n_fp) else: raise StopIteration sd = ap.surface_data[self.region.name] # ap corresponds to \ul{u} field. bf = ap.get_base(sd.face_type, 0, integral=self.integral) ebf = nm.zeros((bf.shape[0], dim, n_fp * dim), dtype=nm.float64) for ir in xrange(dim): ebf[:, ir, ir*n_fp:(ir+1)*n_fp] = bf[:,0,:] normals = sg.variable(0) out = nm.zeros(shape, dtype=nm.float64) lchunk = nm.arange(n_fa, dtype=nm.int32) if diff_var is None: vec_qp = cache('state', self, 0, state=state, get_vector=self.get_vector) if self.mode == 'grad': ebf_t = nm.tile(ebf.transpose((0, 2, 1)), (n_fa, 1, 1, 1)) nl = normals * vec_qp eftnl = dot_sequences(ebf_t, nl, use_rows=True) sg.integrate_chunk(out, eftnl, lchunk, 1) else: bf_t = nm.tile(bf.transpose((0, 2, 1)), (n_fa, 1, 1, 1)) ntu = (normals * vec_qp).sum(axis=-2)[...,None] ftntu = (bf_t * ntu) sg.integrate_chunk(out, ftntu, lchunk, 1) else: ebf_t = nm.tile(ebf.transpose((0, 2, 1)), (n_fa, 1, 1, 1)) bf_ = nm.tile(bf, (n_fa, 1, 1, 1)) eftn =
dot_sequences(ebf_t, normals, use_rows=True)
sfepy.linalg.dot_sequences
from sfepy.terms.terms import * from sfepy.linalg import dot_sequences class NonPenetrationTerm(Term): r""" :Description: Non-penetration condition in the weak sense. :Definition: .. math:: \int_{\Gamma} \lambda \ul{n} \cdot \ul{v} \mbox{ , } \int_{\Gamma} \hat\lambda \ul{n} \cdot \ul{u} :Arguments 1: virtual : :math:`\ul{v}`, state : :math:`\lambda` :Arguments 2: state : :math:`\ul{u}`, virtual : :math:`\hat\lambda` """ name = 'dw_non_penetration' arg_types = (('virtual', 'state'), ('state', 'virtual')) modes = ('grad', 'div') integration = 'surface' use_caches = {'state_in_surface_qp' : [['state']]} def __call__(self, diff_var=None, **kwargs): if self.mode == 'grad': virtual, state = self.get_args(**kwargs) ap, sg = self.get_approximation(virtual) cache = self.get_cache('state_in_surface_qp', 0) else: state, virtual = self.get_args(**kwargs) ap, sg = self.get_approximation(state) cache = self.get_cache('state_in_surface_qp', 0) n_fa, n_qp, dim, n_fp = ap.get_s_data_shape(self.integral, self.region.name) rdim, cdim = virtual.n_components, state.n_components if diff_var is None: shape = (n_fa, 1, rdim * n_fp, 1) elif diff_var == self.get_arg_name('state'): shape = (n_fa, 1, rdim * n_fp, cdim * n_fp) else: raise StopIteration sd = ap.surface_data[self.region.name] # ap corresponds to \ul{u} field. bf = ap.get_base(sd.face_type, 0, integral=self.integral) ebf = nm.zeros((bf.shape[0], dim, n_fp * dim), dtype=nm.float64) for ir in xrange(dim): ebf[:, ir, ir*n_fp:(ir+1)*n_fp] = bf[:,0,:] normals = sg.variable(0) out = nm.zeros(shape, dtype=nm.float64) lchunk = nm.arange(n_fa, dtype=nm.int32) if diff_var is None: vec_qp = cache('state', self, 0, state=state, get_vector=self.get_vector) if self.mode == 'grad': ebf_t = nm.tile(ebf.transpose((0, 2, 1)), (n_fa, 1, 1, 1)) nl = normals * vec_qp eftnl =
dot_sequences(ebf_t, nl, use_rows=True)
sfepy.linalg.dot_sequences
r""" Diametrically point loaded 2-D disk with postprocessing and probes. See :ref:`sec-primer`. Find :math:`\ul{u}` such that: .. math:: \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) = 0 \;, \quad \forall \ul{v} \;, where .. math:: D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) + \lambda \ \delta_{ij} \delta_{kl} \;. """ from __future__ import absolute_import from examples.linear_elasticity.its2D_1 import * from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.postprocess.probes_vtk import Probe import os from six.moves import range def stress_strain(out, pb, state, extend=False): """ Calculate and output strain and stress for given displacements. """ from sfepy.base.base import Struct import matplotlib.pyplot as plt import matplotlib.font_manager as fm ev = pb.evaluate strain = ev('ev_cauchy_strain.2.Omega(u)', mode='el_avg') stress = ev('ev_cauchy_stress.2.Omega(Asphalt.D, u)', mode='el_avg') out['cauchy_strain'] = Struct(name='output_data', mode='cell', data=strain, dofs=None) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) probe =
Probe(out, pb.domain.mesh, probe_view=True)
sfepy.postprocess.probes_vtk.Probe
r""" Diametrically point loaded 2-D disk with postprocessing and probes. See :ref:`sec-primer`. Find :math:`\ul{u}` such that: .. math:: \int_{\Omega} D_{ijkl}\ e_{ij}(\ul{v}) e_{kl}(\ul{u}) = 0 \;, \quad \forall \ul{v} \;, where .. math:: D_{ijkl} = \mu (\delta_{ik} \delta_{jl}+\delta_{il} \delta_{jk}) + \lambda \ \delta_{ij} \delta_{kl} \;. """ from __future__ import absolute_import from examples.linear_elasticity.its2D_1 import * from sfepy.mechanics.matcoefs import stiffness_from_youngpoisson from sfepy.postprocess.probes_vtk import Probe import os from six.moves import range def stress_strain(out, pb, state, extend=False): """ Calculate and output strain and stress for given displacements. """ from sfepy.base.base import Struct import matplotlib.pyplot as plt import matplotlib.font_manager as fm ev = pb.evaluate strain = ev('ev_cauchy_strain.2.Omega(u)', mode='el_avg') stress = ev('ev_cauchy_stress.2.Omega(Asphalt.D, u)', mode='el_avg') out['cauchy_strain'] = Struct(name='output_data', mode='cell', data=strain, dofs=None) out['cauchy_stress'] = Struct(name='output_data', mode='cell', data=stress, dofs=None) probe = Probe(out, pb.domain.mesh, probe_view=True) ps0 = [[0.0, 0.0, 0.0], [ 0.0, 0.0, 0.0]] ps1 = [[75.0, 0.0, 0.0], [ 0.0, 75.0, 0.0]] n_point = 10 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('line%d' % ip) probe.add_line_probe('line%d' % ip, p0, p1, n_point) for ip, label in zip(probes, labels): fig = plt.figure() plt.clf() fig.subplots_adjust(hspace=0.4) plt.subplot(311) pars, vals = probe(ip, 'u') for ic in range(vals.shape[1] - 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', prop=fm.FontProperties(size=10)) sym_indices = [0, 4, 1] sym_labels = ['11', '22', '12'] plt.subplot(312) pars, vals = probe(ip, 'cauchy_strain') for ii, ic in enumerate(sym_indices): plt.plot(pars, vals[:,ic], label=r'$e_{%s}$' % sym_labels[ii], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy strain') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', prop=fm.FontProperties(size=8)) plt.subplot(313) pars, vals = probe(ip, 'cauchy_stress') for ii, ic in enumerate(sym_indices): plt.plot(pars, vals[:,ic], label=r'$\sigma_{%s}$' % sym_labels[ii], lw=1, ls='-', marker='+', ms=3) plt.ylabel('Cauchy stress') plt.xlabel('probe %s' % label, fontsize=8) plt.legend(loc='best', prop=fm.FontProperties(size=8)) opts = pb.conf.options filename_results = os.path.join(opts.get('output_dir'), 'its2D_probe_%s.png' % ip) fig.savefig(filename_results) return out materials['Asphalt'][0].update({'D' :
stiffness_from_youngpoisson(2, young, poisson)
sfepy.mechanics.matcoefs.stiffness_from_youngpoisson
"""All Sfepy imports go in this module """ import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field from sfepy.discrete.fem import FEDomain as Domain from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem, ) from sfepy.terms import Term, Terms from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.base.base import output from toolz.curried import pipe, curry, do goptions["verbose"] = False
output.set_output(quiet=True)
sfepy.base.base.output.set_output
"""All Sfepy imports go in this module """ import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field from sfepy.discrete.fem import FEDomain as Domain from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem, ) from sfepy.terms import Term, Terms from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.base.base import output from toolz.curried import pipe, curry, do goptions["verbose"] = False output.set_output(quiet=True) def check(ids): """Check that the fixed displacement nodes have been isolated Args: ids: the isolated IDs Returns the unchanged IDs >>> check([1, 2, 3, 4]) Traceback (most recent call last): ... RuntimeError: length of ids is incorrect """ if len(ids) != 3: raise RuntimeError("length of ids is incorrect") return ids @curry def subdomain(i_x, domain_, eps, coords, **_): """Find the node IDs that will be fixed Args: i_x: the index (either 0 or 1) depends on direction of axes domain_: the Sfepy domain eps: a small value coords: the coordinates of the nodes Returns: the isolated node IDs """ def i_y(): """Switch the index from 0 -> 1 or from 1 -> 0 """ return (i_x + 1) % 2 return pipe( (coords[:, i_x] > -eps) & (coords[:, i_x] < eps), lambda x: (coords[:, i_x] < domain_.get_mesh_bounding_box()[0][i_x] + eps) | x, lambda x: (coords[:, i_x] > domain_.get_mesh_bounding_box()[1][i_x] - eps) | x, lambda x: (coords[:, i_y()] < eps) & (coords[:, i_y()] > -eps) & x, lambda x: np.where(x)[0], check, ) def get_bc(domain, delta_x, index, cond): """Make a displacement boundary condition Args: domain: the Sfepy domain delta_x: the mesh spacing index: the index (either 0 or 1) depends on direction of axes cond: the BC dictionary Returns: the Sfepy boundary condition """ return pipe( Function("fix_points", subdomain(index, domain, delta_x * 1e-3)), lambda x: domain.create_region( "region_fix_points", "vertices by fix_points", "vertex", functions=Functions([x]), ), lambda x:
EssentialBC("fix_points_BC", x, cond)
sfepy.discrete.conditions.EssentialBC
"""All Sfepy imports go in this module """ import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field from sfepy.discrete.fem import FEDomain as Domain from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem, ) from sfepy.terms import Term, Terms from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.base.base import output from toolz.curried import pipe, curry, do goptions["verbose"] = False output.set_output(quiet=True) def check(ids): """Check that the fixed displacement nodes have been isolated Args: ids: the isolated IDs Returns the unchanged IDs >>> check([1, 2, 3, 4]) Traceback (most recent call last): ... RuntimeError: length of ids is incorrect """ if len(ids) != 3: raise RuntimeError("length of ids is incorrect") return ids @curry def subdomain(i_x, domain_, eps, coords, **_): """Find the node IDs that will be fixed Args: i_x: the index (either 0 or 1) depends on direction of axes domain_: the Sfepy domain eps: a small value coords: the coordinates of the nodes Returns: the isolated node IDs """ def i_y(): """Switch the index from 0 -> 1 or from 1 -> 0 """ return (i_x + 1) % 2 return pipe( (coords[:, i_x] > -eps) & (coords[:, i_x] < eps), lambda x: (coords[:, i_x] < domain_.get_mesh_bounding_box()[0][i_x] + eps) | x, lambda x: (coords[:, i_x] > domain_.get_mesh_bounding_box()[1][i_x] - eps) | x, lambda x: (coords[:, i_y()] < eps) & (coords[:, i_y()] > -eps) & x, lambda x: np.where(x)[0], check, ) def get_bc(domain, delta_x, index, cond): """Make a displacement boundary condition Args: domain: the Sfepy domain delta_x: the mesh spacing index: the index (either 0 or 1) depends on direction of axes cond: the BC dictionary Returns: the Sfepy boundary condition """ return pipe( Function("fix_points", subdomain(index, domain, delta_x * 1e-3)), lambda x: domain.create_region( "region_fix_points", "vertices by fix_points", "vertex", functions=Functions([x]), ), lambda x: EssentialBC("fix_points_BC", x, cond), ) def get_bcs(domain, delta_x): """Get the boundary conditions Args: domain: the Sfepy domain delta_x: the mesh spacing Returns: the boundary conditions """ return Conditions( [ get_bc(domain, delta_x, 1, {"u.0": 0.0}), get_bc(domain, delta_x, 0, {"u.1": 0.0}), ] ) def get_material(calc_stiffness, calc_prestress): """Get the material Args: calc_stiffness: the function for calculating the stiffness tensor calc_prestress: the function for calculating the prestress Returns: the material """ def _material_func_(_, coors, mode=None, **__): if mode == "qp": return dict(D=calc_stiffness(coors), stress=calc_prestress(coors)) return None return Material("m", function=
Function("material_func", _material_func_)
sfepy.discrete.Function
"""All Sfepy imports go in this module """ import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field from sfepy.discrete.fem import FEDomain as Domain from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem, ) from sfepy.terms import Term, Terms from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.base.base import output from toolz.curried import pipe, curry, do goptions["verbose"] = False output.set_output(quiet=True) def check(ids): """Check that the fixed displacement nodes have been isolated Args: ids: the isolated IDs Returns the unchanged IDs >>> check([1, 2, 3, 4]) Traceback (most recent call last): ... RuntimeError: length of ids is incorrect """ if len(ids) != 3: raise RuntimeError("length of ids is incorrect") return ids @curry def subdomain(i_x, domain_, eps, coords, **_): """Find the node IDs that will be fixed Args: i_x: the index (either 0 or 1) depends on direction of axes domain_: the Sfepy domain eps: a small value coords: the coordinates of the nodes Returns: the isolated node IDs """ def i_y(): """Switch the index from 0 -> 1 or from 1 -> 0 """ return (i_x + 1) % 2 return pipe( (coords[:, i_x] > -eps) & (coords[:, i_x] < eps), lambda x: (coords[:, i_x] < domain_.get_mesh_bounding_box()[0][i_x] + eps) | x, lambda x: (coords[:, i_x] > domain_.get_mesh_bounding_box()[1][i_x] - eps) | x, lambda x: (coords[:, i_y()] < eps) & (coords[:, i_y()] > -eps) & x, lambda x: np.where(x)[0], check, ) def get_bc(domain, delta_x, index, cond): """Make a displacement boundary condition Args: domain: the Sfepy domain delta_x: the mesh spacing index: the index (either 0 or 1) depends on direction of axes cond: the BC dictionary Returns: the Sfepy boundary condition """ return pipe( Function("fix_points", subdomain(index, domain, delta_x * 1e-3)), lambda x: domain.create_region( "region_fix_points", "vertices by fix_points", "vertex", functions=Functions([x]), ), lambda x: EssentialBC("fix_points_BC", x, cond), ) def get_bcs(domain, delta_x): """Get the boundary conditions Args: domain: the Sfepy domain delta_x: the mesh spacing Returns: the boundary conditions """ return Conditions( [ get_bc(domain, delta_x, 1, {"u.0": 0.0}), get_bc(domain, delta_x, 0, {"u.1": 0.0}), ] ) def get_material(calc_stiffness, calc_prestress): """Get the material Args: calc_stiffness: the function for calculating the stiffness tensor calc_prestress: the function for calculating the prestress Returns: the material """ def _material_func_(_, coors, mode=None, **__): if mode == "qp": return dict(D=calc_stiffness(coors), stress=calc_prestress(coors)) return None return Material("m", function=Function("material_func", _material_func_)) def get_uv(shape, delta_x): """Get the fields for the displacement and test function Args: shape: the shape of the domain delta_x: the mesh spacing Returns: tuple of field variables """ return pipe( np.array(shape), lambda x: gen_block_mesh( x * delta_x, x + 1, np.zeros_like(shape), verbose=False ), lambda x:
Domain("domain", x)
sfepy.discrete.fem.FEDomain
"""All Sfepy imports go in this module """ import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field from sfepy.discrete.fem import FEDomain as Domain from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem, ) from sfepy.terms import Term, Terms from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.base.base import output from toolz.curried import pipe, curry, do goptions["verbose"] = False output.set_output(quiet=True) def check(ids): """Check that the fixed displacement nodes have been isolated Args: ids: the isolated IDs Returns the unchanged IDs >>> check([1, 2, 3, 4]) Traceback (most recent call last): ... RuntimeError: length of ids is incorrect """ if len(ids) != 3: raise RuntimeError("length of ids is incorrect") return ids @curry def subdomain(i_x, domain_, eps, coords, **_): """Find the node IDs that will be fixed Args: i_x: the index (either 0 or 1) depends on direction of axes domain_: the Sfepy domain eps: a small value coords: the coordinates of the nodes Returns: the isolated node IDs """ def i_y(): """Switch the index from 0 -> 1 or from 1 -> 0 """ return (i_x + 1) % 2 return pipe( (coords[:, i_x] > -eps) & (coords[:, i_x] < eps), lambda x: (coords[:, i_x] < domain_.get_mesh_bounding_box()[0][i_x] + eps) | x, lambda x: (coords[:, i_x] > domain_.get_mesh_bounding_box()[1][i_x] - eps) | x, lambda x: (coords[:, i_y()] < eps) & (coords[:, i_y()] > -eps) & x, lambda x: np.where(x)[0], check, ) def get_bc(domain, delta_x, index, cond): """Make a displacement boundary condition Args: domain: the Sfepy domain delta_x: the mesh spacing index: the index (either 0 or 1) depends on direction of axes cond: the BC dictionary Returns: the Sfepy boundary condition """ return pipe( Function("fix_points", subdomain(index, domain, delta_x * 1e-3)), lambda x: domain.create_region( "region_fix_points", "vertices by fix_points", "vertex", functions=Functions([x]), ), lambda x: EssentialBC("fix_points_BC", x, cond), ) def get_bcs(domain, delta_x): """Get the boundary conditions Args: domain: the Sfepy domain delta_x: the mesh spacing Returns: the boundary conditions """ return Conditions( [ get_bc(domain, delta_x, 1, {"u.0": 0.0}), get_bc(domain, delta_x, 0, {"u.1": 0.0}), ] ) def get_material(calc_stiffness, calc_prestress): """Get the material Args: calc_stiffness: the function for calculating the stiffness tensor calc_prestress: the function for calculating the prestress Returns: the material """ def _material_func_(_, coors, mode=None, **__): if mode == "qp": return dict(D=calc_stiffness(coors), stress=calc_prestress(coors)) return None return Material("m", function=Function("material_func", _material_func_)) def get_uv(shape, delta_x): """Get the fields for the displacement and test function Args: shape: the shape of the domain delta_x: the mesh spacing Returns: tuple of field variables """ return pipe( np.array(shape), lambda x: gen_block_mesh( x * delta_x, x + 1, np.zeros_like(shape), verbose=False ), lambda x: Domain("domain", x), lambda x: x.create_region("region_all", "all"), lambda x:
Field.from_args("fu", np.float64, "vector", x, approx_order=2)
sfepy.discrete.fem.Field.from_args
"""All Sfepy imports go in this module """ import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field from sfepy.discrete.fem import FEDomain as Domain from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem, ) from sfepy.terms import Term, Terms from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.base.base import output from toolz.curried import pipe, curry, do goptions["verbose"] = False output.set_output(quiet=True) def check(ids): """Check that the fixed displacement nodes have been isolated Args: ids: the isolated IDs Returns the unchanged IDs >>> check([1, 2, 3, 4]) Traceback (most recent call last): ... RuntimeError: length of ids is incorrect """ if len(ids) != 3: raise RuntimeError("length of ids is incorrect") return ids @curry def subdomain(i_x, domain_, eps, coords, **_): """Find the node IDs that will be fixed Args: i_x: the index (either 0 or 1) depends on direction of axes domain_: the Sfepy domain eps: a small value coords: the coordinates of the nodes Returns: the isolated node IDs """ def i_y(): """Switch the index from 0 -> 1 or from 1 -> 0 """ return (i_x + 1) % 2 return pipe( (coords[:, i_x] > -eps) & (coords[:, i_x] < eps), lambda x: (coords[:, i_x] < domain_.get_mesh_bounding_box()[0][i_x] + eps) | x, lambda x: (coords[:, i_x] > domain_.get_mesh_bounding_box()[1][i_x] - eps) | x, lambda x: (coords[:, i_y()] < eps) & (coords[:, i_y()] > -eps) & x, lambda x: np.where(x)[0], check, ) def get_bc(domain, delta_x, index, cond): """Make a displacement boundary condition Args: domain: the Sfepy domain delta_x: the mesh spacing index: the index (either 0 or 1) depends on direction of axes cond: the BC dictionary Returns: the Sfepy boundary condition """ return pipe( Function("fix_points", subdomain(index, domain, delta_x * 1e-3)), lambda x: domain.create_region( "region_fix_points", "vertices by fix_points", "vertex", functions=Functions([x]), ), lambda x: EssentialBC("fix_points_BC", x, cond), ) def get_bcs(domain, delta_x): """Get the boundary conditions Args: domain: the Sfepy domain delta_x: the mesh spacing Returns: the boundary conditions """ return Conditions( [ get_bc(domain, delta_x, 1, {"u.0": 0.0}), get_bc(domain, delta_x, 0, {"u.1": 0.0}), ] ) def get_material(calc_stiffness, calc_prestress): """Get the material Args: calc_stiffness: the function for calculating the stiffness tensor calc_prestress: the function for calculating the prestress Returns: the material """ def _material_func_(_, coors, mode=None, **__): if mode == "qp": return dict(D=calc_stiffness(coors), stress=calc_prestress(coors)) return None return Material("m", function=Function("material_func", _material_func_)) def get_uv(shape, delta_x): """Get the fields for the displacement and test function Args: shape: the shape of the domain delta_x: the mesh spacing Returns: tuple of field variables """ return pipe( np.array(shape), lambda x: gen_block_mesh( x * delta_x, x + 1, np.zeros_like(shape), verbose=False ), lambda x: Domain("domain", x), lambda x: x.create_region("region_all", "all"), lambda x: Field.from_args("fu", np.float64, "vector", x, approx_order=2), lambda x: ( FieldVariable("u", "unknown", x), FieldVariable("v", "test", x, primary_var_name="u"), ), ) # field = Field.from_args('fu', np.float64, 'vector', region_all, # pylint: disable=no-member # approx_order=2) def get_terms(u_field, v_field, calc_stiffness, calc_prestress): """Get the terms for the equation Args: u_field: the displacement field v_field: the test function field calc_stiffness: a function to calculate the stiffness tensor calc_prestress: a function to calculate the prestress tensor Returns: a tuple of terms for the equation """ return ( Term.new( "dw_lin_elastic(m.D, v, u)",
Integral("i", order=4)
sfepy.discrete.Integral
"""All Sfepy imports go in this module """ import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field from sfepy.discrete.fem import FEDomain as Domain from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem, ) from sfepy.terms import Term, Terms from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.base.base import output from toolz.curried import pipe, curry, do goptions["verbose"] = False output.set_output(quiet=True) def check(ids): """Check that the fixed displacement nodes have been isolated Args: ids: the isolated IDs Returns the unchanged IDs >>> check([1, 2, 3, 4]) Traceback (most recent call last): ... RuntimeError: length of ids is incorrect """ if len(ids) != 3: raise RuntimeError("length of ids is incorrect") return ids @curry def subdomain(i_x, domain_, eps, coords, **_): """Find the node IDs that will be fixed Args: i_x: the index (either 0 or 1) depends on direction of axes domain_: the Sfepy domain eps: a small value coords: the coordinates of the nodes Returns: the isolated node IDs """ def i_y(): """Switch the index from 0 -> 1 or from 1 -> 0 """ return (i_x + 1) % 2 return pipe( (coords[:, i_x] > -eps) & (coords[:, i_x] < eps), lambda x: (coords[:, i_x] < domain_.get_mesh_bounding_box()[0][i_x] + eps) | x, lambda x: (coords[:, i_x] > domain_.get_mesh_bounding_box()[1][i_x] - eps) | x, lambda x: (coords[:, i_y()] < eps) & (coords[:, i_y()] > -eps) & x, lambda x: np.where(x)[0], check, ) def get_bc(domain, delta_x, index, cond): """Make a displacement boundary condition Args: domain: the Sfepy domain delta_x: the mesh spacing index: the index (either 0 or 1) depends on direction of axes cond: the BC dictionary Returns: the Sfepy boundary condition """ return pipe( Function("fix_points", subdomain(index, domain, delta_x * 1e-3)), lambda x: domain.create_region( "region_fix_points", "vertices by fix_points", "vertex", functions=Functions([x]), ), lambda x: EssentialBC("fix_points_BC", x, cond), ) def get_bcs(domain, delta_x): """Get the boundary conditions Args: domain: the Sfepy domain delta_x: the mesh spacing Returns: the boundary conditions """ return Conditions( [ get_bc(domain, delta_x, 1, {"u.0": 0.0}), get_bc(domain, delta_x, 0, {"u.1": 0.0}), ] ) def get_material(calc_stiffness, calc_prestress): """Get the material Args: calc_stiffness: the function for calculating the stiffness tensor calc_prestress: the function for calculating the prestress Returns: the material """ def _material_func_(_, coors, mode=None, **__): if mode == "qp": return dict(D=calc_stiffness(coors), stress=calc_prestress(coors)) return None return Material("m", function=Function("material_func", _material_func_)) def get_uv(shape, delta_x): """Get the fields for the displacement and test function Args: shape: the shape of the domain delta_x: the mesh spacing Returns: tuple of field variables """ return pipe( np.array(shape), lambda x: gen_block_mesh( x * delta_x, x + 1, np.zeros_like(shape), verbose=False ), lambda x: Domain("domain", x), lambda x: x.create_region("region_all", "all"), lambda x: Field.from_args("fu", np.float64, "vector", x, approx_order=2), lambda x: ( FieldVariable("u", "unknown", x), FieldVariable("v", "test", x, primary_var_name="u"), ), ) # field = Field.from_args('fu', np.float64, 'vector', region_all, # pylint: disable=no-member # approx_order=2) def get_terms(u_field, v_field, calc_stiffness, calc_prestress): """Get the terms for the equation Args: u_field: the displacement field v_field: the test function field calc_stiffness: a function to calculate the stiffness tensor calc_prestress: a function to calculate the prestress tensor Returns: a tuple of terms for the equation """ return ( Term.new( "dw_lin_elastic(m.D, v, u)", Integral("i", order=4), v_field.field.region, m=get_material(calc_stiffness, calc_prestress), v=v_field, u=u_field, ), Term.new( "dw_lin_prestress(m.stress, v)",
Integral("i", order=4)
sfepy.discrete.Integral
"""All Sfepy imports go in this module """ import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field from sfepy.discrete.fem import FEDomain as Domain from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem, ) from sfepy.terms import Term, Terms from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.base.base import output from toolz.curried import pipe, curry, do goptions["verbose"] = False output.set_output(quiet=True) def check(ids): """Check that the fixed displacement nodes have been isolated Args: ids: the isolated IDs Returns the unchanged IDs >>> check([1, 2, 3, 4]) Traceback (most recent call last): ... RuntimeError: length of ids is incorrect """ if len(ids) != 3: raise RuntimeError("length of ids is incorrect") return ids @curry def subdomain(i_x, domain_, eps, coords, **_): """Find the node IDs that will be fixed Args: i_x: the index (either 0 or 1) depends on direction of axes domain_: the Sfepy domain eps: a small value coords: the coordinates of the nodes Returns: the isolated node IDs """ def i_y(): """Switch the index from 0 -> 1 or from 1 -> 0 """ return (i_x + 1) % 2 return pipe( (coords[:, i_x] > -eps) & (coords[:, i_x] < eps), lambda x: (coords[:, i_x] < domain_.get_mesh_bounding_box()[0][i_x] + eps) | x, lambda x: (coords[:, i_x] > domain_.get_mesh_bounding_box()[1][i_x] - eps) | x, lambda x: (coords[:, i_y()] < eps) & (coords[:, i_y()] > -eps) & x, lambda x: np.where(x)[0], check, ) def get_bc(domain, delta_x, index, cond): """Make a displacement boundary condition Args: domain: the Sfepy domain delta_x: the mesh spacing index: the index (either 0 or 1) depends on direction of axes cond: the BC dictionary Returns: the Sfepy boundary condition """ return pipe( Function("fix_points", subdomain(index, domain, delta_x * 1e-3)), lambda x: domain.create_region( "region_fix_points", "vertices by fix_points", "vertex", functions=Functions([x]), ), lambda x: EssentialBC("fix_points_BC", x, cond), ) def get_bcs(domain, delta_x): """Get the boundary conditions Args: domain: the Sfepy domain delta_x: the mesh spacing Returns: the boundary conditions """ return Conditions( [ get_bc(domain, delta_x, 1, {"u.0": 0.0}), get_bc(domain, delta_x, 0, {"u.1": 0.0}), ] ) def get_material(calc_stiffness, calc_prestress): """Get the material Args: calc_stiffness: the function for calculating the stiffness tensor calc_prestress: the function for calculating the prestress Returns: the material """ def _material_func_(_, coors, mode=None, **__): if mode == "qp": return dict(D=calc_stiffness(coors), stress=calc_prestress(coors)) return None return Material("m", function=Function("material_func", _material_func_)) def get_uv(shape, delta_x): """Get the fields for the displacement and test function Args: shape: the shape of the domain delta_x: the mesh spacing Returns: tuple of field variables """ return pipe( np.array(shape), lambda x: gen_block_mesh( x * delta_x, x + 1, np.zeros_like(shape), verbose=False ), lambda x: Domain("domain", x), lambda x: x.create_region("region_all", "all"), lambda x: Field.from_args("fu", np.float64, "vector", x, approx_order=2), lambda x: ( FieldVariable("u", "unknown", x), FieldVariable("v", "test", x, primary_var_name="u"), ), ) # field = Field.from_args('fu', np.float64, 'vector', region_all, # pylint: disable=no-member # approx_order=2) def get_terms(u_field, v_field, calc_stiffness, calc_prestress): """Get the terms for the equation Args: u_field: the displacement field v_field: the test function field calc_stiffness: a function to calculate the stiffness tensor calc_prestress: a function to calculate the prestress tensor Returns: a tuple of terms for the equation """ return ( Term.new( "dw_lin_elastic(m.D, v, u)", Integral("i", order=4), v_field.field.region, m=get_material(calc_stiffness, calc_prestress), v=v_field, u=u_field, ), Term.new( "dw_lin_prestress(m.stress, v)", Integral("i", order=4), v_field.field.region, m=get_material(calc_stiffness, calc_prestress), v=v_field, ), ) def get_nls(evaluator): """Get the non-linear solver Args: evaluator: the problem evaluator Returns: the non-linear solver """ return Newton( {}, lin_solver=
ScipyDirect({})
sfepy.solvers.ls.ScipyDirect
"""All Sfepy imports go in this module """ import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field from sfepy.discrete.fem import FEDomain as Domain from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem, ) from sfepy.terms import Term, Terms from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.base.base import output from toolz.curried import pipe, curry, do goptions["verbose"] = False output.set_output(quiet=True) def check(ids): """Check that the fixed displacement nodes have been isolated Args: ids: the isolated IDs Returns the unchanged IDs >>> check([1, 2, 3, 4]) Traceback (most recent call last): ... RuntimeError: length of ids is incorrect """ if len(ids) != 3: raise RuntimeError("length of ids is incorrect") return ids @curry def subdomain(i_x, domain_, eps, coords, **_): """Find the node IDs that will be fixed Args: i_x: the index (either 0 or 1) depends on direction of axes domain_: the Sfepy domain eps: a small value coords: the coordinates of the nodes Returns: the isolated node IDs """ def i_y(): """Switch the index from 0 -> 1 or from 1 -> 0 """ return (i_x + 1) % 2 return pipe( (coords[:, i_x] > -eps) & (coords[:, i_x] < eps), lambda x: (coords[:, i_x] < domain_.get_mesh_bounding_box()[0][i_x] + eps) | x, lambda x: (coords[:, i_x] > domain_.get_mesh_bounding_box()[1][i_x] - eps) | x, lambda x: (coords[:, i_y()] < eps) & (coords[:, i_y()] > -eps) & x, lambda x: np.where(x)[0], check, ) def get_bc(domain, delta_x, index, cond): """Make a displacement boundary condition Args: domain: the Sfepy domain delta_x: the mesh spacing index: the index (either 0 or 1) depends on direction of axes cond: the BC dictionary Returns: the Sfepy boundary condition """ return pipe( Function("fix_points", subdomain(index, domain, delta_x * 1e-3)), lambda x: domain.create_region( "region_fix_points", "vertices by fix_points", "vertex", functions=Functions([x]), ), lambda x: EssentialBC("fix_points_BC", x, cond), ) def get_bcs(domain, delta_x): """Get the boundary conditions Args: domain: the Sfepy domain delta_x: the mesh spacing Returns: the boundary conditions """ return Conditions( [ get_bc(domain, delta_x, 1, {"u.0": 0.0}), get_bc(domain, delta_x, 0, {"u.1": 0.0}), ] ) def get_material(calc_stiffness, calc_prestress): """Get the material Args: calc_stiffness: the function for calculating the stiffness tensor calc_prestress: the function for calculating the prestress Returns: the material """ def _material_func_(_, coors, mode=None, **__): if mode == "qp": return dict(D=calc_stiffness(coors), stress=calc_prestress(coors)) return None return Material("m", function=Function("material_func", _material_func_)) def get_uv(shape, delta_x): """Get the fields for the displacement and test function Args: shape: the shape of the domain delta_x: the mesh spacing Returns: tuple of field variables """ return pipe( np.array(shape), lambda x: gen_block_mesh( x * delta_x, x + 1, np.zeros_like(shape), verbose=False ), lambda x: Domain("domain", x), lambda x: x.create_region("region_all", "all"), lambda x: Field.from_args("fu", np.float64, "vector", x, approx_order=2), lambda x: (
FieldVariable("u", "unknown", x)
sfepy.discrete.FieldVariable
"""All Sfepy imports go in this module """ import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field from sfepy.discrete.fem import FEDomain as Domain from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem, ) from sfepy.terms import Term, Terms from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.base.base import output from toolz.curried import pipe, curry, do goptions["verbose"] = False output.set_output(quiet=True) def check(ids): """Check that the fixed displacement nodes have been isolated Args: ids: the isolated IDs Returns the unchanged IDs >>> check([1, 2, 3, 4]) Traceback (most recent call last): ... RuntimeError: length of ids is incorrect """ if len(ids) != 3: raise RuntimeError("length of ids is incorrect") return ids @curry def subdomain(i_x, domain_, eps, coords, **_): """Find the node IDs that will be fixed Args: i_x: the index (either 0 or 1) depends on direction of axes domain_: the Sfepy domain eps: a small value coords: the coordinates of the nodes Returns: the isolated node IDs """ def i_y(): """Switch the index from 0 -> 1 or from 1 -> 0 """ return (i_x + 1) % 2 return pipe( (coords[:, i_x] > -eps) & (coords[:, i_x] < eps), lambda x: (coords[:, i_x] < domain_.get_mesh_bounding_box()[0][i_x] + eps) | x, lambda x: (coords[:, i_x] > domain_.get_mesh_bounding_box()[1][i_x] - eps) | x, lambda x: (coords[:, i_y()] < eps) & (coords[:, i_y()] > -eps) & x, lambda x: np.where(x)[0], check, ) def get_bc(domain, delta_x, index, cond): """Make a displacement boundary condition Args: domain: the Sfepy domain delta_x: the mesh spacing index: the index (either 0 or 1) depends on direction of axes cond: the BC dictionary Returns: the Sfepy boundary condition """ return pipe( Function("fix_points", subdomain(index, domain, delta_x * 1e-3)), lambda x: domain.create_region( "region_fix_points", "vertices by fix_points", "vertex", functions=Functions([x]), ), lambda x: EssentialBC("fix_points_BC", x, cond), ) def get_bcs(domain, delta_x): """Get the boundary conditions Args: domain: the Sfepy domain delta_x: the mesh spacing Returns: the boundary conditions """ return Conditions( [ get_bc(domain, delta_x, 1, {"u.0": 0.0}), get_bc(domain, delta_x, 0, {"u.1": 0.0}), ] ) def get_material(calc_stiffness, calc_prestress): """Get the material Args: calc_stiffness: the function for calculating the stiffness tensor calc_prestress: the function for calculating the prestress Returns: the material """ def _material_func_(_, coors, mode=None, **__): if mode == "qp": return dict(D=calc_stiffness(coors), stress=calc_prestress(coors)) return None return Material("m", function=Function("material_func", _material_func_)) def get_uv(shape, delta_x): """Get the fields for the displacement and test function Args: shape: the shape of the domain delta_x: the mesh spacing Returns: tuple of field variables """ return pipe( np.array(shape), lambda x: gen_block_mesh( x * delta_x, x + 1, np.zeros_like(shape), verbose=False ), lambda x: Domain("domain", x), lambda x: x.create_region("region_all", "all"), lambda x: Field.from_args("fu", np.float64, "vector", x, approx_order=2), lambda x: ( FieldVariable("u", "unknown", x),
FieldVariable("v", "test", x, primary_var_name="u")
sfepy.discrete.FieldVariable
"""All Sfepy imports go in this module """ import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field from sfepy.discrete.fem import FEDomain as Domain from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem, ) from sfepy.terms import Term, Terms from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.base.base import output from toolz.curried import pipe, curry, do goptions["verbose"] = False output.set_output(quiet=True) def check(ids): """Check that the fixed displacement nodes have been isolated Args: ids: the isolated IDs Returns the unchanged IDs >>> check([1, 2, 3, 4]) Traceback (most recent call last): ... RuntimeError: length of ids is incorrect """ if len(ids) != 3: raise RuntimeError("length of ids is incorrect") return ids @curry def subdomain(i_x, domain_, eps, coords, **_): """Find the node IDs that will be fixed Args: i_x: the index (either 0 or 1) depends on direction of axes domain_: the Sfepy domain eps: a small value coords: the coordinates of the nodes Returns: the isolated node IDs """ def i_y(): """Switch the index from 0 -> 1 or from 1 -> 0 """ return (i_x + 1) % 2 return pipe( (coords[:, i_x] > -eps) & (coords[:, i_x] < eps), lambda x: (coords[:, i_x] < domain_.get_mesh_bounding_box()[0][i_x] + eps) | x, lambda x: (coords[:, i_x] > domain_.get_mesh_bounding_box()[1][i_x] - eps) | x, lambda x: (coords[:, i_y()] < eps) & (coords[:, i_y()] > -eps) & x, lambda x: np.where(x)[0], check, ) def get_bc(domain, delta_x, index, cond): """Make a displacement boundary condition Args: domain: the Sfepy domain delta_x: the mesh spacing index: the index (either 0 or 1) depends on direction of axes cond: the BC dictionary Returns: the Sfepy boundary condition """ return pipe( Function("fix_points", subdomain(index, domain, delta_x * 1e-3)), lambda x: domain.create_region( "region_fix_points", "vertices by fix_points", "vertex", functions=Functions([x]), ), lambda x: EssentialBC("fix_points_BC", x, cond), ) def get_bcs(domain, delta_x): """Get the boundary conditions Args: domain: the Sfepy domain delta_x: the mesh spacing Returns: the boundary conditions """ return Conditions( [ get_bc(domain, delta_x, 1, {"u.0": 0.0}), get_bc(domain, delta_x, 0, {"u.1": 0.0}), ] ) def get_material(calc_stiffness, calc_prestress): """Get the material Args: calc_stiffness: the function for calculating the stiffness tensor calc_prestress: the function for calculating the prestress Returns: the material """ def _material_func_(_, coors, mode=None, **__): if mode == "qp": return dict(D=calc_stiffness(coors), stress=calc_prestress(coors)) return None return Material("m", function=Function("material_func", _material_func_)) def get_uv(shape, delta_x): """Get the fields for the displacement and test function Args: shape: the shape of the domain delta_x: the mesh spacing Returns: tuple of field variables """ return pipe( np.array(shape), lambda x: gen_block_mesh( x * delta_x, x + 1, np.zeros_like(shape), verbose=False ), lambda x: Domain("domain", x), lambda x: x.create_region("region_all", "all"), lambda x: Field.from_args("fu", np.float64, "vector", x, approx_order=2), lambda x: ( FieldVariable("u", "unknown", x), FieldVariable("v", "test", x, primary_var_name="u"), ), ) # field = Field.from_args('fu', np.float64, 'vector', region_all, # pylint: disable=no-member # approx_order=2) def get_terms(u_field, v_field, calc_stiffness, calc_prestress): """Get the terms for the equation Args: u_field: the displacement field v_field: the test function field calc_stiffness: a function to calculate the stiffness tensor calc_prestress: a function to calculate the prestress tensor Returns: a tuple of terms for the equation """ return ( Term.new( "dw_lin_elastic(m.D, v, u)", Integral("i", order=4), v_field.field.region, m=get_material(calc_stiffness, calc_prestress), v=v_field, u=u_field, ), Term.new( "dw_lin_prestress(m.stress, v)", Integral("i", order=4), v_field.field.region, m=get_material(calc_stiffness, calc_prestress), v=v_field, ), ) def get_nls(evaluator): """Get the non-linear solver Args: evaluator: the problem evaluator Returns: the non-linear solver """ return Newton( {}, lin_solver=ScipyDirect({}), fun=evaluator.eval_residual, fun_grad=evaluator.eval_tangent_matrix, ) def get_problem(u_field, v_field, calc_stiffness, calc_prestress, delta_x): """Get the problem Args: u_field: the displacement field v_field: the test function field calc_stiffness: a functioin to calcuate the stiffness tensor calc_prestress: a function to calculate the prestress tensor delta_x: the mesh spacing Returns: the Sfepy problem """ return pipe( get_terms(u_field, v_field, calc_stiffness, calc_prestress), lambda x: Equation("balance_of_forces",
Terms([x[0], x[1]])
sfepy.terms.Terms
"""All Sfepy imports go in this module """ import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field from sfepy.discrete.fem import FEDomain as Domain from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem, ) from sfepy.terms import Term, Terms from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.base.base import output from toolz.curried import pipe, curry, do goptions["verbose"] = False output.set_output(quiet=True) def check(ids): """Check that the fixed displacement nodes have been isolated Args: ids: the isolated IDs Returns the unchanged IDs >>> check([1, 2, 3, 4]) Traceback (most recent call last): ... RuntimeError: length of ids is incorrect """ if len(ids) != 3: raise RuntimeError("length of ids is incorrect") return ids @curry def subdomain(i_x, domain_, eps, coords, **_): """Find the node IDs that will be fixed Args: i_x: the index (either 0 or 1) depends on direction of axes domain_: the Sfepy domain eps: a small value coords: the coordinates of the nodes Returns: the isolated node IDs """ def i_y(): """Switch the index from 0 -> 1 or from 1 -> 0 """ return (i_x + 1) % 2 return pipe( (coords[:, i_x] > -eps) & (coords[:, i_x] < eps), lambda x: (coords[:, i_x] < domain_.get_mesh_bounding_box()[0][i_x] + eps) | x, lambda x: (coords[:, i_x] > domain_.get_mesh_bounding_box()[1][i_x] - eps) | x, lambda x: (coords[:, i_y()] < eps) & (coords[:, i_y()] > -eps) & x, lambda x: np.where(x)[0], check, ) def get_bc(domain, delta_x, index, cond): """Make a displacement boundary condition Args: domain: the Sfepy domain delta_x: the mesh spacing index: the index (either 0 or 1) depends on direction of axes cond: the BC dictionary Returns: the Sfepy boundary condition """ return pipe( Function("fix_points", subdomain(index, domain, delta_x * 1e-3)), lambda x: domain.create_region( "region_fix_points", "vertices by fix_points", "vertex", functions=
Functions([x])
sfepy.discrete.Functions
"""All Sfepy imports go in this module """ import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field from sfepy.discrete.fem import FEDomain as Domain from sfepy.discrete import ( FieldVariable, Material, Integral, Function, Equation, Equations, Problem, ) from sfepy.terms import Term, Terms from sfepy.discrete.conditions import Conditions, EssentialBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.base.base import output from toolz.curried import pipe, curry, do goptions["verbose"] = False output.set_output(quiet=True) def check(ids): """Check that the fixed displacement nodes have been isolated Args: ids: the isolated IDs Returns the unchanged IDs >>> check([1, 2, 3, 4]) Traceback (most recent call last): ... RuntimeError: length of ids is incorrect """ if len(ids) != 3: raise RuntimeError("length of ids is incorrect") return ids @curry def subdomain(i_x, domain_, eps, coords, **_): """Find the node IDs that will be fixed Args: i_x: the index (either 0 or 1) depends on direction of axes domain_: the Sfepy domain eps: a small value coords: the coordinates of the nodes Returns: the isolated node IDs """ def i_y(): """Switch the index from 0 -> 1 or from 1 -> 0 """ return (i_x + 1) % 2 return pipe( (coords[:, i_x] > -eps) & (coords[:, i_x] < eps), lambda x: (coords[:, i_x] < domain_.get_mesh_bounding_box()[0][i_x] + eps) | x, lambda x: (coords[:, i_x] > domain_.get_mesh_bounding_box()[1][i_x] - eps) | x, lambda x: (coords[:, i_y()] < eps) & (coords[:, i_y()] > -eps) & x, lambda x: np.where(x)[0], check, ) def get_bc(domain, delta_x, index, cond): """Make a displacement boundary condition Args: domain: the Sfepy domain delta_x: the mesh spacing index: the index (either 0 or 1) depends on direction of axes cond: the BC dictionary Returns: the Sfepy boundary condition """ return pipe( Function("fix_points", subdomain(index, domain, delta_x * 1e-3)), lambda x: domain.create_region( "region_fix_points", "vertices by fix_points", "vertex", functions=Functions([x]), ), lambda x: EssentialBC("fix_points_BC", x, cond), ) def get_bcs(domain, delta_x): """Get the boundary conditions Args: domain: the Sfepy domain delta_x: the mesh spacing Returns: the boundary conditions """ return Conditions( [ get_bc(domain, delta_x, 1, {"u.0": 0.0}), get_bc(domain, delta_x, 0, {"u.1": 0.0}), ] ) def get_material(calc_stiffness, calc_prestress): """Get the material Args: calc_stiffness: the function for calculating the stiffness tensor calc_prestress: the function for calculating the prestress Returns: the material """ def _material_func_(_, coors, mode=None, **__): if mode == "qp": return dict(D=calc_stiffness(coors), stress=calc_prestress(coors)) return None return Material("m", function=Function("material_func", _material_func_)) def get_uv(shape, delta_x): """Get the fields for the displacement and test function Args: shape: the shape of the domain delta_x: the mesh spacing Returns: tuple of field variables """ return pipe( np.array(shape), lambda x: gen_block_mesh( x * delta_x, x + 1, np.zeros_like(shape), verbose=False ), lambda x: Domain("domain", x), lambda x: x.create_region("region_all", "all"), lambda x: Field.from_args("fu", np.float64, "vector", x, approx_order=2), lambda x: ( FieldVariable("u", "unknown", x), FieldVariable("v", "test", x, primary_var_name="u"), ), ) # field = Field.from_args('fu', np.float64, 'vector', region_all, # pylint: disable=no-member # approx_order=2) def get_terms(u_field, v_field, calc_stiffness, calc_prestress): """Get the terms for the equation Args: u_field: the displacement field v_field: the test function field calc_stiffness: a function to calculate the stiffness tensor calc_prestress: a function to calculate the prestress tensor Returns: a tuple of terms for the equation """ return ( Term.new( "dw_lin_elastic(m.D, v, u)", Integral("i", order=4), v_field.field.region, m=get_material(calc_stiffness, calc_prestress), v=v_field, u=u_field, ), Term.new( "dw_lin_prestress(m.stress, v)", Integral("i", order=4), v_field.field.region, m=get_material(calc_stiffness, calc_prestress), v=v_field, ), ) def get_nls(evaluator): """Get the non-linear solver Args: evaluator: the problem evaluator Returns: the non-linear solver """ return Newton( {}, lin_solver=ScipyDirect({}), fun=evaluator.eval_residual, fun_grad=evaluator.eval_tangent_matrix, ) def get_problem(u_field, v_field, calc_stiffness, calc_prestress, delta_x): """Get the problem Args: u_field: the displacement field v_field: the test function field calc_stiffness: a functioin to calcuate the stiffness tensor calc_prestress: a function to calculate the prestress tensor delta_x: the mesh spacing Returns: the Sfepy problem """ return pipe( get_terms(u_field, v_field, calc_stiffness, calc_prestress), lambda x: Equation("balance_of_forces", Terms([x[0], x[1]])), lambda x: Problem("elasticity", equations=
Equations([x])
sfepy.discrete.Equations
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class =
get_default(solver_class, ScipyDirect)
sfepy.base.base.get_default
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf =
get_default(solver_conf, {})
sfepy.base.base.get_default
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer =
Timer(start=True)
sfepy.base.timing.Timer
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf =
get_default(conf, self.conf)
sfepy.base.base.get_default
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx =
get_default(mtx, self.mtx)
sfepy.base.base.get_default
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status =
get_default(status, self.status)
sfepy.base.base.get_default
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context =
get_default(context, self.context)
sfepy.base.base.get_default
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context)
assert_(mtx.shape[0] == mtx.shape[1] == rhs.shape[0])
sfepy.base.base.assert_
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) assert_(mtx.shape[0] == mtx.shape[1] == rhs.shape[0]) if x0 is not None: assert_(x0.shape[0] == rhs.shape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, context=context, **kwargs) if isinstance(result, tuple): result, n_iter = result else: n_iter = -1 # Number of iterations is undefined/unavailable. elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = n_iter return result return _standard_call def petsc_call(call): """ Decorator handling argument preparation and timing for PETSc-based linear solvers. """ def _petsc_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, comm=None, context=None, **kwargs): timer =
Timer(start=True)
sfepy.base.timing.Timer
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) assert_(mtx.shape[0] == mtx.shape[1] == rhs.shape[0]) if x0 is not None: assert_(x0.shape[0] == rhs.shape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, context=context, **kwargs) if isinstance(result, tuple): result, n_iter = result else: n_iter = -1 # Number of iterations is undefined/unavailable. elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = n_iter return result return _standard_call def petsc_call(call): """ Decorator handling argument preparation and timing for PETSc-based linear solvers. """ def _petsc_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, comm=None, context=None, **kwargs): timer = Timer(start=True) conf =
get_default(conf, self.conf)
sfepy.base.base.get_default
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) assert_(mtx.shape[0] == mtx.shape[1] == rhs.shape[0]) if x0 is not None: assert_(x0.shape[0] == rhs.shape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, context=context, **kwargs) if isinstance(result, tuple): result, n_iter = result else: n_iter = -1 # Number of iterations is undefined/unavailable. elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = n_iter return result return _standard_call def petsc_call(call): """ Decorator handling argument preparation and timing for PETSc-based linear solvers. """ def _petsc_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, comm=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx =
get_default(mtx, self.mtx)
sfepy.base.base.get_default
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) assert_(mtx.shape[0] == mtx.shape[1] == rhs.shape[0]) if x0 is not None: assert_(x0.shape[0] == rhs.shape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, context=context, **kwargs) if isinstance(result, tuple): result, n_iter = result else: n_iter = -1 # Number of iterations is undefined/unavailable. elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = n_iter return result return _standard_call def petsc_call(call): """ Decorator handling argument preparation and timing for PETSc-based linear solvers. """ def _petsc_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, comm=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status =
get_default(status, self.status)
sfepy.base.base.get_default
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) assert_(mtx.shape[0] == mtx.shape[1] == rhs.shape[0]) if x0 is not None: assert_(x0.shape[0] == rhs.shape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, context=context, **kwargs) if isinstance(result, tuple): result, n_iter = result else: n_iter = -1 # Number of iterations is undefined/unavailable. elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = n_iter return result return _standard_call def petsc_call(call): """ Decorator handling argument preparation and timing for PETSc-based linear solvers. """ def _petsc_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, comm=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context =
get_default(context, self.context)
sfepy.base.base.get_default
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) assert_(mtx.shape[0] == mtx.shape[1] == rhs.shape[0]) if x0 is not None: assert_(x0.shape[0] == rhs.shape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, context=context, **kwargs) if isinstance(result, tuple): result, n_iter = result else: n_iter = -1 # Number of iterations is undefined/unavailable. elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = n_iter return result return _standard_call def petsc_call(call): """ Decorator handling argument preparation and timing for PETSc-based linear solvers. """ def _petsc_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, comm=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) comm =
get_default(comm, self.comm)
sfepy.base.base.get_default
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) assert_(mtx.shape[0] == mtx.shape[1] == rhs.shape[0]) if x0 is not None: assert_(x0.shape[0] == rhs.shape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, context=context, **kwargs) if isinstance(result, tuple): result, n_iter = result else: n_iter = -1 # Number of iterations is undefined/unavailable. elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = n_iter return result return _standard_call def petsc_call(call): """ Decorator handling argument preparation and timing for PETSc-based linear solvers. """ def _petsc_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, comm=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) comm = get_default(comm, self.comm) mshape = mtx.size if isinstance(mtx, self.petsc.Mat) else mtx.shape rshape = [rhs.size] if isinstance(rhs, self.petsc.Vec) else rhs.shape
assert_(mshape[0] == mshape[1] == rshape[0])
sfepy.base.base.assert_
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) assert_(mtx.shape[0] == mtx.shape[1] == rhs.shape[0]) if x0 is not None: assert_(x0.shape[0] == rhs.shape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, context=context, **kwargs) if isinstance(result, tuple): result, n_iter = result else: n_iter = -1 # Number of iterations is undefined/unavailable. elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = n_iter return result return _standard_call def petsc_call(call): """ Decorator handling argument preparation and timing for PETSc-based linear solvers. """ def _petsc_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, comm=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) comm = get_default(comm, self.comm) mshape = mtx.size if isinstance(mtx, self.petsc.Mat) else mtx.shape rshape = [rhs.size] if isinstance(rhs, self.petsc.Vec) else rhs.shape assert_(mshape[0] == mshape[1] == rshape[0]) if x0 is not None: xshape = [x0.size] if isinstance(x0, self.petsc.Vec) else x0.shape assert_(xshape[0] == rshape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, comm, context=context, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = self.ksp.getIterationNumber() return result return _petsc_call class ScipyDirect(LinearSolver): """ Direct sparse solver from SciPy. """ name = 'ls.scipy_direct' _parameters = [ ('method', "{'auto', 'umfpack', 'superlu'}", 'auto', False, 'The actual solver to use.'), ('use_presolve', 'bool', False, False, 'If True, pre-factorize the matrix.'), ] def __init__(self, conf, method=None, **kwargs):
LinearSolver.__init__(self, conf, solve=None, **kwargs)
sfepy.solvers.solvers.LinearSolver.__init__
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) assert_(mtx.shape[0] == mtx.shape[1] == rhs.shape[0]) if x0 is not None: assert_(x0.shape[0] == rhs.shape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, context=context, **kwargs) if isinstance(result, tuple): result, n_iter = result else: n_iter = -1 # Number of iterations is undefined/unavailable. elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = n_iter return result return _standard_call def petsc_call(call): """ Decorator handling argument preparation and timing for PETSc-based linear solvers. """ def _petsc_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, comm=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) comm = get_default(comm, self.comm) mshape = mtx.size if isinstance(mtx, self.petsc.Mat) else mtx.shape rshape = [rhs.size] if isinstance(rhs, self.petsc.Vec) else rhs.shape assert_(mshape[0] == mshape[1] == rshape[0]) if x0 is not None: xshape = [x0.size] if isinstance(x0, self.petsc.Vec) else x0.shape assert_(xshape[0] == rshape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, comm, context=context, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = self.ksp.getIterationNumber() return result return _petsc_call class ScipyDirect(LinearSolver): """ Direct sparse solver from SciPy. """ name = 'ls.scipy_direct' _parameters = [ ('method', "{'auto', 'umfpack', 'superlu'}", 'auto', False, 'The actual solver to use.'), ('use_presolve', 'bool', False, False, 'If True, pre-factorize the matrix.'), ] def __init__(self, conf, method=None, **kwargs): LinearSolver.__init__(self, conf, solve=None, **kwargs) um = self.sls = None if method is None: method = self.conf.method aux = try_imports(['import scipy.linsolve as sls', 'import scipy.splinalg.dsolve as sls', 'import scipy.sparse.linalg.dsolve as sls'], 'cannot import scipy sparse direct solvers!') if 'sls' in aux: self.sls = aux['sls'] else: raise ValueError('SuperLU not available!') if method in ['auto', 'umfpack']: aux = try_imports([ 'import scipy.linsolve.umfpack as um', 'import scipy.splinalg.dsolve.umfpack as um', 'import scipy.sparse.linalg.dsolve.umfpack as um', 'import scikits.umfpack as um']) is_umfpack = True if 'um' in aux\ and hasattr(aux['um'], 'UMFPACK_OK') else False if method == 'umfpack' and not is_umfpack: raise ValueError('UMFPACK not available!') elif method == 'superlu': is_umfpack = False else: raise ValueError('uknown solution method! (%s)' % method) if is_umfpack: self.sls.use_solver(useUmfpack=True, assumeSortedIndices=True) else: self.sls.use_solver(useUmfpack=False) @standard_call def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, **kwargs): if conf.use_presolve: self.presolve(mtx) if self.solve is not None: # Matrix is already prefactorized. return self.solve(rhs) else: return self.sls.spsolve(mtx, rhs) def presolve(self, mtx): is_new, mtx_digest = _is_new_matrix(mtx, self.mtx_digest) if is_new: self.solve = self.sls.factorized(mtx) self.mtx_digest = mtx_digest class ScipySuperLU(ScipyDirect): """ SuperLU - direct sparse solver from SciPy. """ name = 'ls.scipy_superlu' _parameters = [ ('use_presolve', 'bool', False, False, 'If True, pre-factorize the matrix.'), ] def __init__(self, conf, **kwargs): ScipyDirect.__init__(self, conf, method='superlu', **kwargs) class ScipyUmfpack(ScipyDirect): """ UMFPACK - direct sparse solver from SciPy. """ name = 'ls.scipy_umfpack' _parameters = [ ('use_presolve', 'bool', False, False, 'If True, pre-factorize the matrix.'), ] def __init__(self, conf, **kwargs): ScipyDirect.__init__(self, conf, method='umfpack', **kwargs) class ScipyIterative(LinearSolver): """ Interface to SciPy iterative solvers. The `eps_r` tolerance is both absolute and relative - the solvers stop when either the relative or the absolute residual is below it. """ name = 'ls.scipy_iterative' _parameters = [ ('method', 'str', 'cg', False, 'The actual solver to use.'), ('setup_precond', 'callable', lambda mtx, context: None, False, """User-supplied function for the preconditioner initialization/setup. It is called as setup_precond(mtx, context), where mtx is the matrix, context is a user-supplied context, and should return one of {sparse matrix, dense matrix, LinearOperator}. """), ('callback', 'callable', None, False, """User-supplied function to call after each iteration. It is called as callback(xk), where xk is the current solution vector, except the gmres method, where the argument is the residual. """), ('i_max', 'int', 100, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-8, False, 'The absolute tolerance for the residual.'), ('eps_r', 'float', 1e-8, False, 'The relative tolerance for the residual.'), ('*', '*', None, False, 'Additional parameters supported by the method.'), ] # All iterative solvers in scipy.sparse.linalg pass a solution vector into # a callback except those below, that take a residual vector. _callbacks_res = ['gmres'] def __init__(self, conf, context=None, **kwargs): import scipy.sparse.linalg.isolve as la
LinearSolver.__init__(self, conf, context=context, **kwargs)
sfepy.solvers.solvers.LinearSolver.__init__
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) assert_(mtx.shape[0] == mtx.shape[1] == rhs.shape[0]) if x0 is not None: assert_(x0.shape[0] == rhs.shape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, context=context, **kwargs) if isinstance(result, tuple): result, n_iter = result else: n_iter = -1 # Number of iterations is undefined/unavailable. elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = n_iter return result return _standard_call def petsc_call(call): """ Decorator handling argument preparation and timing for PETSc-based linear solvers. """ def _petsc_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, comm=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) comm = get_default(comm, self.comm) mshape = mtx.size if isinstance(mtx, self.petsc.Mat) else mtx.shape rshape = [rhs.size] if isinstance(rhs, self.petsc.Vec) else rhs.shape assert_(mshape[0] == mshape[1] == rshape[0]) if x0 is not None: xshape = [x0.size] if isinstance(x0, self.petsc.Vec) else x0.shape assert_(xshape[0] == rshape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, comm, context=context, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = self.ksp.getIterationNumber() return result return _petsc_call class ScipyDirect(LinearSolver): """ Direct sparse solver from SciPy. """ name = 'ls.scipy_direct' _parameters = [ ('method', "{'auto', 'umfpack', 'superlu'}", 'auto', False, 'The actual solver to use.'), ('use_presolve', 'bool', False, False, 'If True, pre-factorize the matrix.'), ] def __init__(self, conf, method=None, **kwargs): LinearSolver.__init__(self, conf, solve=None, **kwargs) um = self.sls = None if method is None: method = self.conf.method aux = try_imports(['import scipy.linsolve as sls', 'import scipy.splinalg.dsolve as sls', 'import scipy.sparse.linalg.dsolve as sls'], 'cannot import scipy sparse direct solvers!') if 'sls' in aux: self.sls = aux['sls'] else: raise ValueError('SuperLU not available!') if method in ['auto', 'umfpack']: aux = try_imports([ 'import scipy.linsolve.umfpack as um', 'import scipy.splinalg.dsolve.umfpack as um', 'import scipy.sparse.linalg.dsolve.umfpack as um', 'import scikits.umfpack as um']) is_umfpack = True if 'um' in aux\ and hasattr(aux['um'], 'UMFPACK_OK') else False if method == 'umfpack' and not is_umfpack: raise ValueError('UMFPACK not available!') elif method == 'superlu': is_umfpack = False else: raise ValueError('uknown solution method! (%s)' % method) if is_umfpack: self.sls.use_solver(useUmfpack=True, assumeSortedIndices=True) else: self.sls.use_solver(useUmfpack=False) @standard_call def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, **kwargs): if conf.use_presolve: self.presolve(mtx) if self.solve is not None: # Matrix is already prefactorized. return self.solve(rhs) else: return self.sls.spsolve(mtx, rhs) def presolve(self, mtx): is_new, mtx_digest = _is_new_matrix(mtx, self.mtx_digest) if is_new: self.solve = self.sls.factorized(mtx) self.mtx_digest = mtx_digest class ScipySuperLU(ScipyDirect): """ SuperLU - direct sparse solver from SciPy. """ name = 'ls.scipy_superlu' _parameters = [ ('use_presolve', 'bool', False, False, 'If True, pre-factorize the matrix.'), ] def __init__(self, conf, **kwargs): ScipyDirect.__init__(self, conf, method='superlu', **kwargs) class ScipyUmfpack(ScipyDirect): """ UMFPACK - direct sparse solver from SciPy. """ name = 'ls.scipy_umfpack' _parameters = [ ('use_presolve', 'bool', False, False, 'If True, pre-factorize the matrix.'), ] def __init__(self, conf, **kwargs): ScipyDirect.__init__(self, conf, method='umfpack', **kwargs) class ScipyIterative(LinearSolver): """ Interface to SciPy iterative solvers. The `eps_r` tolerance is both absolute and relative - the solvers stop when either the relative or the absolute residual is below it. """ name = 'ls.scipy_iterative' _parameters = [ ('method', 'str', 'cg', False, 'The actual solver to use.'), ('setup_precond', 'callable', lambda mtx, context: None, False, """User-supplied function for the preconditioner initialization/setup. It is called as setup_precond(mtx, context), where mtx is the matrix, context is a user-supplied context, and should return one of {sparse matrix, dense matrix, LinearOperator}. """), ('callback', 'callable', None, False, """User-supplied function to call after each iteration. It is called as callback(xk), where xk is the current solution vector, except the gmres method, where the argument is the residual. """), ('i_max', 'int', 100, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-8, False, 'The absolute tolerance for the residual.'), ('eps_r', 'float', 1e-8, False, 'The relative tolerance for the residual.'), ('*', '*', None, False, 'Additional parameters supported by the method.'), ] # All iterative solvers in scipy.sparse.linalg pass a solution vector into # a callback except those below, that take a residual vector. _callbacks_res = ['gmres'] def __init__(self, conf, context=None, **kwargs): import scipy.sparse.linalg.isolve as la LinearSolver.__init__(self, conf, context=context, **kwargs) try: solver = getattr(la, self.conf.method) except AttributeError: output('scipy solver %s does not exist!' % self.conf.method) output('using cg instead') solver = la.cg self.solver = solver self.converged_reasons = { 0 : 'successful exit', 1 : 'number of iterations', -1 : 'illegal input or breakdown', } @standard_call def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): solver_kwargs = self.build_solver_kwargs(conf) eps_a =
get_default(eps_a, self.conf.eps_a)
sfepy.base.base.get_default
from __future__ import absolute_import import hashlib import numpy as nm import warnings import scipy.sparse as sps import six from six.moves import range warnings.simplefilter('ignore', sps.SparseEfficiencyWarning) from sfepy.base.base import output, get_default, assert_, try_imports from sfepy.base.timing import Timer from sfepy.solvers.solvers import LinearSolver def solve(mtx, rhs, solver_class=None, solver_conf=None): """ Solve the linear system with the matrix `mtx` and the right-hand side `rhs`. Convenience wrapper around the linear solver classes below. """ solver_class = get_default(solver_class, ScipyDirect) solver_conf = get_default(solver_conf, {}) solver = solver_class(solver_conf, mtx=mtx) solution = solver(rhs) return solution def _get_cs_matrix_hash(mtx, chunk_size=100000): def _gen_array_chunks(arr): ii = 0 while len(arr[ii:]): yield arr[ii:ii+chunk_size].tobytes() ii += chunk_size sha1 = hashlib.sha1() for chunk in _gen_array_chunks(mtx.indptr): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.indices): sha1.update(chunk) for chunk in _gen_array_chunks(mtx.data): sha1.update(chunk) digest = sha1.hexdigest() return digest def _is_new_matrix(mtx, mtx_digest, force_reuse=False): if not isinstance(mtx, sps.csr_matrix): return True, mtx_digest if force_reuse: return False, mtx_digest id0, digest0 = mtx_digest id1 = id(mtx) digest1 = _get_cs_matrix_hash(mtx) if (id1 == id0) and (digest1 == digest0): return False, (id1, digest1) return True, (id1, digest1) def standard_call(call): """ Decorator handling argument preparation and timing for linear solvers. """ def _standard_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) assert_(mtx.shape[0] == mtx.shape[1] == rhs.shape[0]) if x0 is not None: assert_(x0.shape[0] == rhs.shape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, context=context, **kwargs) if isinstance(result, tuple): result, n_iter = result else: n_iter = -1 # Number of iterations is undefined/unavailable. elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = n_iter return result return _standard_call def petsc_call(call): """ Decorator handling argument preparation and timing for PETSc-based linear solvers. """ def _petsc_call(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, comm=None, context=None, **kwargs): timer = Timer(start=True) conf = get_default(conf, self.conf) mtx = get_default(mtx, self.mtx) status = get_default(status, self.status) context = get_default(context, self.context) comm = get_default(comm, self.comm) mshape = mtx.size if isinstance(mtx, self.petsc.Mat) else mtx.shape rshape = [rhs.size] if isinstance(rhs, self.petsc.Vec) else rhs.shape assert_(mshape[0] == mshape[1] == rshape[0]) if x0 is not None: xshape = [x0.size] if isinstance(x0, self.petsc.Vec) else x0.shape assert_(xshape[0] == rshape[0]) result = call(self, rhs, x0, conf, eps_a, eps_r, i_max, mtx, status, comm, context=context, **kwargs) elapsed = timer.stop() if status is not None: status['time'] = elapsed status['n_iter'] = self.ksp.getIterationNumber() return result return _petsc_call class ScipyDirect(LinearSolver): """ Direct sparse solver from SciPy. """ name = 'ls.scipy_direct' _parameters = [ ('method', "{'auto', 'umfpack', 'superlu'}", 'auto', False, 'The actual solver to use.'), ('use_presolve', 'bool', False, False, 'If True, pre-factorize the matrix.'), ] def __init__(self, conf, method=None, **kwargs): LinearSolver.__init__(self, conf, solve=None, **kwargs) um = self.sls = None if method is None: method = self.conf.method aux = try_imports(['import scipy.linsolve as sls', 'import scipy.splinalg.dsolve as sls', 'import scipy.sparse.linalg.dsolve as sls'], 'cannot import scipy sparse direct solvers!') if 'sls' in aux: self.sls = aux['sls'] else: raise ValueError('SuperLU not available!') if method in ['auto', 'umfpack']: aux = try_imports([ 'import scipy.linsolve.umfpack as um', 'import scipy.splinalg.dsolve.umfpack as um', 'import scipy.sparse.linalg.dsolve.umfpack as um', 'import scikits.umfpack as um']) is_umfpack = True if 'um' in aux\ and hasattr(aux['um'], 'UMFPACK_OK') else False if method == 'umfpack' and not is_umfpack: raise ValueError('UMFPACK not available!') elif method == 'superlu': is_umfpack = False else: raise ValueError('uknown solution method! (%s)' % method) if is_umfpack: self.sls.use_solver(useUmfpack=True, assumeSortedIndices=True) else: self.sls.use_solver(useUmfpack=False) @standard_call def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, **kwargs): if conf.use_presolve: self.presolve(mtx) if self.solve is not None: # Matrix is already prefactorized. return self.solve(rhs) else: return self.sls.spsolve(mtx, rhs) def presolve(self, mtx): is_new, mtx_digest = _is_new_matrix(mtx, self.mtx_digest) if is_new: self.solve = self.sls.factorized(mtx) self.mtx_digest = mtx_digest class ScipySuperLU(ScipyDirect): """ SuperLU - direct sparse solver from SciPy. """ name = 'ls.scipy_superlu' _parameters = [ ('use_presolve', 'bool', False, False, 'If True, pre-factorize the matrix.'), ] def __init__(self, conf, **kwargs): ScipyDirect.__init__(self, conf, method='superlu', **kwargs) class ScipyUmfpack(ScipyDirect): """ UMFPACK - direct sparse solver from SciPy. """ name = 'ls.scipy_umfpack' _parameters = [ ('use_presolve', 'bool', False, False, 'If True, pre-factorize the matrix.'), ] def __init__(self, conf, **kwargs): ScipyDirect.__init__(self, conf, method='umfpack', **kwargs) class ScipyIterative(LinearSolver): """ Interface to SciPy iterative solvers. The `eps_r` tolerance is both absolute and relative - the solvers stop when either the relative or the absolute residual is below it. """ name = 'ls.scipy_iterative' _parameters = [ ('method', 'str', 'cg', False, 'The actual solver to use.'), ('setup_precond', 'callable', lambda mtx, context: None, False, """User-supplied function for the preconditioner initialization/setup. It is called as setup_precond(mtx, context), where mtx is the matrix, context is a user-supplied context, and should return one of {sparse matrix, dense matrix, LinearOperator}. """), ('callback', 'callable', None, False, """User-supplied function to call after each iteration. It is called as callback(xk), where xk is the current solution vector, except the gmres method, where the argument is the residual. """), ('i_max', 'int', 100, False, 'The maximum number of iterations.'), ('eps_a', 'float', 1e-8, False, 'The absolute tolerance for the residual.'), ('eps_r', 'float', 1e-8, False, 'The relative tolerance for the residual.'), ('*', '*', None, False, 'Additional parameters supported by the method.'), ] # All iterative solvers in scipy.sparse.linalg pass a solution vector into # a callback except those below, that take a residual vector. _callbacks_res = ['gmres'] def __init__(self, conf, context=None, **kwargs): import scipy.sparse.linalg.isolve as la LinearSolver.__init__(self, conf, context=context, **kwargs) try: solver = getattr(la, self.conf.method) except AttributeError: output('scipy solver %s does not exist!' % self.conf.method) output('using cg instead') solver = la.cg self.solver = solver self.converged_reasons = { 0 : 'successful exit', 1 : 'number of iterations', -1 : 'illegal input or breakdown', } @standard_call def __call__(self, rhs, x0=None, conf=None, eps_a=None, eps_r=None, i_max=None, mtx=None, status=None, context=None, **kwargs): solver_kwargs = self.build_solver_kwargs(conf) eps_a = get_default(eps_a, self.conf.eps_a) eps_r =
get_default(eps_r, self.conf.eps_r)
sfepy.base.base.get_default