prompt
stringlengths
174
59.5k
completion
stringlengths
7
228
api
stringlengths
12
64
""" Functions to visualize quadrature points in reference elements. """ import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output from sfepy.postprocess.plot_dofs import _get_axes, _to2d from sfepy.postprocess.plot_facets import plot_geometry def _get_qp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement aux = Integral('aux', order=order) coors, weights = aux.get_qp(geometry) true_order = aux.qps[geometry].order output('geometry:', geometry, 'order:', order, 'num. points:', coors.shape[0], 'true_order:', true_order) output('min. weight:', weights.min()) output('max. weight:', weights.max()) return GeometryElement(geometry), coors, weights def _get_bqp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement from sfepy.discrete.fem import Mesh, FEDomain, Field gel = GeometryElement(geometry) mesh = Mesh.from_data('aux', gel.coors, None, [gel.conn[None, :]], [[0]], [geometry]) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') surf = domain.create_region('Surf', 'vertices of surface', 'facet') field = Field.from_args('f', nm.float64, shape=1, region=omega, approx_order=1) field.setup_surface_data(surf) integral = Integral('aux', order=order) field.create_bqp('Surf', integral) sd = field.surface_data['Surf'] qp = field.qp_coors[(integral.order, sd.bkey)] output('geometry:', geometry, 'order:', order, 'num. points:', qp.vals.shape[1], 'true_order:', integral.qps[gel.surface_facet_name].order) output('min. weight:', qp.weights.min()) output('max. weight:', qp.weights.max()) return (gel, qp.vals.reshape((-1, mesh.dim)), nm.tile(qp.weights, qp.vals.shape[0])) def plot_weighted_points(ax, coors, weights, min_radius=10, max_radius=50, show_colorbar=False): """ Plot points with given coordinates as circles/spheres with radii given by weights. """ dim = coors.shape[1] ax =
_get_axes(ax, dim)
sfepy.postprocess.plot_dofs._get_axes
""" Functions to visualize quadrature points in reference elements. """ import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output from sfepy.postprocess.plot_dofs import _get_axes, _to2d from sfepy.postprocess.plot_facets import plot_geometry def _get_qp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement aux = Integral('aux', order=order) coors, weights = aux.get_qp(geometry) true_order = aux.qps[geometry].order output('geometry:', geometry, 'order:', order, 'num. points:', coors.shape[0], 'true_order:', true_order) output('min. weight:', weights.min()) output('max. weight:', weights.max()) return GeometryElement(geometry), coors, weights def _get_bqp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement from sfepy.discrete.fem import Mesh, FEDomain, Field gel = GeometryElement(geometry) mesh = Mesh.from_data('aux', gel.coors, None, [gel.conn[None, :]], [[0]], [geometry]) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') surf = domain.create_region('Surf', 'vertices of surface', 'facet') field = Field.from_args('f', nm.float64, shape=1, region=omega, approx_order=1) field.setup_surface_data(surf) integral = Integral('aux', order=order) field.create_bqp('Surf', integral) sd = field.surface_data['Surf'] qp = field.qp_coors[(integral.order, sd.bkey)] output('geometry:', geometry, 'order:', order, 'num. points:', qp.vals.shape[1], 'true_order:', integral.qps[gel.surface_facet_name].order) output('min. weight:', qp.weights.min()) output('max. weight:', qp.weights.max()) return (gel, qp.vals.reshape((-1, mesh.dim)), nm.tile(qp.weights, qp.vals.shape[0])) def plot_weighted_points(ax, coors, weights, min_radius=10, max_radius=50, show_colorbar=False): """ Plot points with given coordinates as circles/spheres with radii given by weights. """ dim = coors.shape[1] ax = _get_axes(ax, dim) wmin, wmax = weights.min(), weights.max() if (wmax - wmin) < 1e-12: nweights = weights * max_radius / wmax else: nweights = ((weights - wmin) * (max_radius - min_radius) / (wmax - wmin) + min_radius) coors =
_to2d(coors)
sfepy.postprocess.plot_dofs._to2d
""" Functions to visualize quadrature points in reference elements. """ import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output from sfepy.postprocess.plot_dofs import _get_axes, _to2d from sfepy.postprocess.plot_facets import plot_geometry def _get_qp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement aux = Integral('aux', order=order) coors, weights = aux.get_qp(geometry) true_order = aux.qps[geometry].order output('geometry:', geometry, 'order:', order, 'num. points:', coors.shape[0], 'true_order:', true_order) output('min. weight:', weights.min()) output('max. weight:', weights.max()) return GeometryElement(geometry), coors, weights def _get_bqp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement from sfepy.discrete.fem import Mesh, FEDomain, Field gel = GeometryElement(geometry) mesh = Mesh.from_data('aux', gel.coors, None, [gel.conn[None, :]], [[0]], [geometry]) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') surf = domain.create_region('Surf', 'vertices of surface', 'facet') field = Field.from_args('f', nm.float64, shape=1, region=omega, approx_order=1) field.setup_surface_data(surf) integral = Integral('aux', order=order) field.create_bqp('Surf', integral) sd = field.surface_data['Surf'] qp = field.qp_coors[(integral.order, sd.bkey)] output('geometry:', geometry, 'order:', order, 'num. points:', qp.vals.shape[1], 'true_order:', integral.qps[gel.surface_facet_name].order) output('min. weight:', qp.weights.min()) output('max. weight:', qp.weights.max()) return (gel, qp.vals.reshape((-1, mesh.dim)), nm.tile(qp.weights, qp.vals.shape[0])) def plot_weighted_points(ax, coors, weights, min_radius=10, max_radius=50, show_colorbar=False): """ Plot points with given coordinates as circles/spheres with radii given by weights. """ dim = coors.shape[1] ax = _get_axes(ax, dim) wmin, wmax = weights.min(), weights.max() if (wmax - wmin) < 1e-12: nweights = weights * max_radius / wmax else: nweights = ((weights - wmin) * (max_radius - min_radius) / (wmax - wmin) + min_radius) coors = _to2d(coors) sc = ax.scatter(*coors.T, s=nweights, c=weights, alpha=1) if show_colorbar: plt.colorbar(sc) return ax def label_points(ax, coors): """ Label points with their indices. """ dim = coors.shape[1] ax =
_get_axes(ax, dim)
sfepy.postprocess.plot_dofs._get_axes
""" Functions to visualize quadrature points in reference elements. """ import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output from sfepy.postprocess.plot_dofs import _get_axes, _to2d from sfepy.postprocess.plot_facets import plot_geometry def _get_qp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement aux = Integral('aux', order=order) coors, weights = aux.get_qp(geometry) true_order = aux.qps[geometry].order output('geometry:', geometry, 'order:', order, 'num. points:', coors.shape[0], 'true_order:', true_order) output('min. weight:', weights.min()) output('max. weight:', weights.max()) return GeometryElement(geometry), coors, weights def _get_bqp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement from sfepy.discrete.fem import Mesh, FEDomain, Field gel = GeometryElement(geometry) mesh = Mesh.from_data('aux', gel.coors, None, [gel.conn[None, :]], [[0]], [geometry]) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') surf = domain.create_region('Surf', 'vertices of surface', 'facet') field = Field.from_args('f', nm.float64, shape=1, region=omega, approx_order=1) field.setup_surface_data(surf) integral = Integral('aux', order=order) field.create_bqp('Surf', integral) sd = field.surface_data['Surf'] qp = field.qp_coors[(integral.order, sd.bkey)] output('geometry:', geometry, 'order:', order, 'num. points:', qp.vals.shape[1], 'true_order:', integral.qps[gel.surface_facet_name].order) output('min. weight:', qp.weights.min()) output('max. weight:', qp.weights.max()) return (gel, qp.vals.reshape((-1, mesh.dim)), nm.tile(qp.weights, qp.vals.shape[0])) def plot_weighted_points(ax, coors, weights, min_radius=10, max_radius=50, show_colorbar=False): """ Plot points with given coordinates as circles/spheres with radii given by weights. """ dim = coors.shape[1] ax = _get_axes(ax, dim) wmin, wmax = weights.min(), weights.max() if (wmax - wmin) < 1e-12: nweights = weights * max_radius / wmax else: nweights = ((weights - wmin) * (max_radius - min_radius) / (wmax - wmin) + min_radius) coors = _to2d(coors) sc = ax.scatter(*coors.T, s=nweights, c=weights, alpha=1) if show_colorbar: plt.colorbar(sc) return ax def label_points(ax, coors): """ Label points with their indices. """ dim = coors.shape[1] ax = _get_axes(ax, dim) shift = 0.02 * (coors.max(0) - coors.min(0)) ccs = coors + shift for ic, cc in enumerate(ccs): ax.text(*cc, s='%d' % ic, color='b') def plot_quadrature(ax, geometry, order, boundary=False, min_radius=10, max_radius=50, show_colorbar=False, show_labels=False): """ Plot quadrature points for the given geometry and integration order. The points are plotted as circles/spheres with radii given by quadrature weights - the weights are mapped to [`min_radius`, `max_radius`] interval. """ if not boundary: gel, coors, weights = _get_qp(geometry, order) else: gel, coors, weights = _get_bqp(geometry, order) dim = coors.shape[1] ax =
_get_axes(ax, dim)
sfepy.postprocess.plot_dofs._get_axes
""" Functions to visualize quadrature points in reference elements. """ import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output from sfepy.postprocess.plot_dofs import _get_axes, _to2d from sfepy.postprocess.plot_facets import plot_geometry def _get_qp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement aux = Integral('aux', order=order) coors, weights = aux.get_qp(geometry) true_order = aux.qps[geometry].order output('geometry:', geometry, 'order:', order, 'num. points:', coors.shape[0], 'true_order:', true_order) output('min. weight:', weights.min()) output('max. weight:', weights.max()) return GeometryElement(geometry), coors, weights def _get_bqp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement from sfepy.discrete.fem import Mesh, FEDomain, Field gel = GeometryElement(geometry) mesh = Mesh.from_data('aux', gel.coors, None, [gel.conn[None, :]], [[0]], [geometry]) domain = FEDomain('domain', mesh) omega = domain.create_region('Omega', 'all') surf = domain.create_region('Surf', 'vertices of surface', 'facet') field = Field.from_args('f', nm.float64, shape=1, region=omega, approx_order=1) field.setup_surface_data(surf) integral = Integral('aux', order=order) field.create_bqp('Surf', integral) sd = field.surface_data['Surf'] qp = field.qp_coors[(integral.order, sd.bkey)] output('geometry:', geometry, 'order:', order, 'num. points:', qp.vals.shape[1], 'true_order:', integral.qps[gel.surface_facet_name].order) output('min. weight:', qp.weights.min()) output('max. weight:', qp.weights.max()) return (gel, qp.vals.reshape((-1, mesh.dim)), nm.tile(qp.weights, qp.vals.shape[0])) def plot_weighted_points(ax, coors, weights, min_radius=10, max_radius=50, show_colorbar=False): """ Plot points with given coordinates as circles/spheres with radii given by weights. """ dim = coors.shape[1] ax = _get_axes(ax, dim) wmin, wmax = weights.min(), weights.max() if (wmax - wmin) < 1e-12: nweights = weights * max_radius / wmax else: nweights = ((weights - wmin) * (max_radius - min_radius) / (wmax - wmin) + min_radius) coors = _to2d(coors) sc = ax.scatter(*coors.T, s=nweights, c=weights, alpha=1) if show_colorbar: plt.colorbar(sc) return ax def label_points(ax, coors): """ Label points with their indices. """ dim = coors.shape[1] ax = _get_axes(ax, dim) shift = 0.02 * (coors.max(0) - coors.min(0)) ccs = coors + shift for ic, cc in enumerate(ccs): ax.text(*cc, s='%d' % ic, color='b') def plot_quadrature(ax, geometry, order, boundary=False, min_radius=10, max_radius=50, show_colorbar=False, show_labels=False): """ Plot quadrature points for the given geometry and integration order. The points are plotted as circles/spheres with radii given by quadrature weights - the weights are mapped to [`min_radius`, `max_radius`] interval. """ if not boundary: gel, coors, weights = _get_qp(geometry, order) else: gel, coors, weights = _get_bqp(geometry, order) dim = coors.shape[1] ax = _get_axes(ax, dim)
plot_geometry(ax, gel)
sfepy.postprocess.plot_facets.plot_geometry
""" Functions to visualize quadrature points in reference elements. """ import numpy as nm import matplotlib.pyplot as plt from sfepy.base.base import output from sfepy.postprocess.plot_dofs import _get_axes, _to2d from sfepy.postprocess.plot_facets import plot_geometry def _get_qp(geometry, order): from sfepy.discrete import Integral from sfepy.discrete.fem.geometry_element import GeometryElement aux = Integral('aux', order=order) coors, weights = aux.get_qp(geometry) true_order = aux.qps[geometry].order output('geometry:', geometry, 'order:', order, 'num. points:', coors.shape[0], 'true_order:', true_order) output('min. weight:', weights.min()) output('max. weight:', weights.max()) return
GeometryElement(geometry)
sfepy.discrete.fem.geometry_element.GeometryElement
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False
output.set_output(quiet=True)
sfepy.base.base.output.set_output
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func =
Function('material_func', _material_func_)
sfepy.discrete.Function
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return
Material('m', function=material_func)
sfepy.discrete.Material
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points =
Function('fix_x_points', fix_x_points_)
sfepy.discrete.Function
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return
EssentialBC('fix_points_BC', region_fix_points, fix_points_dict)
sfepy.discrete.conditions.EssentialBC
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points =
Function('shift_x_points', shift_x_points_)
sfepy.discrete.Function
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return
Conditions([fix_points_BC, shift_points_BC])
sfepy.discrete.conditions.Conditions
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus =
Function('xplus', xplus_)
sfepy.discrete.Function
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus =
Function('xminus', xminus_)
sfepy.discrete.Function
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane =
Function('match_x_plane', per.match_x_plane)
sfepy.discrete.Function
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift =
Function('shift', shift_)
sfepy.discrete.Function
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return
Conditions([lcbc])
sfepy.discrete.conditions.Conditions
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus =
Function(plus_string, plus_)
sfepy.discrete.Function
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus =
Function(minus_string, minus_)
sfepy.discrete.Function
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.0': 'u.0'} bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _get_periodicBC_YZ(self, domain, dim): dims = domain.get_mesh_bounding_box().shape[1] dim_dict = {0: ('x', per.match_x_plane), 1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] plus_ = self._subdomain_func(**{dim_string: (max_,)}) minus_ = self._subdomain_func(**{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus =
Function(plus_string, plus_)
sfepy.discrete.Function
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.0': 'u.0'} bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _get_periodicBC_YZ(self, domain, dim): dims = domain.get_mesh_bounding_box().shape[1] dim_dict = {0: ('x', per.match_x_plane), 1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] plus_ = self._subdomain_func(**{dim_string: (max_,)}) minus_ = self._subdomain_func(**{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus =
Function(minus_string, minus_)
sfepy.discrete.Function
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.0': 'u.0'} bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _get_periodicBC_YZ(self, domain, dim): dims = domain.get_mesh_bounding_box().shape[1] dim_dict = {0: ('x', per.match_x_plane), 1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] plus_ = self._subdomain_func(**{dim_string: (max_,)}) minus_ = self._subdomain_func(**{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.1': 'u.1'} if dims == 3: bc_dict['u.2'] = 'u.2' bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _solve(self, property_array): """ Solve the Sfepy problem for one sample. Args: property_array: array of shape (n_x, n_y, 2) where the last index is for Lame's parameter and shear modulus, respectively. Returns: the strain field of shape (n_x, n_y, 2) where the last index represents the x and y displacements """ shape = property_array.shape[:-1] mesh = self._get_mesh(shape) domain =
Domain('domain', mesh)
sfepy.discrete.fem.Domain
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.0': 'u.0'} bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _get_periodicBC_YZ(self, domain, dim): dims = domain.get_mesh_bounding_box().shape[1] dim_dict = {0: ('x', per.match_x_plane), 1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] plus_ = self._subdomain_func(**{dim_string: (max_,)}) minus_ = self._subdomain_func(**{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.1': 'u.1'} if dims == 3: bc_dict['u.2'] = 'u.2' bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _solve(self, property_array): """ Solve the Sfepy problem for one sample. Args: property_array: array of shape (n_x, n_y, 2) where the last index is for Lame's parameter and shear modulus, respectively. Returns: the strain field of shape (n_x, n_y, 2) where the last index represents the x and y displacements """ shape = property_array.shape[:-1] mesh = self._get_mesh(shape) domain = Domain('domain', mesh) region_all = domain.create_region('region_all', 'all') field = Field.from_args('fu', np.float64, 'vector', region_all, approx_order=2) u =
FieldVariable('u', 'unknown', field)
sfepy.discrete.FieldVariable
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.0': 'u.0'} bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _get_periodicBC_YZ(self, domain, dim): dims = domain.get_mesh_bounding_box().shape[1] dim_dict = {0: ('x', per.match_x_plane), 1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] plus_ = self._subdomain_func(**{dim_string: (max_,)}) minus_ = self._subdomain_func(**{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.1': 'u.1'} if dims == 3: bc_dict['u.2'] = 'u.2' bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _solve(self, property_array): """ Solve the Sfepy problem for one sample. Args: property_array: array of shape (n_x, n_y, 2) where the last index is for Lame's parameter and shear modulus, respectively. Returns: the strain field of shape (n_x, n_y, 2) where the last index represents the x and y displacements """ shape = property_array.shape[:-1] mesh = self._get_mesh(shape) domain = Domain('domain', mesh) region_all = domain.create_region('region_all', 'all') field = Field.from_args('fu', np.float64, 'vector', region_all, approx_order=2) u = FieldVariable('u', 'unknown', field) v =
FieldVariable('v', 'test', field, primary_var_name='u')
sfepy.discrete.FieldVariable
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.0': 'u.0'} bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _get_periodicBC_YZ(self, domain, dim): dims = domain.get_mesh_bounding_box().shape[1] dim_dict = {0: ('x', per.match_x_plane), 1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] plus_ = self._subdomain_func(**{dim_string: (max_,)}) minus_ = self._subdomain_func(**{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.1': 'u.1'} if dims == 3: bc_dict['u.2'] = 'u.2' bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _solve(self, property_array): """ Solve the Sfepy problem for one sample. Args: property_array: array of shape (n_x, n_y, 2) where the last index is for Lame's parameter and shear modulus, respectively. Returns: the strain field of shape (n_x, n_y, 2) where the last index represents the x and y displacements """ shape = property_array.shape[:-1] mesh = self._get_mesh(shape) domain = Domain('domain', mesh) region_all = domain.create_region('region_all', 'all') field = Field.from_args('fu', np.float64, 'vector', region_all, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = self._get_material(property_array, domain) integral =
Integral('i', order=4)
sfepy.discrete.Integral
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.0': 'u.0'} bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _get_periodicBC_YZ(self, domain, dim): dims = domain.get_mesh_bounding_box().shape[1] dim_dict = {0: ('x', per.match_x_plane), 1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] plus_ = self._subdomain_func(**{dim_string: (max_,)}) minus_ = self._subdomain_func(**{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.1': 'u.1'} if dims == 3: bc_dict['u.2'] = 'u.2' bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _solve(self, property_array): """ Solve the Sfepy problem for one sample. Args: property_array: array of shape (n_x, n_y, 2) where the last index is for Lame's parameter and shear modulus, respectively. Returns: the strain field of shape (n_x, n_y, 2) where the last index represents the x and y displacements """ shape = property_array.shape[:-1] mesh = self._get_mesh(shape) domain = Domain('domain', mesh) region_all = domain.create_region('region_all', 'all') field = Field.from_args('fu', np.float64, 'vector', region_all, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = self._get_material(property_array, domain) integral = Integral('i', order=4) t1 = Term.new('dw_lin_elastic_iso(m.lam, m.mu, v, u)', integral, region_all, m=m, v=v, u=u) eq =
Equation('balance_of_forces', t1)
sfepy.discrete.Equation
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.0': 'u.0'} bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _get_periodicBC_YZ(self, domain, dim): dims = domain.get_mesh_bounding_box().shape[1] dim_dict = {0: ('x', per.match_x_plane), 1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] plus_ = self._subdomain_func(**{dim_string: (max_,)}) minus_ = self._subdomain_func(**{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.1': 'u.1'} if dims == 3: bc_dict['u.2'] = 'u.2' bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _solve(self, property_array): """ Solve the Sfepy problem for one sample. Args: property_array: array of shape (n_x, n_y, 2) where the last index is for Lame's parameter and shear modulus, respectively. Returns: the strain field of shape (n_x, n_y, 2) where the last index represents the x and y displacements """ shape = property_array.shape[:-1] mesh = self._get_mesh(shape) domain = Domain('domain', mesh) region_all = domain.create_region('region_all', 'all') field = Field.from_args('fu', np.float64, 'vector', region_all, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = self._get_material(property_array, domain) integral = Integral('i', order=4) t1 = Term.new('dw_lin_elastic_iso(m.lam, m.mu, v, u)', integral, region_all, m=m, v=v, u=u) eq = Equation('balance_of_forces', t1) eqs =
Equations([eq])
sfepy.discrete.Equations
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.0': 'u.0'} bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _get_periodicBC_YZ(self, domain, dim): dims = domain.get_mesh_bounding_box().shape[1] dim_dict = {0: ('x', per.match_x_plane), 1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] plus_ = self._subdomain_func(**{dim_string: (max_,)}) minus_ = self._subdomain_func(**{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.1': 'u.1'} if dims == 3: bc_dict['u.2'] = 'u.2' bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _solve(self, property_array): """ Solve the Sfepy problem for one sample. Args: property_array: array of shape (n_x, n_y, 2) where the last index is for Lame's parameter and shear modulus, respectively. Returns: the strain field of shape (n_x, n_y, 2) where the last index represents the x and y displacements """ shape = property_array.shape[:-1] mesh = self._get_mesh(shape) domain = Domain('domain', mesh) region_all = domain.create_region('region_all', 'all') field = Field.from_args('fu', np.float64, 'vector', region_all, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = self._get_material(property_array, domain) integral = Integral('i', order=4) t1 = Term.new('dw_lin_elastic_iso(m.lam, m.mu, v, u)', integral, region_all, m=m, v=v, u=u) eq = Equation('balance_of_forces', t1) eqs = Equations([eq]) epbcs, functions = self._get_periodicBCs(domain) ebcs = self._get_displacementBCs(domain) lcbcs = self._get_linear_combinationBCs(domain) ls =
ScipyDirect({})
sfepy.solvers.ls.ScipyDirect
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.0': 'u.0'} bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _get_periodicBC_YZ(self, domain, dim): dims = domain.get_mesh_bounding_box().shape[1] dim_dict = {0: ('x', per.match_x_plane), 1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] plus_ = self._subdomain_func(**{dim_string: (max_,)}) minus_ = self._subdomain_func(**{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.1': 'u.1'} if dims == 3: bc_dict['u.2'] = 'u.2' bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _solve(self, property_array): """ Solve the Sfepy problem for one sample. Args: property_array: array of shape (n_x, n_y, 2) where the last index is for Lame's parameter and shear modulus, respectively. Returns: the strain field of shape (n_x, n_y, 2) where the last index represents the x and y displacements """ shape = property_array.shape[:-1] mesh = self._get_mesh(shape) domain = Domain('domain', mesh) region_all = domain.create_region('region_all', 'all') field = Field.from_args('fu', np.float64, 'vector', region_all, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = self._get_material(property_array, domain) integral = Integral('i', order=4) t1 = Term.new('dw_lin_elastic_iso(m.lam, m.mu, v, u)', integral, region_all, m=m, v=v, u=u) eq = Equation('balance_of_forces', t1) eqs = Equations([eq]) epbcs, functions = self._get_periodicBCs(domain) ebcs = self._get_displacementBCs(domain) lcbcs = self._get_linear_combinationBCs(domain) ls = ScipyDirect({}) pb =
Problem('elasticity', equations=eqs, auto_solvers=None)
sfepy.discrete.Problem
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec =
ElasticConstants(young=E, poisson=nu)
sfepy.mechanics.matcoefs.ElasticConstants
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.0': 'u.0'} bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _get_periodicBC_YZ(self, domain, dim): dims = domain.get_mesh_bounding_box().shape[1] dim_dict = {0: ('x', per.match_x_plane), 1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] plus_ = self._subdomain_func(**{dim_string: (max_,)}) minus_ = self._subdomain_func(**{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.1': 'u.1'} if dims == 3: bc_dict['u.2'] = 'u.2' bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _solve(self, property_array): """ Solve the Sfepy problem for one sample. Args: property_array: array of shape (n_x, n_y, 2) where the last index is for Lame's parameter and shear modulus, respectively. Returns: the strain field of shape (n_x, n_y, 2) where the last index represents the x and y displacements """ shape = property_array.shape[:-1] mesh = self._get_mesh(shape) domain = Domain('domain', mesh) region_all = domain.create_region('region_all', 'all') field = Field.from_args('fu', np.float64, 'vector', region_all, approx_order=2) u = FieldVariable('u', 'unknown', field) v = FieldVariable('v', 'test', field, primary_var_name='u') m = self._get_material(property_array, domain) integral = Integral('i', order=4) t1 = Term.new('dw_lin_elastic_iso(m.lam, m.mu, v, u)', integral, region_all, m=m, v=v, u=u) eq = Equation('balance_of_forces', t1) eqs = Equations([eq]) epbcs, functions = self._get_periodicBCs(domain) ebcs = self._get_displacementBCs(domain) lcbcs = self._get_linear_combinationBCs(domain) ls = ScipyDirect({}) pb = Problem('elasticity', equations=eqs, auto_solvers=None) pb.time_update( ebcs=ebcs, epbcs=epbcs, lcbcs=lcbcs, functions=functions) ev = pb.get_evaluator() nls = Newton({}, lin_solver=ls, fun=ev.eval_residual, fun_grad=ev.eval_tangent_matrix) try: pb.set_solvers_instances(ls, nls) except AttributeError: pb.set_solver(nls) vec = pb.solve() u = vec.create_output_dict()['u'].data u_reshape = np.reshape(u, (tuple(x + 1 for x in shape) + u.shape[-1:])) dims = domain.get_mesh_bounding_box().shape[1] strain = np.squeeze( pb.evaluate( 'ev_cauchy_strain.{dim}.region_all(u)'.format( dim=dims), mode='el_avg', copy_materials=False)) strain_reshape = np.reshape(strain, (shape + strain.shape[-1:])) stress = np.squeeze( pb.evaluate( 'ev_cauchy_stress.{dim}.region_all(m.D, u)'.format( dim=dims), mode='el_avg', copy_materials=False)) stress_reshape = np.reshape(stress, (shape + stress.shape[-1:])) return strain_reshape, u_reshape, stress_reshape def _get_periodicBCs(self, domain): dims = domain.get_mesh_bounding_box().shape[1] bc_list_YZ, func_list_YZ = list( zip(*[self._get_periodicBC_YZ(domain, i) for i in range(0, dims)])) bc_list_X, func_list_X = list( zip(*[self._get_periodicBC_X(domain, i) for i in range(1, dims)])) return Conditions( bc_list_YZ + bc_list_X),
Functions(func_list_YZ + func_list_X)
sfepy.discrete.Functions
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness =
stiffness_from_lame(dims, lam=lam, mu=mu)
sfepy.mechanics.matcoefs.stiffness_from_lame
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=
Functions([fix_x_points])
sfepy.discrete.Functions
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=
Functions([shift_x_points])
sfepy.discrete.Functions
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=
Functions([xplus])
sfepy.discrete.Functions
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=
Functions([xminus])
sfepy.discrete.Functions
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=
Functions([plus])
sfepy.discrete.Functions
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=
Functions([minus])
sfepy.discrete.Functions
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.0': 'u.0'} bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _get_periodicBC_YZ(self, domain, dim): dims = domain.get_mesh_bounding_box().shape[1] dim_dict = {0: ('x', per.match_x_plane), 1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] plus_ = self._subdomain_func(**{dim_string: (max_,)}) minus_ = self._subdomain_func(**{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=
Functions([plus])
sfepy.discrete.Functions
import numpy as np from sfepy.base.goptions import goptions from sfepy.discrete.fem import Field try: from sfepy.discrete.fem import FEDomain as Domain except ImportError: from sfepy.discrete.fem import Domain from sfepy.discrete import (FieldVariable, Material, Integral, Function, Equation, Equations, Problem) from sfepy.terms import Term from sfepy.discrete.conditions import Conditions, EssentialBC, PeriodicBC from sfepy.solvers.ls import ScipyDirect from sfepy.solvers.nls import Newton import sfepy.discrete.fem.periodic as per from sfepy.discrete import Functions from sfepy.mesh.mesh_generators import gen_block_mesh from sfepy.mechanics.matcoefs import ElasticConstants from sfepy.base.base import output from sfepy.discrete.conditions import LinearCombinationBC goptions['verbose'] = False output.set_output(quiet=True) class ElasticFESimulation(object): """ Use SfePy to solve a linear strain problem in 2D with a varying microstructure on a rectangular grid. The rectangle (cube) is held at the negative edge (plane) and displaced by 1 on the positive x edge (plane). Periodic boundary conditions are applied to the other boundaries. The microstructure is of shape (n_samples, n_x, n_y) or (n_samples, n_x, n_y, n_z). >>> X = np.zeros((1, 3, 3), dtype=int) >>> X[0, :, 1] = 1 >>> sim = ElasticFESimulation(elastic_modulus=(1.0, 10.0), ... poissons_ratio=(0., 0.)) >>> sim.run(X) >>> y = sim.strain y is the strain with components as follows >>> exx = y[..., 0] >>> eyy = y[..., 1] >>> exy = y[..., 2] In this example, the strain is only in the x-direction and has a uniform value of 1 since the displacement is always 1 and the size of the domain is 1. >>> assert np.allclose(exx, 1) >>> assert np.allclose(eyy, 0) >>> assert np.allclose(exy, 0) The following example is for a system with contrast. It tests the left/right periodic offset and the top/bottom periodicity. >>> X = np.array([[[1, 0, 0, 1], ... [0, 1, 1, 1], ... [0, 0, 1, 1], ... [1, 0, 0, 1]]]) >>> n_samples, N, N = X.shape >>> macro_strain = 0.1 >>> sim = ElasticFESimulation((10.0,1.0), (0.3,0.3), macro_strain=0.1) >>> sim.run(X) >>> u = sim.displacement[0] Check that the offset for the left/right planes is `N * macro_strain`. >>> assert np.allclose(u[-1,:,0] - u[0,:,0], N * macro_strain) Check that the left/right side planes are periodic in y. >>> assert np.allclose(u[0,:,1], u[-1,:,1]) Check that the top/bottom planes are periodic in both x and y. >>> assert np.allclose(u[:,0], u[:,-1]) """ def __init__(self, elastic_modulus, poissons_ratio, macro_strain=1.,): """Instantiate a ElasticFESimulation. Args: elastic_modulus (1D array): array of elastic moduli for phases poissons_ratio (1D array): array of Possion's ratios for phases macro_strain (float, optional): Scalar for macroscopic strain """ self.macro_strain = macro_strain self.dx = 1.0 self.elastic_modulus = elastic_modulus self.poissons_ratio = poissons_ratio if len(elastic_modulus) != len(poissons_ratio): raise RuntimeError( 'elastic_modulus and poissons_ratio must be the same length') def _convert_properties(self, dim): """ Convert from elastic modulus and Poisson's ratio to the Lame parameter and shear modulus >>> model = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> result = model._convert_properties(2) >>> answer = np.array([[-0.5, 1. / 6.], [-1., 1. / 3.]]) >>> assert(np.allclose(result, answer)) Args: dim (int): Scalar value for the dimension of the microstructure. Returns: array with the Lame parameter and the shear modulus for each phase. """ def _convert(E, nu): ec = ElasticConstants(young=E, poisson=nu) mu = dim / 3. * ec.mu lame = ec.lam return lame, mu return np.array([_convert(E, nu) for E, nu in zip(self.elastic_modulus, self.poissons_ratio)]) def _get_property_array(self, X): """ Generate property array with elastic_modulus and poissons_ratio for each phase. Test case for 2D with 3 phases. >>> X2D = np.array([[[0, 1, 2, 1], ... [2, 1, 0, 0], ... [1, 0, 2, 2]]]) >>> model2D = ElasticFESimulation(elastic_modulus=(1., 2., 3.), ... poissons_ratio=(1., 1., 1.)) >>> lame = lame0, lame1, lame2 = -0.5, -1., -1.5 >>> mu = mu0, mu1, mu2 = 1. / 6, 1. / 3, 1. / 2 >>> lm = zip(lame, mu) >>> X2D_property = np.array([[lm[0], lm[1], lm[2], lm[1]], ... [lm[2], lm[1], lm[0], lm[0]], ... [lm[1], lm[0], lm[2], lm[2]]]) >>> assert(np.allclose(model2D._get_property_array(X2D), X2D_property)) Test case for 3D with 2 phases. >>> model3D = ElasticFESimulation(elastic_modulus=(1., 2.), ... poissons_ratio=(1., 1.)) >>> X3D = np.array([[[0, 1], ... [0, 0]], ... [[1, 1], ... [0, 1]]]) >>> X3D_property = np.array([[[lm[0], lm[1]], ... [lm[0], lm[0]]], ... [[lm[1], lm[1]], ... [lm[0], lm[1]]]]) >>> assert(np.allclose(model3D._get_property_array(X3D), X3D_property)) """ dim = len(X.shape) - 1 n_phases = len(self.elastic_modulus) if not issubclass(X.dtype.type, np.integer): raise TypeError("X must be an integer array") if np.max(X) >= n_phases or np.min(X) < 0: raise RuntimeError( "X must be between 0 and {N}.".format(N=n_phases - 1)) if not (2 <= dim <= 3): raise RuntimeError("the shape of X is incorrect") return self._convert_properties(dim)[X] def run(self, X): """ Run the simulation. Args: X (ND array): microstructure with shape (n_samples, n_x, ...) """ X_property = self._get_property_array(X) strain = [] displacement = [] stress = [] for x in X_property: strain_, displacement_, stress_ = self._solve(x) strain.append(strain_) displacement.append(displacement_) stress.append(stress_) self.strain = np.array(strain) self.displacement = np.array(displacement) self.stress = np.array(stress) @property def response(self): return self.strain[..., 0] def _get_material(self, property_array, domain): """ Creates an SfePy material from the material property fields for the quadrature points. Args: property_array: array of the properties with shape (n_x, n_y, n_z, 2) Returns: an SfePy material """ min_xyz = domain.get_mesh_bounding_box()[0] dims = domain.get_mesh_bounding_box().shape[1] def _material_func_(ts, coors, mode=None, **kwargs): if mode == 'qp': ijk_out = np.empty_like(coors, dtype=int) ijk = np.floor((coors - min_xyz[None]) / self.dx, ijk_out, casting="unsafe") ijk_tuple = tuple(ijk.swapaxes(0, 1)) property_array_qp = property_array[ijk_tuple] lam = property_array_qp[..., 0] mu = property_array_qp[..., 1] lam = np.ascontiguousarray(lam.reshape((lam.shape[0], 1, 1))) mu = np.ascontiguousarray(mu.reshape((mu.shape[0], 1, 1))) from sfepy.mechanics.matcoefs import stiffness_from_lame stiffness = stiffness_from_lame(dims, lam=lam, mu=mu) return {'lam': lam, 'mu': mu, 'D': stiffness} else: return material_func = Function('material_func', _material_func_) return Material('m', function=material_func) def _subdomain_func(self, x=(), y=(), z=(), max_x=None): """ Creates a function to mask subdomains in Sfepy. Args: x: tuple of lines or points to be masked in the x-plane y: tuple of lines or points to be masked in the y-plane z: tuple of lines or points to be masked in the z-plane Returns: array of masked location indices """ eps = 1e-3 * self.dx def _func(coords, domain=None): flag_x = len(x) == 0 flag_y = len(y) == 0 flag_z = len(z) == 0 for x_ in x: flag = (coords[:, 0] < (x_ + eps)) & \ (coords[:, 0] > (x_ - eps)) flag_x = flag_x | flag for y_ in y: flag = (coords[:, 1] < (y_ + eps)) & \ (coords[:, 1] > (y_ - eps)) flag_y = flag_y | flag for z_ in z: flag = (coords[:, 2] < (z_ + eps)) & \ (coords[:, 2] > (z_ - eps)) flag_z = flag_z | flag flag = flag_x & flag_y & flag_z if max_x is not None: flag = flag & (coords[:, 0] < (max_x - eps)) return np.where(flag)[0] return _func def _get_mesh(self, shape): """ Generate an Sfepy rectangular mesh Args: shape: proposed shape of domain (vertex shape) (n_x, n_y) Returns: Sfepy mesh """ center = np.zeros_like(shape) return gen_block_mesh(shape, np.array(shape) + 1, center, verbose=False) def _get_fixed_displacementsBCs(self, domain): """ Fix the left top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} fix_points_dict = {'u.0': 0.0, 'u.1': 0.0} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} fix_points_dict['u.2'] = 0.0 fix_x_points_ = self._subdomain_func(x=(min_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) fix_x_points = Function('fix_x_points', fix_x_points_) region_fix_points = domain.create_region( 'region_fix_points', 'vertices by fix_x_points', 'vertex', functions=Functions([fix_x_points])) return EssentialBC('fix_points_BC', region_fix_points, fix_points_dict) def _get_shift_displacementsBCs(self, domain): """ Fix the right top and bottom points in x, y and z Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] kwargs = {} if len(min_xyz) == 3: kwargs = {'z': (max_xyz[2], min_xyz[2])} displacement = self.macro_strain * (max_xyz[0] - min_xyz[0]) shift_points_dict = {'u.0': displacement} shift_x_points_ = self._subdomain_func(x=(max_xyz[0],), y=(max_xyz[1], min_xyz[1]), **kwargs) shift_x_points = Function('shift_x_points', shift_x_points_) region_shift_points = domain.create_region( 'region_shift_points', 'vertices by shift_x_points', 'vertex', functions=Functions([shift_x_points])) return EssentialBC('shift_points_BC', region_shift_points, shift_points_dict) def _get_displacementBCs(self, domain): shift_points_BC = self._get_shift_displacementsBCs(domain) fix_points_BC = self._get_fixed_displacementsBCs(domain) return Conditions([fix_points_BC, shift_points_BC]) def _get_linear_combinationBCs(self, domain): """ The right nodes are periodic with the left nodes but also displaced. Args: domain: an Sfepy domain Returns: the Sfepy boundary conditions """ min_xyz = domain.get_mesh_bounding_box()[0] max_xyz = domain.get_mesh_bounding_box()[1] xplus_ = self._subdomain_func(x=(max_xyz[0],)) xminus_ = self._subdomain_func(x=(min_xyz[0],)) xplus = Function('xplus', xplus_) xminus = Function('xminus', xminus_) region_x_plus = domain.create_region('region_x_plus', 'vertices by xplus', 'facet', functions=Functions([xplus])) region_x_minus = domain.create_region('region_x_minus', 'vertices by xminus', 'facet', functions=Functions([xminus])) match_x_plane = Function('match_x_plane', per.match_x_plane) def shift_(ts, coors, region): return np.ones_like(coors[:, 0]) * \ self.macro_strain * (max_xyz[0] - min_xyz[0]) shift = Function('shift', shift_) lcbc = LinearCombinationBC( 'lcbc', [region_x_plus, region_x_minus], { 'u.0': 'u.0'}, match_x_plane, 'shifted_periodic', arguments=(shift,)) return Conditions([lcbc]) def _get_periodicBC_X(self, domain, dim): dim_dict = {1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] min_x, max_x = domain.get_mesh_bounding_box()[:, 0] plus_ = self._subdomain_func(max_x=max_x, **{dim_string: (max_,)}) minus_ = self._subdomain_func(max_x=max_x, **{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=Functions([minus])) match_plane = Function( 'match_{0}_plane'.format(dim_string), match_plane) bc_dict = {'u.0': 'u.0'} bc = PeriodicBC('periodic_{0}'.format(dim_string), [region_plus, region_minus], bc_dict, match='match_{0}_plane'.format(dim_string)) return bc, match_plane def _get_periodicBC_YZ(self, domain, dim): dims = domain.get_mesh_bounding_box().shape[1] dim_dict = {0: ('x', per.match_x_plane), 1: ('y', per.match_y_plane), 2: ('z', per.match_z_plane)} dim_string = dim_dict[dim][0] match_plane = dim_dict[dim][1] min_, max_ = domain.get_mesh_bounding_box()[:, dim] plus_ = self._subdomain_func(**{dim_string: (max_,)}) minus_ = self._subdomain_func(**{dim_string: (min_,)}) plus_string = dim_string + 'plus' minus_string = dim_string + 'minus' plus = Function(plus_string, plus_) minus = Function(minus_string, minus_) region_plus = domain.create_region( 'region_{0}_plus'.format(dim_string), 'vertices by {0}'.format( plus_string), 'facet', functions=Functions([plus])) region_minus = domain.create_region( 'region_{0}_minus'.format(dim_string), 'vertices by {0}'.format( minus_string), 'facet', functions=
Functions([minus])
sfepy.discrete.Functions
""" Utility functions based on igakit. """ import numpy as nm from sfepy.base.base import Struct from sfepy.discrete.fem import Mesh from sfepy.mesh.mesh_generators import get_tensor_product_conn def create_linear_fe_mesh(nurbs, pars=None): """ Convert a NURBS object into a nD-linear tensor product FE mesh. Parameters ---------- nurbs : igakit.nurbs.NURBS instance The NURBS object. pars : sequence of array, optional The values of parameters in each parametric dimension. If not given, the values are set so that the resulting mesh has the same number of vertices as the number of control points/basis functions of the NURBS object. Returns ------- coors : array The coordinates of mesh vertices. conn : array The vertex connectivity array. desc : str The cell kind. """ knots = nurbs.knots shape = nurbs.weights.shape if pars is None: pars = [] for ii, kv in enumerate(knots): par = nm.linspace(kv[0], kv[-1], shape[ii]) pars.append(par) coors = nurbs(*pars) coors.shape = (-1, coors.shape[-1]) conn, desc = get_tensor_product_conn([len(ii) for ii in pars]) if (coors[:, -1] == 0.0).all(): coors = coors[:, :-1] return coors, conn, desc def create_mesh_and_output(nurbs, pars=None, **kwargs): """ Create a nD-linear tensor product FE mesh using :func:`create_linear_fe_mesh()`, evaluate field variables given as keyword arguments in the mesh vertices and create a dictionary of output data usable by Mesh.write(). Parameters ---------- nurbs : igakit.nurbs.NURBS instance The NURBS object. pars : sequence of array, optional The values of parameters in each parametric dimension. If not given, the values are set so that the resulting mesh has the same number of vertices as the number of control points/basis functions of the NURBS object. **kwargs : kwargs The field variables as keyword arguments. Their names serve as keys in the output dictionary. Returns ------- mesh : Mesh instance The finite element mesh. out : dict The output dictionary. """ coors, conn, desc = create_linear_fe_mesh(nurbs, pars) mat_id = nm.zeros(conn.shape[0], dtype=nm.int32) mesh =
Mesh.from_data('nurbs', coors, None, [conn], [mat_id], [desc])
sfepy.discrete.fem.Mesh.from_data
""" Utility functions based on igakit. """ import numpy as nm from sfepy.base.base import Struct from sfepy.discrete.fem import Mesh from sfepy.mesh.mesh_generators import get_tensor_product_conn def create_linear_fe_mesh(nurbs, pars=None): """ Convert a NURBS object into a nD-linear tensor product FE mesh. Parameters ---------- nurbs : igakit.nurbs.NURBS instance The NURBS object. pars : sequence of array, optional The values of parameters in each parametric dimension. If not given, the values are set so that the resulting mesh has the same number of vertices as the number of control points/basis functions of the NURBS object. Returns ------- coors : array The coordinates of mesh vertices. conn : array The vertex connectivity array. desc : str The cell kind. """ knots = nurbs.knots shape = nurbs.weights.shape if pars is None: pars = [] for ii, kv in enumerate(knots): par = nm.linspace(kv[0], kv[-1], shape[ii]) pars.append(par) coors = nurbs(*pars) coors.shape = (-1, coors.shape[-1]) conn, desc = get_tensor_product_conn([len(ii) for ii in pars]) if (coors[:, -1] == 0.0).all(): coors = coors[:, :-1] return coors, conn, desc def create_mesh_and_output(nurbs, pars=None, **kwargs): """ Create a nD-linear tensor product FE mesh using :func:`create_linear_fe_mesh()`, evaluate field variables given as keyword arguments in the mesh vertices and create a dictionary of output data usable by Mesh.write(). Parameters ---------- nurbs : igakit.nurbs.NURBS instance The NURBS object. pars : sequence of array, optional The values of parameters in each parametric dimension. If not given, the values are set so that the resulting mesh has the same number of vertices as the number of control points/basis functions of the NURBS object. **kwargs : kwargs The field variables as keyword arguments. Their names serve as keys in the output dictionary. Returns ------- mesh : Mesh instance The finite element mesh. out : dict The output dictionary. """ coors, conn, desc = create_linear_fe_mesh(nurbs, pars) mat_id = nm.zeros(conn.shape[0], dtype=nm.int32) mesh = Mesh.from_data('nurbs', coors, None, [conn], [mat_id], [desc]) out = {} for key, variable in kwargs.iteritems(): if variable.ndim == 2: nc = variable.shape[1] field = variable.reshape(nurbs.weights.shape + (nc,)) else: field = variable.reshape(nurbs.weights.shape) nc = 1 vals = nurbs.evaluate(field, *pars) out[key] = Struct(name='output_data', mode='vertex', data=vals.reshape((-1, nc))) return mesh, out def save_basis(nurbs, pars): """ Save a NURBS object basis on a FE mesh corresponding to the given parametrization in VTK files. Parameters ---------- nurbs : igakit.nurbs.NURBS instance The NURBS object. pars : sequence of array, optional The values of parameters in each parametric dimension. """ coors, conn, desc = create_linear_fe_mesh(nurbs, pars) mat_id = nm.zeros(conn.shape[0], dtype=nm.int32) mesh =
Mesh.from_data('nurbs', coors, None, [conn], [mat_id], [desc])
sfepy.discrete.fem.Mesh.from_data
#!/usr/bin/env python # 12.01.2007, c from __future__ import absolute_import from argparse import ArgumentParser import sfepy from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.band_gaps_app import AcousticBandGapsApp from sfepy.base.plotutils import plt helps = { 'debug': 'automatically start debugger when an exception is raised', 'filename' : 'basename of output file(s) [default: <basename of input file>]', 'detect_band_gaps' : 'detect frequency band gaps', 'analyze_dispersion' : 'analyze dispersion properties (low frequency domain)', 'plot' : 'plot frequency band gaps, assumes -b', 'phase_velocity' : 'compute phase velocity (frequency-independet mass only)' } def main(): parser = ArgumentParser() parser.add_argument("--version", action="version", version="%(prog)s " + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=helps['debug']) parser.add_argument("-o", metavar='filename', action="store", dest="output_filename_trunk", default=None, help=helps['filename']) parser.add_argument("-b", "--band-gaps", action="store_true", dest="detect_band_gaps", default=False, help=helps['detect_band_gaps']) parser.add_argument("-d", "--dispersion", action="store_true", dest="analyze_dispersion", default=False, help=helps['analyze_dispersion']) parser.add_argument("-p", "--plot", action="store_true", dest="plot", default=False, help=helps['plot']) parser.add_argument("--phase-velocity", action="store_true", dest="phase_velocity", default=False, help=helps['phase_velocity']) parser.add_argument("filename_in") options = parser.parse_args() if options.debug: from sfepy.base.base import debug_on_error; debug_on_error() if options.plot: if plt is None: output('matplotlib.pyplot cannot be imported, ignoring option -p!') options.plot = False elif options.analyze_dispersion == False: options.detect_band_gaps = True required, other =
get_standard_keywords()
sfepy.base.conf.get_standard_keywords
#!/usr/bin/env python # 12.01.2007, c from __future__ import absolute_import from argparse import ArgumentParser import sfepy from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.band_gaps_app import AcousticBandGapsApp from sfepy.base.plotutils import plt helps = { 'debug': 'automatically start debugger when an exception is raised', 'filename' : 'basename of output file(s) [default: <basename of input file>]', 'detect_band_gaps' : 'detect frequency band gaps', 'analyze_dispersion' : 'analyze dispersion properties (low frequency domain)', 'plot' : 'plot frequency band gaps, assumes -b', 'phase_velocity' : 'compute phase velocity (frequency-independet mass only)' } def main(): parser = ArgumentParser() parser.add_argument("--version", action="version", version="%(prog)s " + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=helps['debug']) parser.add_argument("-o", metavar='filename', action="store", dest="output_filename_trunk", default=None, help=helps['filename']) parser.add_argument("-b", "--band-gaps", action="store_true", dest="detect_band_gaps", default=False, help=helps['detect_band_gaps']) parser.add_argument("-d", "--dispersion", action="store_true", dest="analyze_dispersion", default=False, help=helps['analyze_dispersion']) parser.add_argument("-p", "--plot", action="store_true", dest="plot", default=False, help=helps['plot']) parser.add_argument("--phase-velocity", action="store_true", dest="phase_velocity", default=False, help=helps['phase_velocity']) parser.add_argument("filename_in") options = parser.parse_args() if options.debug: from sfepy.base.base import debug_on_error; debug_on_error() if options.plot: if plt is None: output('matplotlib.pyplot cannot be imported, ignoring option -p!') options.plot = False elif options.analyze_dispersion == False: options.detect_band_gaps = True required, other = get_standard_keywords() required.remove('equations') if not options.analyze_dispersion: required.remove('solver_[0-9]+|solvers') if options.phase_velocity: required = [ii for ii in required if 'ebc' not in ii] conf =
ProblemConf.from_file(options.filename_in, required, other)
sfepy.base.conf.ProblemConf.from_file
#!/usr/bin/env python # 12.01.2007, c from __future__ import absolute_import from argparse import ArgumentParser import sfepy from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.band_gaps_app import AcousticBandGapsApp from sfepy.base.plotutils import plt helps = { 'debug': 'automatically start debugger when an exception is raised', 'filename' : 'basename of output file(s) [default: <basename of input file>]', 'detect_band_gaps' : 'detect frequency band gaps', 'analyze_dispersion' : 'analyze dispersion properties (low frequency domain)', 'plot' : 'plot frequency band gaps, assumes -b', 'phase_velocity' : 'compute phase velocity (frequency-independet mass only)' } def main(): parser = ArgumentParser() parser.add_argument("--version", action="version", version="%(prog)s " + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=helps['debug']) parser.add_argument("-o", metavar='filename', action="store", dest="output_filename_trunk", default=None, help=helps['filename']) parser.add_argument("-b", "--band-gaps", action="store_true", dest="detect_band_gaps", default=False, help=helps['detect_band_gaps']) parser.add_argument("-d", "--dispersion", action="store_true", dest="analyze_dispersion", default=False, help=helps['analyze_dispersion']) parser.add_argument("-p", "--plot", action="store_true", dest="plot", default=False, help=helps['plot']) parser.add_argument("--phase-velocity", action="store_true", dest="phase_velocity", default=False, help=helps['phase_velocity']) parser.add_argument("filename_in") options = parser.parse_args() if options.debug: from sfepy.base.base import debug_on_error; debug_on_error() if options.plot: if plt is None: output('matplotlib.pyplot cannot be imported, ignoring option -p!') options.plot = False elif options.analyze_dispersion == False: options.detect_band_gaps = True required, other = get_standard_keywords() required.remove('equations') if not options.analyze_dispersion: required.remove('solver_[0-9]+|solvers') if options.phase_velocity: required = [ii for ii in required if 'ebc' not in ii] conf = ProblemConf.from_file(options.filename_in, required, other) app =
AcousticBandGapsApp(conf, options, 'phonon:')
sfepy.homogenization.band_gaps_app.AcousticBandGapsApp
#!/usr/bin/env python # 12.01.2007, c from __future__ import absolute_import from argparse import ArgumentParser import sfepy from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.band_gaps_app import AcousticBandGapsApp from sfepy.base.plotutils import plt helps = { 'debug': 'automatically start debugger when an exception is raised', 'filename' : 'basename of output file(s) [default: <basename of input file>]', 'detect_band_gaps' : 'detect frequency band gaps', 'analyze_dispersion' : 'analyze dispersion properties (low frequency domain)', 'plot' : 'plot frequency band gaps, assumes -b', 'phase_velocity' : 'compute phase velocity (frequency-independet mass only)' } def main(): parser = ArgumentParser() parser.add_argument("--version", action="version", version="%(prog)s " + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=helps['debug']) parser.add_argument("-o", metavar='filename', action="store", dest="output_filename_trunk", default=None, help=helps['filename']) parser.add_argument("-b", "--band-gaps", action="store_true", dest="detect_band_gaps", default=False, help=helps['detect_band_gaps']) parser.add_argument("-d", "--dispersion", action="store_true", dest="analyze_dispersion", default=False, help=helps['analyze_dispersion']) parser.add_argument("-p", "--plot", action="store_true", dest="plot", default=False, help=helps['plot']) parser.add_argument("--phase-velocity", action="store_true", dest="phase_velocity", default=False, help=helps['phase_velocity']) parser.add_argument("filename_in") options = parser.parse_args() if options.debug: from sfepy.base.base import debug_on_error;
debug_on_error()
sfepy.base.base.debug_on_error
#!/usr/bin/env python # 12.01.2007, c from __future__ import absolute_import from argparse import ArgumentParser import sfepy from sfepy.base.base import output from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.homogenization.band_gaps_app import AcousticBandGapsApp from sfepy.base.plotutils import plt helps = { 'debug': 'automatically start debugger when an exception is raised', 'filename' : 'basename of output file(s) [default: <basename of input file>]', 'detect_band_gaps' : 'detect frequency band gaps', 'analyze_dispersion' : 'analyze dispersion properties (low frequency domain)', 'plot' : 'plot frequency band gaps, assumes -b', 'phase_velocity' : 'compute phase velocity (frequency-independet mass only)' } def main(): parser = ArgumentParser() parser.add_argument("--version", action="version", version="%(prog)s " + sfepy.__version__) parser.add_argument('--debug', action='store_true', dest='debug', default=False, help=helps['debug']) parser.add_argument("-o", metavar='filename', action="store", dest="output_filename_trunk", default=None, help=helps['filename']) parser.add_argument("-b", "--band-gaps", action="store_true", dest="detect_band_gaps", default=False, help=helps['detect_band_gaps']) parser.add_argument("-d", "--dispersion", action="store_true", dest="analyze_dispersion", default=False, help=helps['analyze_dispersion']) parser.add_argument("-p", "--plot", action="store_true", dest="plot", default=False, help=helps['plot']) parser.add_argument("--phase-velocity", action="store_true", dest="phase_velocity", default=False, help=helps['phase_velocity']) parser.add_argument("filename_in") options = parser.parse_args() if options.debug: from sfepy.base.base import debug_on_error; debug_on_error() if options.plot: if plt is None:
output('matplotlib.pyplot cannot be imported, ignoring option -p!')
sfepy.base.base.output
""" This module is not a test file. It contains classes grouping some common functionality, that is used in several test files. """ from __future__ import absolute_import from sfepy.base.base import IndexedStruct from sfepy.base.testing import TestCommon import os.path as op class NLSStatus(IndexedStruct): """ Custom nonlinear solver status storing stopping condition of all time steps. """ def __setitem__(self, key, val):
IndexedStruct.__setitem__(self, key, val)
sfepy.base.base.IndexedStruct.__setitem__
""" This module is not a test file. It contains classes grouping some common functionality, that is used in several test files. """ from __future__ import absolute_import from sfepy.base.base import IndexedStruct from sfepy.base.testing import TestCommon import os.path as op class NLSStatus(IndexedStruct): """ Custom nonlinear solver status storing stopping condition of all time steps. """ def __setitem__(self, key, val): IndexedStruct.__setitem__(self, key, val) if key == 'condition': self.conditions.append(val) class TestDummy(TestCommon): """Simulate test OK result for missing optional modules.""" @staticmethod def from_conf(conf, options): return TestDummy() def test_dummy(self): return True class TestInput(TestCommon): """Test that an input file works. See test_input_*.py files.""" @staticmethod def from_conf(conf, options, cls=None): from sfepy.base.base import Struct from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.applications import assign_standard_hooks required, other =
get_standard_keywords()
sfepy.base.conf.get_standard_keywords
""" This module is not a test file. It contains classes grouping some common functionality, that is used in several test files. """ from __future__ import absolute_import from sfepy.base.base import IndexedStruct from sfepy.base.testing import TestCommon import os.path as op class NLSStatus(IndexedStruct): """ Custom nonlinear solver status storing stopping condition of all time steps. """ def __setitem__(self, key, val): IndexedStruct.__setitem__(self, key, val) if key == 'condition': self.conditions.append(val) class TestDummy(TestCommon): """Simulate test OK result for missing optional modules.""" @staticmethod def from_conf(conf, options): return TestDummy() def test_dummy(self): return True class TestInput(TestCommon): """Test that an input file works. See test_input_*.py files.""" @staticmethod def from_conf(conf, options, cls=None): from sfepy.base.base import Struct from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.applications import assign_standard_hooks required, other = get_standard_keywords() input_name = op.join(op.dirname(__file__), conf.input_name) test_conf =
ProblemConf.from_file(input_name, required, other)
sfepy.base.conf.ProblemConf.from_file
""" This module is not a test file. It contains classes grouping some common functionality, that is used in several test files. """ from __future__ import absolute_import from sfepy.base.base import IndexedStruct from sfepy.base.testing import TestCommon import os.path as op class NLSStatus(IndexedStruct): """ Custom nonlinear solver status storing stopping condition of all time steps. """ def __setitem__(self, key, val): IndexedStruct.__setitem__(self, key, val) if key == 'condition': self.conditions.append(val) class TestDummy(TestCommon): """Simulate test OK result for missing optional modules.""" @staticmethod def from_conf(conf, options): return TestDummy() def test_dummy(self): return True class TestInput(TestCommon): """Test that an input file works. See test_input_*.py files.""" @staticmethod def from_conf(conf, options, cls=None): from sfepy.base.base import Struct from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.applications import assign_standard_hooks required, other = get_standard_keywords() input_name = op.join(op.dirname(__file__), conf.input_name) test_conf = ProblemConf.from_file(input_name, required, other) if cls is None: cls = TestInput test = cls(test_conf=test_conf, conf=conf, options=options)
assign_standard_hooks(test, test_conf.options.get, test_conf)
sfepy.applications.assign_standard_hooks
""" This module is not a test file. It contains classes grouping some common functionality, that is used in several test files. """ from __future__ import absolute_import from sfepy.base.base import IndexedStruct from sfepy.base.testing import TestCommon import os.path as op class NLSStatus(IndexedStruct): """ Custom nonlinear solver status storing stopping condition of all time steps. """ def __setitem__(self, key, val): IndexedStruct.__setitem__(self, key, val) if key == 'condition': self.conditions.append(val) class TestDummy(TestCommon): """Simulate test OK result for missing optional modules.""" @staticmethod def from_conf(conf, options): return TestDummy() def test_dummy(self): return True class TestInput(TestCommon): """Test that an input file works. See test_input_*.py files.""" @staticmethod def from_conf(conf, options, cls=None): from sfepy.base.base import Struct from sfepy.base.conf import ProblemConf, get_standard_keywords from sfepy.applications import assign_standard_hooks required, other = get_standard_keywords() input_name = op.join(op.dirname(__file__), conf.input_name) test_conf = ProblemConf.from_file(input_name, required, other) if cls is None: cls = TestInput test = cls(test_conf=test_conf, conf=conf, options=options) assign_standard_hooks(test, test_conf.options.get, test_conf) name = test.get_output_name_trunk() ext = test.get_output_name_ext() test.solver_options = Struct(output_filename_trunk=name, output_format=ext if ext != '' else "vtk", save_ebc=False, save_ebc_nodes=False, save_regions=False, save_regions_as_groups=False, save_field_meshes=False, solve_not=False) return test def get_output_name_trunk(self): return op.splitext(op.split(self.conf.output_name)[1])[0] def get_output_name_ext(self): return op.splitext(op.split(self.conf.output_name)[1])[1].replace(".", "") def check_conditions(self, conditions): ok = (conditions == 0).all() if not ok: self.report('nls stopping conditions:') self.report(conditions) return ok def test_input(self): import numpy as nm from sfepy.applications import solve_pde self.report('solving %s...' % self.conf.input_name) status = IndexedStruct(nls_status=NLSStatus(conditions=[])) solve_pde(self.test_conf, self.solver_options, status=status, output_dir=self.options.out_dir, step_hook=self.step_hook, post_process_hook=self.post_process_hook, post_process_hook_final=self.post_process_hook_final) self.report('%s solved' % self.conf.input_name) ok = self.check_conditions(nm.array(status.nls_status.conditions)) return ok class TestInputEvolutionary(TestInput): @staticmethod def from_conf(conf, options, cls=None): if cls is None: cls = TestInputEvolutionary return TestInput.from_conf(conf, options, cls=cls) def get_output_name_trunk(self): return self.conf.output_name_trunk def get_output_name_ext(self): return "" class TestLCBC(TestCommon): """Test linear combination BC. See test_lcbc_*.py files.""" @staticmethod def from_conf(conf, options): return TestLCBC(conf=conf, options=options) def test_linear_rigid_body_bc(self): import scipy if scipy.version.version == "0.6.0": # This test uses a functionality implemented in scipy svn, which is # missing in scipy 0.6.0 return True from sfepy.base.base import Struct from sfepy.applications import solve_pde from sfepy.base.base import IndexedStruct status =
IndexedStruct()
sfepy.base.base.IndexedStruct
""" IGA domain generators. """ import numpy as nm from sfepy.base.base import output, Struct import sfepy.discrete.iga as iga from sfepy.discrete.iga.domain import NurbsPatch def gen_patch_block_domain(dims, shape, centre, degrees, continuity=None, name='block', verbose=True): """ Generate a single IGA patch block in 2D or 3D of given degrees and continuity using igakit. Parameters ---------- dims : array of D floats Dimensions of the block. shape : array of D ints Numbers of unique knot values along each axis. centre : array of D floats Centre of the block. degrees : array of D floats NURBS degrees along each axis. continuity : array of D ints, optional NURBS continuity along each axis. If None, `degrees-1` is used. name : string Domain name. verbose : bool If True, report progress of the domain generation. Returns ------- nurbs : NurbsPatch instance The NURBS data. The igakit NURBS object is stored as `nurbs` attribute. bmesh : Struct instance The Bezier mesh data. regions : dict The patch surface regions. """ import igakit.cad as cad dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) degrees = nm.asarray(degrees, dtype=nm.int32) if continuity is None: continuity = degrees - 1 else: continuity = nm.asarray(continuity, dtype=nm.int32) dim = len(shape)
output('generating NURBS...', verbose=verbose)
sfepy.base.base.output
""" IGA domain generators. """ import numpy as nm from sfepy.base.base import output, Struct import sfepy.discrete.iga as iga from sfepy.discrete.iga.domain import NurbsPatch def gen_patch_block_domain(dims, shape, centre, degrees, continuity=None, name='block', verbose=True): """ Generate a single IGA patch block in 2D or 3D of given degrees and continuity using igakit. Parameters ---------- dims : array of D floats Dimensions of the block. shape : array of D ints Numbers of unique knot values along each axis. centre : array of D floats Centre of the block. degrees : array of D floats NURBS degrees along each axis. continuity : array of D ints, optional NURBS continuity along each axis. If None, `degrees-1` is used. name : string Domain name. verbose : bool If True, report progress of the domain generation. Returns ------- nurbs : NurbsPatch instance The NURBS data. The igakit NURBS object is stored as `nurbs` attribute. bmesh : Struct instance The Bezier mesh data. regions : dict The patch surface regions. """ import igakit.cad as cad dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) degrees = nm.asarray(degrees, dtype=nm.int32) if continuity is None: continuity = degrees - 1 else: continuity = nm.asarray(continuity, dtype=nm.int32) dim = len(shape) output('generating NURBS...', verbose=verbose) dd = centre - 0.5 * dims block = cad.grid(shape - 1, degree=degrees, continuity=continuity) for ia in xrange(dim): block.scale(dims[ia], ia) for ia in xrange(dim): block.translate(dd[ia], ia) # Force uniform control points. This prevents coarser resolution inside the # block. shape = nm.asarray(block.points.shape[:-1]) n_nod = nm.prod(shape) 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 coors.shape = shape.tolist() + [dim] block.array[..., :dim] = coors
output('...done', verbose=verbose)
sfepy.base.base.output
""" IGA domain generators. """ import numpy as nm from sfepy.base.base import output, Struct import sfepy.discrete.iga as iga from sfepy.discrete.iga.domain import NurbsPatch def gen_patch_block_domain(dims, shape, centre, degrees, continuity=None, name='block', verbose=True): """ Generate a single IGA patch block in 2D or 3D of given degrees and continuity using igakit. Parameters ---------- dims : array of D floats Dimensions of the block. shape : array of D ints Numbers of unique knot values along each axis. centre : array of D floats Centre of the block. degrees : array of D floats NURBS degrees along each axis. continuity : array of D ints, optional NURBS continuity along each axis. If None, `degrees-1` is used. name : string Domain name. verbose : bool If True, report progress of the domain generation. Returns ------- nurbs : NurbsPatch instance The NURBS data. The igakit NURBS object is stored as `nurbs` attribute. bmesh : Struct instance The Bezier mesh data. regions : dict The patch surface regions. """ import igakit.cad as cad dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) degrees = nm.asarray(degrees, dtype=nm.int32) if continuity is None: continuity = degrees - 1 else: continuity = nm.asarray(continuity, dtype=nm.int32) dim = len(shape) output('generating NURBS...', verbose=verbose) dd = centre - 0.5 * dims block = cad.grid(shape - 1, degree=degrees, continuity=continuity) for ia in xrange(dim): block.scale(dims[ia], ia) for ia in xrange(dim): block.translate(dd[ia], ia) # Force uniform control points. This prevents coarser resolution inside the # block. shape = nm.asarray(block.points.shape[:-1]) n_nod = nm.prod(shape) 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 coors.shape = shape.tolist() + [dim] block.array[..., :dim] = coors output('...done', verbose=verbose) # Compute Bezier extraction data.
output('computing Bezier mesh...', verbose=verbose)
sfepy.base.base.output
""" IGA domain generators. """ import numpy as nm from sfepy.base.base import output, Struct import sfepy.discrete.iga as iga from sfepy.discrete.iga.domain import NurbsPatch def gen_patch_block_domain(dims, shape, centre, degrees, continuity=None, name='block', verbose=True): """ Generate a single IGA patch block in 2D or 3D of given degrees and continuity using igakit. Parameters ---------- dims : array of D floats Dimensions of the block. shape : array of D ints Numbers of unique knot values along each axis. centre : array of D floats Centre of the block. degrees : array of D floats NURBS degrees along each axis. continuity : array of D ints, optional NURBS continuity along each axis. If None, `degrees-1` is used. name : string Domain name. verbose : bool If True, report progress of the domain generation. Returns ------- nurbs : NurbsPatch instance The NURBS data. The igakit NURBS object is stored as `nurbs` attribute. bmesh : Struct instance The Bezier mesh data. regions : dict The patch surface regions. """ import igakit.cad as cad dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) degrees = nm.asarray(degrees, dtype=nm.int32) if continuity is None: continuity = degrees - 1 else: continuity = nm.asarray(continuity, dtype=nm.int32) dim = len(shape) output('generating NURBS...', verbose=verbose) dd = centre - 0.5 * dims block = cad.grid(shape - 1, degree=degrees, continuity=continuity) for ia in xrange(dim): block.scale(dims[ia], ia) for ia in xrange(dim): block.translate(dd[ia], ia) # Force uniform control points. This prevents coarser resolution inside the # block. shape = nm.asarray(block.points.shape[:-1]) n_nod = nm.prod(shape) 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 coors.shape = shape.tolist() + [dim] block.array[..., :dim] = coors output('...done', verbose=verbose) # Compute Bezier extraction data. output('computing Bezier mesh...', verbose=verbose) cs =
iga.compute_bezier_extraction(block.knots, block.degree)
sfepy.discrete.iga.compute_bezier_extraction
""" IGA domain generators. """ import numpy as nm from sfepy.base.base import output, Struct import sfepy.discrete.iga as iga from sfepy.discrete.iga.domain import NurbsPatch def gen_patch_block_domain(dims, shape, centre, degrees, continuity=None, name='block', verbose=True): """ Generate a single IGA patch block in 2D or 3D of given degrees and continuity using igakit. Parameters ---------- dims : array of D floats Dimensions of the block. shape : array of D ints Numbers of unique knot values along each axis. centre : array of D floats Centre of the block. degrees : array of D floats NURBS degrees along each axis. continuity : array of D ints, optional NURBS continuity along each axis. If None, `degrees-1` is used. name : string Domain name. verbose : bool If True, report progress of the domain generation. Returns ------- nurbs : NurbsPatch instance The NURBS data. The igakit NURBS object is stored as `nurbs` attribute. bmesh : Struct instance The Bezier mesh data. regions : dict The patch surface regions. """ import igakit.cad as cad dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) degrees = nm.asarray(degrees, dtype=nm.int32) if continuity is None: continuity = degrees - 1 else: continuity = nm.asarray(continuity, dtype=nm.int32) dim = len(shape) output('generating NURBS...', verbose=verbose) dd = centre - 0.5 * dims block = cad.grid(shape - 1, degree=degrees, continuity=continuity) for ia in xrange(dim): block.scale(dims[ia], ia) for ia in xrange(dim): block.translate(dd[ia], ia) # Force uniform control points. This prevents coarser resolution inside the # block. shape = nm.asarray(block.points.shape[:-1]) n_nod = nm.prod(shape) 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 coors.shape = shape.tolist() + [dim] block.array[..., :dim] = coors output('...done', verbose=verbose) # Compute Bezier extraction data. output('computing Bezier mesh...', verbose=verbose) cs = iga.compute_bezier_extraction(block.knots, block.degree) n_els = [len(ii) for ii in cs] conn, bconn =
iga.create_connectivity(n_els, block.knots, block.degree)
sfepy.discrete.iga.create_connectivity
""" IGA domain generators. """ import numpy as nm from sfepy.base.base import output, Struct import sfepy.discrete.iga as iga from sfepy.discrete.iga.domain import NurbsPatch def gen_patch_block_domain(dims, shape, centre, degrees, continuity=None, name='block', verbose=True): """ Generate a single IGA patch block in 2D or 3D of given degrees and continuity using igakit. Parameters ---------- dims : array of D floats Dimensions of the block. shape : array of D ints Numbers of unique knot values along each axis. centre : array of D floats Centre of the block. degrees : array of D floats NURBS degrees along each axis. continuity : array of D ints, optional NURBS continuity along each axis. If None, `degrees-1` is used. name : string Domain name. verbose : bool If True, report progress of the domain generation. Returns ------- nurbs : NurbsPatch instance The NURBS data. The igakit NURBS object is stored as `nurbs` attribute. bmesh : Struct instance The Bezier mesh data. regions : dict The patch surface regions. """ import igakit.cad as cad dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) degrees = nm.asarray(degrees, dtype=nm.int32) if continuity is None: continuity = degrees - 1 else: continuity = nm.asarray(continuity, dtype=nm.int32) dim = len(shape) output('generating NURBS...', verbose=verbose) dd = centre - 0.5 * dims block = cad.grid(shape - 1, degree=degrees, continuity=continuity) for ia in xrange(dim): block.scale(dims[ia], ia) for ia in xrange(dim): block.translate(dd[ia], ia) # Force uniform control points. This prevents coarser resolution inside the # block. shape = nm.asarray(block.points.shape[:-1]) n_nod = nm.prod(shape) 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 coors.shape = shape.tolist() + [dim] block.array[..., :dim] = coors output('...done', verbose=verbose) # Compute Bezier extraction data. output('computing Bezier mesh...', verbose=verbose) cs = iga.compute_bezier_extraction(block.knots, block.degree) n_els = [len(ii) for ii in cs] conn, bconn = iga.create_connectivity(n_els, block.knots, block.degree) ccs =
iga.combine_bezier_extraction(cs)
sfepy.discrete.iga.combine_bezier_extraction
""" IGA domain generators. """ import numpy as nm from sfepy.base.base import output, Struct import sfepy.discrete.iga as iga from sfepy.discrete.iga.domain import NurbsPatch def gen_patch_block_domain(dims, shape, centre, degrees, continuity=None, name='block', verbose=True): """ Generate a single IGA patch block in 2D or 3D of given degrees and continuity using igakit. Parameters ---------- dims : array of D floats Dimensions of the block. shape : array of D ints Numbers of unique knot values along each axis. centre : array of D floats Centre of the block. degrees : array of D floats NURBS degrees along each axis. continuity : array of D ints, optional NURBS continuity along each axis. If None, `degrees-1` is used. name : string Domain name. verbose : bool If True, report progress of the domain generation. Returns ------- nurbs : NurbsPatch instance The NURBS data. The igakit NURBS object is stored as `nurbs` attribute. bmesh : Struct instance The Bezier mesh data. regions : dict The patch surface regions. """ import igakit.cad as cad dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) degrees = nm.asarray(degrees, dtype=nm.int32) if continuity is None: continuity = degrees - 1 else: continuity = nm.asarray(continuity, dtype=nm.int32) dim = len(shape) output('generating NURBS...', verbose=verbose) dd = centre - 0.5 * dims block = cad.grid(shape - 1, degree=degrees, continuity=continuity) for ia in xrange(dim): block.scale(dims[ia], ia) for ia in xrange(dim): block.translate(dd[ia], ia) # Force uniform control points. This prevents coarser resolution inside the # block. shape = nm.asarray(block.points.shape[:-1]) n_nod = nm.prod(shape) 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 coors.shape = shape.tolist() + [dim] block.array[..., :dim] = coors output('...done', verbose=verbose) # Compute Bezier extraction data. output('computing Bezier mesh...', verbose=verbose) cs = iga.compute_bezier_extraction(block.knots, block.degree) n_els = [len(ii) for ii in cs] conn, bconn = iga.create_connectivity(n_els, block.knots, block.degree) ccs = iga.combine_bezier_extraction(cs) cps = block.points[..., :dim].copy() cps = cps.reshape((-1, dim)) bcps, bweights = iga.compute_bezier_control(cps, block.weights.ravel(), ccs, conn, bconn) nurbs = NurbsPatch(block.knots, degrees, cps, block.weights.ravel(), cs, conn) nurbs.nurbs = block bmesh =
Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn)
sfepy.base.base.Struct
""" IGA domain generators. """ import numpy as nm from sfepy.base.base import output, Struct import sfepy.discrete.iga as iga from sfepy.discrete.iga.domain import NurbsPatch def gen_patch_block_domain(dims, shape, centre, degrees, continuity=None, name='block', verbose=True): """ Generate a single IGA patch block in 2D or 3D of given degrees and continuity using igakit. Parameters ---------- dims : array of D floats Dimensions of the block. shape : array of D ints Numbers of unique knot values along each axis. centre : array of D floats Centre of the block. degrees : array of D floats NURBS degrees along each axis. continuity : array of D ints, optional NURBS continuity along each axis. If None, `degrees-1` is used. name : string Domain name. verbose : bool If True, report progress of the domain generation. Returns ------- nurbs : NurbsPatch instance The NURBS data. The igakit NURBS object is stored as `nurbs` attribute. bmesh : Struct instance The Bezier mesh data. regions : dict The patch surface regions. """ import igakit.cad as cad dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) degrees = nm.asarray(degrees, dtype=nm.int32) if continuity is None: continuity = degrees - 1 else: continuity = nm.asarray(continuity, dtype=nm.int32) dim = len(shape) output('generating NURBS...', verbose=verbose) dd = centre - 0.5 * dims block = cad.grid(shape - 1, degree=degrees, continuity=continuity) for ia in xrange(dim): block.scale(dims[ia], ia) for ia in xrange(dim): block.translate(dd[ia], ia) # Force uniform control points. This prevents coarser resolution inside the # block. shape = nm.asarray(block.points.shape[:-1]) n_nod = nm.prod(shape) 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 coors.shape = shape.tolist() + [dim] block.array[..., :dim] = coors output('...done', verbose=verbose) # Compute Bezier extraction data. output('computing Bezier mesh...', verbose=verbose) cs = iga.compute_bezier_extraction(block.knots, block.degree) n_els = [len(ii) for ii in cs] conn, bconn = iga.create_connectivity(n_els, block.knots, block.degree) ccs = iga.combine_bezier_extraction(cs) cps = block.points[..., :dim].copy() cps = cps.reshape((-1, dim)) bcps, bweights = iga.compute_bezier_control(cps, block.weights.ravel(), ccs, conn, bconn) nurbs = NurbsPatch(block.knots, degrees, cps, block.weights.ravel(), cs, conn) nurbs.nurbs = block bmesh = Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn)
output('...done', verbose=verbose)
sfepy.base.base.output
""" IGA domain generators. """ import numpy as nm from sfepy.base.base import output, Struct import sfepy.discrete.iga as iga from sfepy.discrete.iga.domain import NurbsPatch def gen_patch_block_domain(dims, shape, centre, degrees, continuity=None, name='block', verbose=True): """ Generate a single IGA patch block in 2D or 3D of given degrees and continuity using igakit. Parameters ---------- dims : array of D floats Dimensions of the block. shape : array of D ints Numbers of unique knot values along each axis. centre : array of D floats Centre of the block. degrees : array of D floats NURBS degrees along each axis. continuity : array of D ints, optional NURBS continuity along each axis. If None, `degrees-1` is used. name : string Domain name. verbose : bool If True, report progress of the domain generation. Returns ------- nurbs : NurbsPatch instance The NURBS data. The igakit NURBS object is stored as `nurbs` attribute. bmesh : Struct instance The Bezier mesh data. regions : dict The patch surface regions. """ import igakit.cad as cad dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) degrees = nm.asarray(degrees, dtype=nm.int32) if continuity is None: continuity = degrees - 1 else: continuity = nm.asarray(continuity, dtype=nm.int32) dim = len(shape) output('generating NURBS...', verbose=verbose) dd = centre - 0.5 * dims block = cad.grid(shape - 1, degree=degrees, continuity=continuity) for ia in xrange(dim): block.scale(dims[ia], ia) for ia in xrange(dim): block.translate(dd[ia], ia) # Force uniform control points. This prevents coarser resolution inside the # block. shape = nm.asarray(block.points.shape[:-1]) n_nod = nm.prod(shape) 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 coors.shape = shape.tolist() + [dim] block.array[..., :dim] = coors output('...done', verbose=verbose) # Compute Bezier extraction data. output('computing Bezier mesh...', verbose=verbose) cs = iga.compute_bezier_extraction(block.knots, block.degree) n_els = [len(ii) for ii in cs] conn, bconn = iga.create_connectivity(n_els, block.knots, block.degree) ccs = iga.combine_bezier_extraction(cs) cps = block.points[..., :dim].copy() cps = cps.reshape((-1, dim)) bcps, bweights = iga.compute_bezier_control(cps, block.weights.ravel(), ccs, conn, bconn) nurbs = NurbsPatch(block.knots, degrees, cps, block.weights.ravel(), cs, conn) nurbs.nurbs = block bmesh = Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn) output('...done', verbose=verbose)
output('defining regions...', verbose=verbose)
sfepy.base.base.output
""" IGA domain generators. """ import numpy as nm from sfepy.base.base import output, Struct import sfepy.discrete.iga as iga from sfepy.discrete.iga.domain import NurbsPatch def gen_patch_block_domain(dims, shape, centre, degrees, continuity=None, name='block', verbose=True): """ Generate a single IGA patch block in 2D or 3D of given degrees and continuity using igakit. Parameters ---------- dims : array of D floats Dimensions of the block. shape : array of D ints Numbers of unique knot values along each axis. centre : array of D floats Centre of the block. degrees : array of D floats NURBS degrees along each axis. continuity : array of D ints, optional NURBS continuity along each axis. If None, `degrees-1` is used. name : string Domain name. verbose : bool If True, report progress of the domain generation. Returns ------- nurbs : NurbsPatch instance The NURBS data. The igakit NURBS object is stored as `nurbs` attribute. bmesh : Struct instance The Bezier mesh data. regions : dict The patch surface regions. """ import igakit.cad as cad dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) degrees = nm.asarray(degrees, dtype=nm.int32) if continuity is None: continuity = degrees - 1 else: continuity = nm.asarray(continuity, dtype=nm.int32) dim = len(shape) output('generating NURBS...', verbose=verbose) dd = centre - 0.5 * dims block = cad.grid(shape - 1, degree=degrees, continuity=continuity) for ia in xrange(dim): block.scale(dims[ia], ia) for ia in xrange(dim): block.translate(dd[ia], ia) # Force uniform control points. This prevents coarser resolution inside the # block. shape = nm.asarray(block.points.shape[:-1]) n_nod = nm.prod(shape) 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 coors.shape = shape.tolist() + [dim] block.array[..., :dim] = coors output('...done', verbose=verbose) # Compute Bezier extraction data. output('computing Bezier mesh...', verbose=verbose) cs = iga.compute_bezier_extraction(block.knots, block.degree) n_els = [len(ii) for ii in cs] conn, bconn = iga.create_connectivity(n_els, block.knots, block.degree) ccs = iga.combine_bezier_extraction(cs) cps = block.points[..., :dim].copy() cps = cps.reshape((-1, dim)) bcps, bweights = iga.compute_bezier_control(cps, block.weights.ravel(), ccs, conn, bconn) nurbs = NurbsPatch(block.knots, degrees, cps, block.weights.ravel(), cs, conn) nurbs.nurbs = block bmesh = Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn) output('...done', verbose=verbose) output('defining regions...', verbose=verbose) regions =
iga.get_patch_box_regions(n_els, block.degree)
sfepy.discrete.iga.get_patch_box_regions
""" IGA domain generators. """ import numpy as nm from sfepy.base.base import output, Struct import sfepy.discrete.iga as iga from sfepy.discrete.iga.domain import NurbsPatch def gen_patch_block_domain(dims, shape, centre, degrees, continuity=None, name='block', verbose=True): """ Generate a single IGA patch block in 2D or 3D of given degrees and continuity using igakit. Parameters ---------- dims : array of D floats Dimensions of the block. shape : array of D ints Numbers of unique knot values along each axis. centre : array of D floats Centre of the block. degrees : array of D floats NURBS degrees along each axis. continuity : array of D ints, optional NURBS continuity along each axis. If None, `degrees-1` is used. name : string Domain name. verbose : bool If True, report progress of the domain generation. Returns ------- nurbs : NurbsPatch instance The NURBS data. The igakit NURBS object is stored as `nurbs` attribute. bmesh : Struct instance The Bezier mesh data. regions : dict The patch surface regions. """ import igakit.cad as cad dims = nm.asarray(dims, dtype=nm.float64) shape = nm.asarray(shape, dtype=nm.int32) centre = nm.asarray(centre, dtype=nm.float64) degrees = nm.asarray(degrees, dtype=nm.int32) if continuity is None: continuity = degrees - 1 else: continuity = nm.asarray(continuity, dtype=nm.int32) dim = len(shape) output('generating NURBS...', verbose=verbose) dd = centre - 0.5 * dims block = cad.grid(shape - 1, degree=degrees, continuity=continuity) for ia in xrange(dim): block.scale(dims[ia], ia) for ia in xrange(dim): block.translate(dd[ia], ia) # Force uniform control points. This prevents coarser resolution inside the # block. shape = nm.asarray(block.points.shape[:-1]) n_nod = nm.prod(shape) 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 coors.shape = shape.tolist() + [dim] block.array[..., :dim] = coors output('...done', verbose=verbose) # Compute Bezier extraction data. output('computing Bezier mesh...', verbose=verbose) cs = iga.compute_bezier_extraction(block.knots, block.degree) n_els = [len(ii) for ii in cs] conn, bconn = iga.create_connectivity(n_els, block.knots, block.degree) ccs = iga.combine_bezier_extraction(cs) cps = block.points[..., :dim].copy() cps = cps.reshape((-1, dim)) bcps, bweights = iga.compute_bezier_control(cps, block.weights.ravel(), ccs, conn, bconn) nurbs = NurbsPatch(block.knots, degrees, cps, block.weights.ravel(), cs, conn) nurbs.nurbs = block bmesh = Struct(name='bmesh', cps=bcps, weights=bweights, conn=bconn) output('...done', verbose=verbose) output('defining regions...', verbose=verbose) regions = iga.get_patch_box_regions(n_els, block.degree)
output('...done', verbose=verbose)
sfepy.base.base.output
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors =
get_eval_coors(vertex_coors, vertex_conn, gps)
sfepy.discrete.fem.linearizer.get_eval_coors
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out =
convert_complex_output(out)
sfepy.discrete.fem.meshio.convert_complex_output
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape =
parse_shape(shape, region.domain.shape.dim)
sfepy.discrete.common.fields.parse_shape
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i =
invert_remap(self.vertex_remap)
sfepy.discrete.fem.utils.invert_remap
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """
assert_(dofs.ndim == 2)
sfepy.base.base.assert_
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape
assert_(n_nod == self.n_nod)
sfepy.base.base.assert_
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod)
assert_(dpn == self.shape[0])
sfepy.base.base.assert_
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs =
get_eval_dofs(dofs, self.econn, ps, ori=self.ori)
sfepy.discrete.fem.linearizer.get_eval_dofs
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors =
get_eval_coors(vertex_coors, vertex_conn, gps)
sfepy.discrete.fem.linearizer.get_eval_coors
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization, Struct(kind='strip')) out = {} if linearization.kind is None: out[key] = Struct(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=dof_names, field_name=self.name) elif linearization.kind == 'strip': if extend: ext = self.extend_dofs(dofs, fill_value) else: ext = self.remove_extra_dofs(dofs) if ext is not None: approx_order = self.get_output_approx_order() if approx_order != 0: # Has vertex data. out[key] = Struct(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs=dof_names) else: ext.shape = (ext.shape[0], 1, ext.shape[1], 1) out[key] = Struct(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=dof_names) else: mesh, vdofs, levels = self.linearize(dofs, linearization.min_level, linearization.max_level, linearization.eps) out[key] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=var_name, dofs=dof_names, mesh=mesh, levels=levels) out =
convert_complex_output(out)
sfepy.discrete.fem.meshio.convert_complex_output
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization, Struct(kind='strip')) out = {} if linearization.kind is None: out[key] = Struct(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=dof_names, field_name=self.name) elif linearization.kind == 'strip': if extend: ext = self.extend_dofs(dofs, fill_value) else: ext = self.remove_extra_dofs(dofs) if ext is not None: approx_order = self.get_output_approx_order() if approx_order != 0: # Has vertex data. out[key] = Struct(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs=dof_names) else: ext.shape = (ext.shape[0], 1, ext.shape[1], 1) out[key] = Struct(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=dof_names) else: mesh, vdofs, levels = self.linearize(dofs, linearization.min_level, linearization.max_level, linearization.eps) out[key] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=var_name, dofs=dof_names, mesh=mesh, levels=levels) out = convert_complex_output(out) return out def create_mesh(self, extra_nodes=True): """ Create a mesh from the field region, optionally including the field extra nodes. """ mesh = self.domain.mesh if self.approx_order != 0: if extra_nodes: conn = self.econn else: conn = self.econn[:, :self.gel.n_vertex] conns = [conn] mat_ids = [mesh.cmesh.cell_groups] descs = mesh.descs[:1] if extra_nodes: coors = self.coors else: coors = self.coors[:self.n_vertex_dof] mesh = Mesh.from_data(self.name, coors, None, conns, mat_ids, descs) return mesh def get_evaluate_cache(self, cache=None, share_geometry=False, verbose=False): """ Get the evaluate cache for :func:`Variable.evaluate_at() <sfepy.discrete.variables.Variable.evaluate_at()>`. Parameters ---------- cache : Struct instance, optional Optionally, use the provided instance to store the cache data. share_geometry : bool Set to True to indicate that all the evaluations will work on the same region. Certain data are then computed only for the first probe and cached. verbose : bool If False, reduce verbosity. Returns ------- cache : Struct instance The evaluate cache. """ import time try: from scipy.spatial import cKDTree as KDTree except ImportError: from scipy.spatial import KDTree from sfepy.discrete.fem.geometry_element import create_geometry_elements if cache is None: cache = Struct(name='evaluate_cache') tt = time.clock() if (cache.get('cmesh', None) is None) or not share_geometry: mesh = self.create_mesh(extra_nodes=False) cache.cmesh = cmesh = mesh.cmesh gels = create_geometry_elements() cmesh.set_local_entities(gels) cmesh.setup_entities() cache.centroids = cmesh.get_centroids(cmesh.tdim) if self.gel.name != '3_8': cache.normals0 = cmesh.get_facet_normals() cache.normals1 = None else: cache.normals0 = cmesh.get_facet_normals(0) cache.normals1 = cmesh.get_facet_normals(1) output('cmesh setup: %f s' % (time.clock()-tt), verbose=verbose) tt = time.clock() if (cache.get('kdtree', None) is None) or not share_geometry: cache.kdtree = KDTree(cmesh.coors) output('kdtree: %f s' % (time.clock()-tt), verbose=verbose) return cache def interp_to_qp(self, dofs): """ Interpolate DOFs into quadrature points. The quadrature order is given by the field approximation order. Parameters ---------- dofs : array The array of DOF values of shape `(n_nod, n_component)`. Returns ------- data_qp : array The values interpolated into the quadrature points. integral : Integral The corresponding integral defining the quadrature points. """ integral =
Integral('i', order=self.approx_order)
sfepy.discrete.integrals.Integral
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization, Struct(kind='strip')) out = {} if linearization.kind is None: out[key] = Struct(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=dof_names, field_name=self.name) elif linearization.kind == 'strip': if extend: ext = self.extend_dofs(dofs, fill_value) else: ext = self.remove_extra_dofs(dofs) if ext is not None: approx_order = self.get_output_approx_order() if approx_order != 0: # Has vertex data. out[key] = Struct(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs=dof_names) else: ext.shape = (ext.shape[0], 1, ext.shape[1], 1) out[key] = Struct(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=dof_names) else: mesh, vdofs, levels = self.linearize(dofs, linearization.min_level, linearization.max_level, linearization.eps) out[key] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=var_name, dofs=dof_names, mesh=mesh, levels=levels) out = convert_complex_output(out) return out def create_mesh(self, extra_nodes=True): """ Create a mesh from the field region, optionally including the field extra nodes. """ mesh = self.domain.mesh if self.approx_order != 0: if extra_nodes: conn = self.econn else: conn = self.econn[:, :self.gel.n_vertex] conns = [conn] mat_ids = [mesh.cmesh.cell_groups] descs = mesh.descs[:1] if extra_nodes: coors = self.coors else: coors = self.coors[:self.n_vertex_dof] mesh = Mesh.from_data(self.name, coors, None, conns, mat_ids, descs) return mesh def get_evaluate_cache(self, cache=None, share_geometry=False, verbose=False): """ Get the evaluate cache for :func:`Variable.evaluate_at() <sfepy.discrete.variables.Variable.evaluate_at()>`. Parameters ---------- cache : Struct instance, optional Optionally, use the provided instance to store the cache data. share_geometry : bool Set to True to indicate that all the evaluations will work on the same region. Certain data are then computed only for the first probe and cached. verbose : bool If False, reduce verbosity. Returns ------- cache : Struct instance The evaluate cache. """ import time try: from scipy.spatial import cKDTree as KDTree except ImportError: from scipy.spatial import KDTree from sfepy.discrete.fem.geometry_element import create_geometry_elements if cache is None: cache = Struct(name='evaluate_cache') tt = time.clock() if (cache.get('cmesh', None) is None) or not share_geometry: mesh = self.create_mesh(extra_nodes=False) cache.cmesh = cmesh = mesh.cmesh gels = create_geometry_elements() cmesh.set_local_entities(gels) cmesh.setup_entities() cache.centroids = cmesh.get_centroids(cmesh.tdim) if self.gel.name != '3_8': cache.normals0 = cmesh.get_facet_normals() cache.normals1 = None else: cache.normals0 = cmesh.get_facet_normals(0) cache.normals1 = cmesh.get_facet_normals(1) output('cmesh setup: %f s' % (time.clock()-tt), verbose=verbose) tt = time.clock() if (cache.get('kdtree', None) is None) or not share_geometry: cache.kdtree = KDTree(cmesh.coors) output('kdtree: %f s' % (time.clock()-tt), verbose=verbose) return cache def interp_to_qp(self, dofs): """ Interpolate DOFs into quadrature points. The quadrature order is given by the field approximation order. Parameters ---------- dofs : array The array of DOF values of shape `(n_nod, n_component)`. Returns ------- data_qp : array The values interpolated into the quadrature points. integral : Integral The corresponding integral defining the quadrature points. """ integral = Integral('i', order=self.approx_order) bf = self.get_base('v', False, integral) bf = bf[:,0,:].copy() data_qp = nm.dot(bf, dofs[self.econn]) data_qp = nm.swapaxes(data_qp, 0, 1) data_qp.shape = data_qp.shape + (1,) return data_qp, integral def get_coor(self, nods=None): """ Get coordinates of the field nodes. Parameters ---------- nods : array, optional The indices of the required nodes. If not given, the coordinates of all the nodes are returned. """ if nods is None: return self.coors else: return self.coors[nods] def get_connectivity(self, region, integration, is_trace=False): """ Convenience alias to `Field.get_econn()`, that is used in some terms. """ return self.get_econn(integration, region, is_trace=is_trace) def create_mapping(self, region, integral, integration, return_mapping=True): """ Create a new reference mapping. Compute jacobians, element volumes and base function derivatives for Volume-type geometries (volume mappings), and jacobians, normals and base function derivatives for Surface-type geometries (surface mappings). Notes ----- - surface mappings are defined on the surface region - surface mappings require field order to be > 0 """ domain = self.domain coors = domain.get_mesh_coors(actual=True) dconn = domain.get_conn() if integration == 'volume': qp = self.get_qp('v', integral) 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 elif (integration == 'surface') or (integration == 'surface_extra'): assert_(self.approx_order > 0) if self.ori is not None: msg = 'surface integrals do not work yet with the' \ ' hierarchical basis!' raise ValueError(msg) sd = domain.surface_groups[region.name] esd = self.surface_data[region.name] geo_ps = self.gel.poly_space ps = self.poly_space conn = sd.get_connectivity() mapping = SurfaceMapping(coors, conn, poly_space=geo_ps) if not self.is_surface: self.create_bqp(region.name, integral) qp = self.qp_coors[(integral.order, esd.bkey)] abf = ps.eval_base(qp.vals[0], transform=self.basis_transform) bf = abf[..., self.efaces[0]] indx = self.gel.get_surface_entities()[0] # Fix geometry element's 1st facet orientation for gradients. indx = nm.roll(indx, -1)[::-1] mapping.set_basis_indices(indx) sg = mapping.get_mapping(qp.vals[0], qp.weights, poly_space=Struct(n_nod=bf.shape[-1]), mode=integration) if integration == 'surface_extra': sg.alloc_extra_data(self.econn.shape[1]) bf_bg = geo_ps.eval_base(qp.vals, diff=True) ebf_bg = self.get_base(esd.bkey, 1, integral) sg.evaluate_bfbgm(bf_bg, ebf_bg, coors, sd.fis, dconn) else: # Do not use BQP for surface fields. qp = self.get_qp(sd.face_type, integral) bf = ps.eval_base(qp.vals, transform=self.basis_transform) sg = mapping.get_mapping(qp.vals, qp.weights, poly_space=Struct(n_nod=bf.shape[-1]), mode=integration) out = sg elif integration == 'point': out = mapping = None elif integration == 'custom': raise ValueError('cannot create custom mapping!') else: raise ValueError('unknown 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 class VolumeField(FEField): """ Finite element field base class over volume elements (element dimension equals space dimension). """ def _check_region(self, region): """ Check whether the `region` can be used for the field. Returns ------- ok : bool True if the region is usable for the field. """ ok = True domain = region.domain if region.kind != 'cell': output("bad region kind! (is: %r, should be: 'cell')" % region.kind) ok = False elif (region.kind_tdim != domain.shape.tdim): output('cells with a bad topological dimension! (%d == %d)' % (region.kind_tdim, domain.shape.tdim)) ok = False return ok def _setup_geometry(self): """ Setup the field region geometry. """ cmesh = self.domain.cmesh for key, gel in six.iteritems(self.domain.geom_els): ct = cmesh.cell_types if (ct[self.region.cells] == cmesh.key_to_index[gel.name]).all(): self.gel = gel break else: raise ValueError('region %s of field %s contains multiple' ' reference geometries!' % (self.region.name, self.name)) self.is_surface = False def _create_interpolant(self): name = '%s_%s_%s_%d%s' % (self.gel.name, self.space, self.poly_space_base, self.approx_order, 'B' * self.force_bubble) ps = PolySpace.any_from_args(name, self.gel, self.approx_order, base=self.poly_space_base, force_bubble=self.force_bubble) self.poly_space = ps def _init_econn(self): """ Initialize the extended DOF connectivity. """ n_ep = self.poly_space.n_nod n_cell = self.region.get_n_cells() self.econn = nm.zeros((n_cell, n_ep), nm.int32) def _setup_vertex_dofs(self): """ Setup vertex DOF connectivity. """ if self.node_desc.vertex is None: return 0, None region = self.region cmesh = self.domain.cmesh conn, offsets = cmesh.get_incident(0, region.cells, region.tdim, ret_offsets=True) vertices = nm.unique(conn) remap =
prepare_remap(vertices, region.n_v_max)
sfepy.discrete.fem.utils.prepare_remap
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization, Struct(kind='strip')) out = {} if linearization.kind is None: out[key] = Struct(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=dof_names, field_name=self.name) elif linearization.kind == 'strip': if extend: ext = self.extend_dofs(dofs, fill_value) else: ext = self.remove_extra_dofs(dofs) if ext is not None: approx_order = self.get_output_approx_order() if approx_order != 0: # Has vertex data. out[key] = Struct(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs=dof_names) else: ext.shape = (ext.shape[0], 1, ext.shape[1], 1) out[key] = Struct(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=dof_names) else: mesh, vdofs, levels = self.linearize(dofs, linearization.min_level, linearization.max_level, linearization.eps) out[key] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=var_name, dofs=dof_names, mesh=mesh, levels=levels) out = convert_complex_output(out) return out def create_mesh(self, extra_nodes=True): """ Create a mesh from the field region, optionally including the field extra nodes. """ mesh = self.domain.mesh if self.approx_order != 0: if extra_nodes: conn = self.econn else: conn = self.econn[:, :self.gel.n_vertex] conns = [conn] mat_ids = [mesh.cmesh.cell_groups] descs = mesh.descs[:1] if extra_nodes: coors = self.coors else: coors = self.coors[:self.n_vertex_dof] mesh = Mesh.from_data(self.name, coors, None, conns, mat_ids, descs) return mesh def get_evaluate_cache(self, cache=None, share_geometry=False, verbose=False): """ Get the evaluate cache for :func:`Variable.evaluate_at() <sfepy.discrete.variables.Variable.evaluate_at()>`. Parameters ---------- cache : Struct instance, optional Optionally, use the provided instance to store the cache data. share_geometry : bool Set to True to indicate that all the evaluations will work on the same region. Certain data are then computed only for the first probe and cached. verbose : bool If False, reduce verbosity. Returns ------- cache : Struct instance The evaluate cache. """ import time try: from scipy.spatial import cKDTree as KDTree except ImportError: from scipy.spatial import KDTree from sfepy.discrete.fem.geometry_element import create_geometry_elements if cache is None: cache = Struct(name='evaluate_cache') tt = time.clock() if (cache.get('cmesh', None) is None) or not share_geometry: mesh = self.create_mesh(extra_nodes=False) cache.cmesh = cmesh = mesh.cmesh gels = create_geometry_elements() cmesh.set_local_entities(gels) cmesh.setup_entities() cache.centroids = cmesh.get_centroids(cmesh.tdim) if self.gel.name != '3_8': cache.normals0 = cmesh.get_facet_normals() cache.normals1 = None else: cache.normals0 = cmesh.get_facet_normals(0) cache.normals1 = cmesh.get_facet_normals(1) output('cmesh setup: %f s' % (time.clock()-tt), verbose=verbose) tt = time.clock() if (cache.get('kdtree', None) is None) or not share_geometry: cache.kdtree = KDTree(cmesh.coors) output('kdtree: %f s' % (time.clock()-tt), verbose=verbose) return cache def interp_to_qp(self, dofs): """ Interpolate DOFs into quadrature points. The quadrature order is given by the field approximation order. Parameters ---------- dofs : array The array of DOF values of shape `(n_nod, n_component)`. Returns ------- data_qp : array The values interpolated into the quadrature points. integral : Integral The corresponding integral defining the quadrature points. """ integral = Integral('i', order=self.approx_order) bf = self.get_base('v', False, integral) bf = bf[:,0,:].copy() data_qp = nm.dot(bf, dofs[self.econn]) data_qp = nm.swapaxes(data_qp, 0, 1) data_qp.shape = data_qp.shape + (1,) return data_qp, integral def get_coor(self, nods=None): """ Get coordinates of the field nodes. Parameters ---------- nods : array, optional The indices of the required nodes. If not given, the coordinates of all the nodes are returned. """ if nods is None: return self.coors else: return self.coors[nods] def get_connectivity(self, region, integration, is_trace=False): """ Convenience alias to `Field.get_econn()`, that is used in some terms. """ return self.get_econn(integration, region, is_trace=is_trace) def create_mapping(self, region, integral, integration, return_mapping=True): """ Create a new reference mapping. Compute jacobians, element volumes and base function derivatives for Volume-type geometries (volume mappings), and jacobians, normals and base function derivatives for Surface-type geometries (surface mappings). Notes ----- - surface mappings are defined on the surface region - surface mappings require field order to be > 0 """ domain = self.domain coors = domain.get_mesh_coors(actual=True) dconn = domain.get_conn() if integration == 'volume': qp = self.get_qp('v', integral) 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 elif (integration == 'surface') or (integration == 'surface_extra'): assert_(self.approx_order > 0) if self.ori is not None: msg = 'surface integrals do not work yet with the' \ ' hierarchical basis!' raise ValueError(msg) sd = domain.surface_groups[region.name] esd = self.surface_data[region.name] geo_ps = self.gel.poly_space ps = self.poly_space conn = sd.get_connectivity() mapping = SurfaceMapping(coors, conn, poly_space=geo_ps) if not self.is_surface: self.create_bqp(region.name, integral) qp = self.qp_coors[(integral.order, esd.bkey)] abf = ps.eval_base(qp.vals[0], transform=self.basis_transform) bf = abf[..., self.efaces[0]] indx = self.gel.get_surface_entities()[0] # Fix geometry element's 1st facet orientation for gradients. indx = nm.roll(indx, -1)[::-1] mapping.set_basis_indices(indx) sg = mapping.get_mapping(qp.vals[0], qp.weights, poly_space=Struct(n_nod=bf.shape[-1]), mode=integration) if integration == 'surface_extra': sg.alloc_extra_data(self.econn.shape[1]) bf_bg = geo_ps.eval_base(qp.vals, diff=True) ebf_bg = self.get_base(esd.bkey, 1, integral) sg.evaluate_bfbgm(bf_bg, ebf_bg, coors, sd.fis, dconn) else: # Do not use BQP for surface fields. qp = self.get_qp(sd.face_type, integral) bf = ps.eval_base(qp.vals, transform=self.basis_transform) sg = mapping.get_mapping(qp.vals, qp.weights, poly_space=Struct(n_nod=bf.shape[-1]), mode=integration) out = sg elif integration == 'point': out = mapping = None elif integration == 'custom': raise ValueError('cannot create custom mapping!') else: raise ValueError('unknown 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 class VolumeField(FEField): """ Finite element field base class over volume elements (element dimension equals space dimension). """ def _check_region(self, region): """ Check whether the `region` can be used for the field. Returns ------- ok : bool True if the region is usable for the field. """ ok = True domain = region.domain if region.kind != 'cell': output("bad region kind! (is: %r, should be: 'cell')" % region.kind) ok = False elif (region.kind_tdim != domain.shape.tdim): output('cells with a bad topological dimension! (%d == %d)' % (region.kind_tdim, domain.shape.tdim)) ok = False return ok def _setup_geometry(self): """ Setup the field region geometry. """ cmesh = self.domain.cmesh for key, gel in six.iteritems(self.domain.geom_els): ct = cmesh.cell_types if (ct[self.region.cells] == cmesh.key_to_index[gel.name]).all(): self.gel = gel break else: raise ValueError('region %s of field %s contains multiple' ' reference geometries!' % (self.region.name, self.name)) self.is_surface = False def _create_interpolant(self): name = '%s_%s_%s_%d%s' % (self.gel.name, self.space, self.poly_space_base, self.approx_order, 'B' * self.force_bubble) ps = PolySpace.any_from_args(name, self.gel, self.approx_order, base=self.poly_space_base, force_bubble=self.force_bubble) self.poly_space = ps def _init_econn(self): """ Initialize the extended DOF connectivity. """ n_ep = self.poly_space.n_nod n_cell = self.region.get_n_cells() self.econn = nm.zeros((n_cell, n_ep), nm.int32) def _setup_vertex_dofs(self): """ Setup vertex DOF connectivity. """ if self.node_desc.vertex is None: return 0, None region = self.region cmesh = self.domain.cmesh conn, offsets = cmesh.get_incident(0, region.cells, region.tdim, ret_offsets=True) vertices = nm.unique(conn) remap = prepare_remap(vertices, region.n_v_max) n_dof = vertices.shape[0] aux = nm.unique(nm.diff(offsets)) assert_(len(aux) == 1, 'region with multiple reference geometries!') offset = aux[0] # Remap vertex node connectivity to field-local numbering. aux = conn.reshape((-1, offset)).astype(nm.int32) self.econn[:, :offset] = nm.take(remap, aux) return n_dof, remap def setup_extra_data(self, geometry, info, is_trace): dct = info.dc_type.type if geometry != None: geometry_flag = 'surface' in geometry else: geometry_flag = False if (dct == 'surface') or (geometry_flag): reg = info.get_region() mreg_name = info.get_region_name(can_trace=False) self.domain.create_surface_group(reg) self.setup_surface_data(reg, is_trace, mreg_name) elif dct == 'edge': raise NotImplementedError('dof connectivity type %s' % dct) elif dct == 'point': self.setup_point_data(self, info.region) elif dct not in ('volume', 'scalar', 'custom'): raise ValueError('unknown dof connectivity type! (%s)' % dct) def setup_point_data(self, field, region): if region.name not in self.point_data: conn = field.get_dofs_in_region(region, merge=True) conn.shape += (1,) self.point_data[region.name] = conn def setup_surface_data(self, region, is_trace=False, trace_region=None): """nodes[leconn] == econn""" """nodes are sorted by node number -> same order as region.vertices""" if region.name not in self.surface_data: sd = FESurface('surface_data_%s' % region.name, region, self.efaces, self.econn, self.region) self.surface_data[region.name] = sd if region.name in self.surface_data and is_trace: sd = self.surface_data[region.name] sd.setup_mirror_connectivity(region, trace_region) return self.surface_data[region.name] def get_econn(self, conn_type, region, is_trace=False, integration=None): """ Get extended connectivity of the given type in the given region. """ ct = conn_type.type if isinstance(conn_type, Struct) else conn_type if ct in ('volume', 'custom'): if region.name == self.region.name: conn = self.econn else: tco = integration in ('volume', 'custom') cells = region.get_cells(true_cells_only=tco) ii = self.region.get_cell_indices(cells, true_cells_only=tco) conn = nm.take(self.econn, ii, axis=0) elif ct == 'surface': sd = self.surface_data[region.name] conn = sd.get_connectivity(is_trace=is_trace) elif ct == 'edge': raise NotImplementedError('connectivity type %s' % ct) elif ct == 'point': conn = self.point_data[region.name] else: raise ValueError('unknown connectivity type! (%s)' % ct) return conn def average_qp_to_vertices(self, data_qp, integral): """ Average data given in quadrature points in region elements into region vertices. .. math:: u_n = \sum_e (u_{e,avg} * volume_e) / \sum_e volume_e = \sum_e \int_{volume_e} u / \sum volume_e """ region = self.region n_cells = region.get_n_cells() if n_cells != data_qp.shape[0]: msg = 'incomatible shape! (%d == %d)' % (n_cells, data_qp.shape[0]) raise ValueError(msg) n_vertex = self.n_vertex_dof nc = data_qp.shape[2] nod_vol = nm.zeros((n_vertex,), dtype=nm.float64) data_vertex = nm.zeros((n_vertex, nc), dtype=nm.float64) vg = self.get_mapping(self.region, integral, 'volume')[0] volume = nm.squeeze(vg.volume) iels = self.region.get_cells() data_e = nm.zeros((volume.shape[0], 1, nc, 1), dtype=nm.float64) vg.integrate(data_e, data_qp[iels]) ir = nm.arange(nc, dtype=nm.int32) conn = self.econn[:, :self.gel.n_vertex] for ii, cc in enumerate(conn): # Assumes unique nodes in cc! ind2, ind1 = nm.meshgrid(ir, cc) data_vertex[ind1,ind2] += data_e[iels[ii],0,:,0] nod_vol[cc] += volume[ii] data_vertex /= nod_vol[:,nm.newaxis] return data_vertex class SurfaceField(FEField): """ Finite element field base class over surface (element dimension is one less than space dimension). """ def _check_region(self, region): """ Check whether the `region` can be used for the field. Returns ------- ok : bool True if the region is usable for the field. """ ok1 = ((region.kind_tdim == (region.tdim - 1)) and (region.get_n_cells(True) > 0)) if not ok1: output('bad region topological dimension and kind! (%d, %s)' % (region.tdim, region.kind)) n_ns = region.get_facet_indices().shape[0] - region.get_n_cells(True) ok2 = n_ns == 0 if not ok2: output('%d region facets are not on the domain surface!' % n_ns) return ok1 and ok2 def _setup_geometry(self): """ Setup the field region geometry. """ for key, vgel in six.iteritems(self.domain.geom_els): self.gel = vgel.surface_facet break if self.gel is None: raise ValueError('cells with no surface!') self.is_surface = True def _create_interpolant(self): name = '%s_%s_%s_%d%s' % (self.gel.name, self.space, self.poly_space_base, self.approx_order, 'B' * self.force_bubble) ps = PolySpace.any_from_args(name, self.gel, self.approx_order, base=self.poly_space_base, force_bubble=self.force_bubble) self.poly_space = ps def setup_extra_data(self, geometry, info, is_trace): dct = info.dc_type.type if dct != 'surface': msg = "dof connectivity type must be 'surface'! (%s)" % dct raise ValueError(msg) reg = info.get_region() if reg.name not in self.surface_data: # Defined in setup_vertex_dofs() msg = 'no surface data of surface field! (%s)' % reg.name raise ValueError(msg) if reg.name in self.surface_data and is_trace: sd = self.surface_data[reg.name] mreg_name = info.get_region_name(can_trace=False) sd.setup_mirror_connectivity(reg, mreg_name) def _init_econn(self): """ Initialize the extended DOF connectivity. """ n_ep = self.poly_space.n_nod n_cell = self.region.get_n_cells(is_surface=self.is_surface) self.econn = nm.zeros((n_cell, n_ep), nm.int32) def _setup_vertex_dofs(self): """ Setup vertex DOF connectivity. """ if self.node_desc.vertex is None: return 0, None region = self.region remap =
prepare_remap(region.vertices, region.n_v_max)
sfepy.discrete.fem.utils.prepare_remap
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization, Struct(kind='strip')) out = {} if linearization.kind is None: out[key] = Struct(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=dof_names, field_name=self.name) elif linearization.kind == 'strip': if extend: ext = self.extend_dofs(dofs, fill_value) else: ext = self.remove_extra_dofs(dofs) if ext is not None: approx_order = self.get_output_approx_order() if approx_order != 0: # Has vertex data. out[key] = Struct(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs=dof_names) else: ext.shape = (ext.shape[0], 1, ext.shape[1], 1) out[key] = Struct(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=dof_names) else: mesh, vdofs, levels = self.linearize(dofs, linearization.min_level, linearization.max_level, linearization.eps) out[key] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=var_name, dofs=dof_names, mesh=mesh, levels=levels) out = convert_complex_output(out) return out def create_mesh(self, extra_nodes=True): """ Create a mesh from the field region, optionally including the field extra nodes. """ mesh = self.domain.mesh if self.approx_order != 0: if extra_nodes: conn = self.econn else: conn = self.econn[:, :self.gel.n_vertex] conns = [conn] mat_ids = [mesh.cmesh.cell_groups] descs = mesh.descs[:1] if extra_nodes: coors = self.coors else: coors = self.coors[:self.n_vertex_dof] mesh = Mesh.from_data(self.name, coors, None, conns, mat_ids, descs) return mesh def get_evaluate_cache(self, cache=None, share_geometry=False, verbose=False): """ Get the evaluate cache for :func:`Variable.evaluate_at() <sfepy.discrete.variables.Variable.evaluate_at()>`. Parameters ---------- cache : Struct instance, optional Optionally, use the provided instance to store the cache data. share_geometry : bool Set to True to indicate that all the evaluations will work on the same region. Certain data are then computed only for the first probe and cached. verbose : bool If False, reduce verbosity. Returns ------- cache : Struct instance The evaluate cache. """ import time try: from scipy.spatial import cKDTree as KDTree except ImportError: from scipy.spatial import KDTree from sfepy.discrete.fem.geometry_element import create_geometry_elements if cache is None: cache = Struct(name='evaluate_cache') tt = time.clock() if (cache.get('cmesh', None) is None) or not share_geometry: mesh = self.create_mesh(extra_nodes=False) cache.cmesh = cmesh = mesh.cmesh gels = create_geometry_elements() cmesh.set_local_entities(gels) cmesh.setup_entities() cache.centroids = cmesh.get_centroids(cmesh.tdim) if self.gel.name != '3_8': cache.normals0 = cmesh.get_facet_normals() cache.normals1 = None else: cache.normals0 = cmesh.get_facet_normals(0) cache.normals1 = cmesh.get_facet_normals(1) output('cmesh setup: %f s' % (time.clock()-tt), verbose=verbose) tt = time.clock() if (cache.get('kdtree', None) is None) or not share_geometry: cache.kdtree = KDTree(cmesh.coors) output('kdtree: %f s' % (time.clock()-tt), verbose=verbose) return cache def interp_to_qp(self, dofs): """ Interpolate DOFs into quadrature points. The quadrature order is given by the field approximation order. Parameters ---------- dofs : array The array of DOF values of shape `(n_nod, n_component)`. Returns ------- data_qp : array The values interpolated into the quadrature points. integral : Integral The corresponding integral defining the quadrature points. """ integral = Integral('i', order=self.approx_order) bf = self.get_base('v', False, integral) bf = bf[:,0,:].copy() data_qp = nm.dot(bf, dofs[self.econn]) data_qp = nm.swapaxes(data_qp, 0, 1) data_qp.shape = data_qp.shape + (1,) return data_qp, integral def get_coor(self, nods=None): """ Get coordinates of the field nodes. Parameters ---------- nods : array, optional The indices of the required nodes. If not given, the coordinates of all the nodes are returned. """ if nods is None: return self.coors else: return self.coors[nods] def get_connectivity(self, region, integration, is_trace=False): """ Convenience alias to `Field.get_econn()`, that is used in some terms. """ return self.get_econn(integration, region, is_trace=is_trace) def create_mapping(self, region, integral, integration, return_mapping=True): """ Create a new reference mapping. Compute jacobians, element volumes and base function derivatives for Volume-type geometries (volume mappings), and jacobians, normals and base function derivatives for Surface-type geometries (surface mappings). Notes ----- - surface mappings are defined on the surface region - surface mappings require field order to be > 0 """ domain = self.domain coors = domain.get_mesh_coors(actual=True) dconn = domain.get_conn() if integration == 'volume': qp = self.get_qp('v', integral) 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 elif (integration == 'surface') or (integration == 'surface_extra'): assert_(self.approx_order > 0) if self.ori is not None: msg = 'surface integrals do not work yet with the' \ ' hierarchical basis!' raise ValueError(msg) sd = domain.surface_groups[region.name] esd = self.surface_data[region.name] geo_ps = self.gel.poly_space ps = self.poly_space conn = sd.get_connectivity() mapping = SurfaceMapping(coors, conn, poly_space=geo_ps) if not self.is_surface: self.create_bqp(region.name, integral) qp = self.qp_coors[(integral.order, esd.bkey)] abf = ps.eval_base(qp.vals[0], transform=self.basis_transform) bf = abf[..., self.efaces[0]] indx = self.gel.get_surface_entities()[0] # Fix geometry element's 1st facet orientation for gradients. indx = nm.roll(indx, -1)[::-1] mapping.set_basis_indices(indx) sg = mapping.get_mapping(qp.vals[0], qp.weights, poly_space=Struct(n_nod=bf.shape[-1]), mode=integration) if integration == 'surface_extra': sg.alloc_extra_data(self.econn.shape[1]) bf_bg = geo_ps.eval_base(qp.vals, diff=True) ebf_bg = self.get_base(esd.bkey, 1, integral) sg.evaluate_bfbgm(bf_bg, ebf_bg, coors, sd.fis, dconn) else: # Do not use BQP for surface fields. qp = self.get_qp(sd.face_type, integral) bf = ps.eval_base(qp.vals, transform=self.basis_transform) sg = mapping.get_mapping(qp.vals, qp.weights, poly_space=Struct(n_nod=bf.shape[-1]), mode=integration) out = sg elif integration == 'point': out = mapping = None elif integration == 'custom': raise ValueError('cannot create custom mapping!') else: raise ValueError('unknown 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 class VolumeField(FEField): """ Finite element field base class over volume elements (element dimension equals space dimension). """ def _check_region(self, region): """ Check whether the `region` can be used for the field. Returns ------- ok : bool True if the region is usable for the field. """ ok = True domain = region.domain if region.kind != 'cell': output("bad region kind! (is: %r, should be: 'cell')" % region.kind) ok = False elif (region.kind_tdim != domain.shape.tdim): output('cells with a bad topological dimension! (%d == %d)' % (region.kind_tdim, domain.shape.tdim)) ok = False return ok def _setup_geometry(self): """ Setup the field region geometry. """ cmesh = self.domain.cmesh for key, gel in six.iteritems(self.domain.geom_els): ct = cmesh.cell_types if (ct[self.region.cells] == cmesh.key_to_index[gel.name]).all(): self.gel = gel break else: raise ValueError('region %s of field %s contains multiple' ' reference geometries!' % (self.region.name, self.name)) self.is_surface = False def _create_interpolant(self): name = '%s_%s_%s_%d%s' % (self.gel.name, self.space, self.poly_space_base, self.approx_order, 'B' * self.force_bubble) ps = PolySpace.any_from_args(name, self.gel, self.approx_order, base=self.poly_space_base, force_bubble=self.force_bubble) self.poly_space = ps def _init_econn(self): """ Initialize the extended DOF connectivity. """ n_ep = self.poly_space.n_nod n_cell = self.region.get_n_cells() self.econn = nm.zeros((n_cell, n_ep), nm.int32) def _setup_vertex_dofs(self): """ Setup vertex DOF connectivity. """ if self.node_desc.vertex is None: return 0, None region = self.region cmesh = self.domain.cmesh conn, offsets = cmesh.get_incident(0, region.cells, region.tdim, ret_offsets=True) vertices = nm.unique(conn) remap = prepare_remap(vertices, region.n_v_max) n_dof = vertices.shape[0] aux = nm.unique(nm.diff(offsets)) assert_(len(aux) == 1, 'region with multiple reference geometries!') offset = aux[0] # Remap vertex node connectivity to field-local numbering. aux = conn.reshape((-1, offset)).astype(nm.int32) self.econn[:, :offset] = nm.take(remap, aux) return n_dof, remap def setup_extra_data(self, geometry, info, is_trace): dct = info.dc_type.type if geometry != None: geometry_flag = 'surface' in geometry else: geometry_flag = False if (dct == 'surface') or (geometry_flag): reg = info.get_region() mreg_name = info.get_region_name(can_trace=False) self.domain.create_surface_group(reg) self.setup_surface_data(reg, is_trace, mreg_name) elif dct == 'edge': raise NotImplementedError('dof connectivity type %s' % dct) elif dct == 'point': self.setup_point_data(self, info.region) elif dct not in ('volume', 'scalar', 'custom'): raise ValueError('unknown dof connectivity type! (%s)' % dct) def setup_point_data(self, field, region): if region.name not in self.point_data: conn = field.get_dofs_in_region(region, merge=True) conn.shape += (1,) self.point_data[region.name] = conn def setup_surface_data(self, region, is_trace=False, trace_region=None): """nodes[leconn] == econn""" """nodes are sorted by node number -> same order as region.vertices""" if region.name not in self.surface_data: sd = FESurface('surface_data_%s' % region.name, region, self.efaces, self.econn, self.region) self.surface_data[region.name] = sd if region.name in self.surface_data and is_trace: sd = self.surface_data[region.name] sd.setup_mirror_connectivity(region, trace_region) return self.surface_data[region.name] def get_econn(self, conn_type, region, is_trace=False, integration=None): """ Get extended connectivity of the given type in the given region. """ ct = conn_type.type if isinstance(conn_type, Struct) else conn_type if ct in ('volume', 'custom'): if region.name == self.region.name: conn = self.econn else: tco = integration in ('volume', 'custom') cells = region.get_cells(true_cells_only=tco) ii = self.region.get_cell_indices(cells, true_cells_only=tco) conn = nm.take(self.econn, ii, axis=0) elif ct == 'surface': sd = self.surface_data[region.name] conn = sd.get_connectivity(is_trace=is_trace) elif ct == 'edge': raise NotImplementedError('connectivity type %s' % ct) elif ct == 'point': conn = self.point_data[region.name] else: raise ValueError('unknown connectivity type! (%s)' % ct) return conn def average_qp_to_vertices(self, data_qp, integral): """ Average data given in quadrature points in region elements into region vertices. .. math:: u_n = \sum_e (u_{e,avg} * volume_e) / \sum_e volume_e = \sum_e \int_{volume_e} u / \sum volume_e """ region = self.region n_cells = region.get_n_cells() if n_cells != data_qp.shape[0]: msg = 'incomatible shape! (%d == %d)' % (n_cells, data_qp.shape[0]) raise ValueError(msg) n_vertex = self.n_vertex_dof nc = data_qp.shape[2] nod_vol = nm.zeros((n_vertex,), dtype=nm.float64) data_vertex = nm.zeros((n_vertex, nc), dtype=nm.float64) vg = self.get_mapping(self.region, integral, 'volume')[0] volume = nm.squeeze(vg.volume) iels = self.region.get_cells() data_e = nm.zeros((volume.shape[0], 1, nc, 1), dtype=nm.float64) vg.integrate(data_e, data_qp[iels]) ir = nm.arange(nc, dtype=nm.int32) conn = self.econn[:, :self.gel.n_vertex] for ii, cc in enumerate(conn): # Assumes unique nodes in cc! ind2, ind1 = nm.meshgrid(ir, cc) data_vertex[ind1,ind2] += data_e[iels[ii],0,:,0] nod_vol[cc] += volume[ii] data_vertex /= nod_vol[:,nm.newaxis] return data_vertex class SurfaceField(FEField): """ Finite element field base class over surface (element dimension is one less than space dimension). """ def _check_region(self, region): """ Check whether the `region` can be used for the field. Returns ------- ok : bool True if the region is usable for the field. """ ok1 = ((region.kind_tdim == (region.tdim - 1)) and (region.get_n_cells(True) > 0)) if not ok1: output('bad region topological dimension and kind! (%d, %s)' % (region.tdim, region.kind)) n_ns = region.get_facet_indices().shape[0] - region.get_n_cells(True) ok2 = n_ns == 0 if not ok2: output('%d region facets are not on the domain surface!' % n_ns) return ok1 and ok2 def _setup_geometry(self): """ Setup the field region geometry. """ for key, vgel in six.iteritems(self.domain.geom_els): self.gel = vgel.surface_facet break if self.gel is None: raise ValueError('cells with no surface!') self.is_surface = True def _create_interpolant(self): name = '%s_%s_%s_%d%s' % (self.gel.name, self.space, self.poly_space_base, self.approx_order, 'B' * self.force_bubble) ps = PolySpace.any_from_args(name, self.gel, self.approx_order, base=self.poly_space_base, force_bubble=self.force_bubble) self.poly_space = ps def setup_extra_data(self, geometry, info, is_trace): dct = info.dc_type.type if dct != 'surface': msg = "dof connectivity type must be 'surface'! (%s)" % dct raise ValueError(msg) reg = info.get_region() if reg.name not in self.surface_data: # Defined in setup_vertex_dofs() msg = 'no surface data of surface field! (%s)' % reg.name raise ValueError(msg) if reg.name in self.surface_data and is_trace: sd = self.surface_data[reg.name] mreg_name = info.get_region_name(can_trace=False) sd.setup_mirror_connectivity(reg, mreg_name) def _init_econn(self): """ Initialize the extended DOF connectivity. """ n_ep = self.poly_space.n_nod n_cell = self.region.get_n_cells(is_surface=self.is_surface) self.econn = nm.zeros((n_cell, n_ep), nm.int32) def _setup_vertex_dofs(self): """ Setup vertex DOF connectivity. """ if self.node_desc.vertex is None: return 0, None region = self.region remap = prepare_remap(region.vertices, region.n_v_max) n_dof = region.vertices.shape[0] # Remap vertex node connectivity to field-local numbering. conn, gel = self.domain.get_conn(ret_gel=True) faces = gel.get_surface_entities() aux =
FESurface('aux', region, faces, conn)
sfepy.discrete.fem.fe_surface.FESurface
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] =
Struct(vals=vals, weights=weights)
sfepy.base.base.Struct
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization,
Struct(kind='strip')
sfepy.base.base.Struct
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization, Struct(kind='strip')) out = {} if linearization.kind is None: out[key] = Struct(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=dof_names, field_name=self.name) elif linearization.kind == 'strip': if extend: ext = self.extend_dofs(dofs, fill_value) else: ext = self.remove_extra_dofs(dofs) if ext is not None: approx_order = self.get_output_approx_order() if approx_order != 0: # Has vertex data. out[key] = Struct(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs=dof_names) else: ext.shape = (ext.shape[0], 1, ext.shape[1], 1) out[key] = Struct(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=dof_names) else: mesh, vdofs, levels = self.linearize(dofs, linearization.min_level, linearization.max_level, linearization.eps) out[key] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=var_name, dofs=dof_names, mesh=mesh, levels=levels) out = convert_complex_output(out) return out def create_mesh(self, extra_nodes=True): """ Create a mesh from the field region, optionally including the field extra nodes. """ mesh = self.domain.mesh if self.approx_order != 0: if extra_nodes: conn = self.econn else: conn = self.econn[:, :self.gel.n_vertex] conns = [conn] mat_ids = [mesh.cmesh.cell_groups] descs = mesh.descs[:1] if extra_nodes: coors = self.coors else: coors = self.coors[:self.n_vertex_dof] mesh = Mesh.from_data(self.name, coors, None, conns, mat_ids, descs) return mesh def get_evaluate_cache(self, cache=None, share_geometry=False, verbose=False): """ Get the evaluate cache for :func:`Variable.evaluate_at() <sfepy.discrete.variables.Variable.evaluate_at()>`. Parameters ---------- cache : Struct instance, optional Optionally, use the provided instance to store the cache data. share_geometry : bool Set to True to indicate that all the evaluations will work on the same region. Certain data are then computed only for the first probe and cached. verbose : bool If False, reduce verbosity. Returns ------- cache : Struct instance The evaluate cache. """ import time try: from scipy.spatial import cKDTree as KDTree except ImportError: from scipy.spatial import KDTree from sfepy.discrete.fem.geometry_element import create_geometry_elements if cache is None: cache =
Struct(name='evaluate_cache')
sfepy.base.base.Struct
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization, Struct(kind='strip')) out = {} if linearization.kind is None: out[key] = Struct(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=dof_names, field_name=self.name) elif linearization.kind == 'strip': if extend: ext = self.extend_dofs(dofs, fill_value) else: ext = self.remove_extra_dofs(dofs) if ext is not None: approx_order = self.get_output_approx_order() if approx_order != 0: # Has vertex data. out[key] = Struct(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs=dof_names) else: ext.shape = (ext.shape[0], 1, ext.shape[1], 1) out[key] = Struct(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=dof_names) else: mesh, vdofs, levels = self.linearize(dofs, linearization.min_level, linearization.max_level, linearization.eps) out[key] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=var_name, dofs=dof_names, mesh=mesh, levels=levels) out = convert_complex_output(out) return out def create_mesh(self, extra_nodes=True): """ Create a mesh from the field region, optionally including the field extra nodes. """ mesh = self.domain.mesh if self.approx_order != 0: if extra_nodes: conn = self.econn else: conn = self.econn[:, :self.gel.n_vertex] conns = [conn] mat_ids = [mesh.cmesh.cell_groups] descs = mesh.descs[:1] if extra_nodes: coors = self.coors else: coors = self.coors[:self.n_vertex_dof] mesh = Mesh.from_data(self.name, coors, None, conns, mat_ids, descs) return mesh def get_evaluate_cache(self, cache=None, share_geometry=False, verbose=False): """ Get the evaluate cache for :func:`Variable.evaluate_at() <sfepy.discrete.variables.Variable.evaluate_at()>`. Parameters ---------- cache : Struct instance, optional Optionally, use the provided instance to store the cache data. share_geometry : bool Set to True to indicate that all the evaluations will work on the same region. Certain data are then computed only for the first probe and cached. verbose : bool If False, reduce verbosity. Returns ------- cache : Struct instance The evaluate cache. """ import time try: from scipy.spatial import cKDTree as KDTree except ImportError: from scipy.spatial import KDTree from sfepy.discrete.fem.geometry_element import create_geometry_elements if cache is None: cache = Struct(name='evaluate_cache') tt = time.clock() if (cache.get('cmesh', None) is None) or not share_geometry: mesh = self.create_mesh(extra_nodes=False) cache.cmesh = cmesh = mesh.cmesh gels =
create_geometry_elements()
sfepy.discrete.fem.geometry_element.create_geometry_elements
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization, Struct(kind='strip')) out = {} if linearization.kind is None: out[key] = Struct(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=dof_names, field_name=self.name) elif linearization.kind == 'strip': if extend: ext = self.extend_dofs(dofs, fill_value) else: ext = self.remove_extra_dofs(dofs) if ext is not None: approx_order = self.get_output_approx_order() if approx_order != 0: # Has vertex data. out[key] = Struct(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs=dof_names) else: ext.shape = (ext.shape[0], 1, ext.shape[1], 1) out[key] = Struct(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=dof_names) else: mesh, vdofs, levels = self.linearize(dofs, linearization.min_level, linearization.max_level, linearization.eps) out[key] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=var_name, dofs=dof_names, mesh=mesh, levels=levels) out = convert_complex_output(out) return out def create_mesh(self, extra_nodes=True): """ Create a mesh from the field region, optionally including the field extra nodes. """ mesh = self.domain.mesh if self.approx_order != 0: if extra_nodes: conn = self.econn else: conn = self.econn[:, :self.gel.n_vertex] conns = [conn] mat_ids = [mesh.cmesh.cell_groups] descs = mesh.descs[:1] if extra_nodes: coors = self.coors else: coors = self.coors[:self.n_vertex_dof] mesh = Mesh.from_data(self.name, coors, None, conns, mat_ids, descs) return mesh def get_evaluate_cache(self, cache=None, share_geometry=False, verbose=False): """ Get the evaluate cache for :func:`Variable.evaluate_at() <sfepy.discrete.variables.Variable.evaluate_at()>`. Parameters ---------- cache : Struct instance, optional Optionally, use the provided instance to store the cache data. share_geometry : bool Set to True to indicate that all the evaluations will work on the same region. Certain data are then computed only for the first probe and cached. verbose : bool If False, reduce verbosity. Returns ------- cache : Struct instance The evaluate cache. """ import time try: from scipy.spatial import cKDTree as KDTree except ImportError: from scipy.spatial import KDTree from sfepy.discrete.fem.geometry_element import create_geometry_elements if cache is None: cache = Struct(name='evaluate_cache') tt = time.clock() if (cache.get('cmesh', None) is None) or not share_geometry: mesh = self.create_mesh(extra_nodes=False) cache.cmesh = cmesh = mesh.cmesh gels = create_geometry_elements() cmesh.set_local_entities(gels) cmesh.setup_entities() cache.centroids = cmesh.get_centroids(cmesh.tdim) if self.gel.name != '3_8': cache.normals0 = cmesh.get_facet_normals() cache.normals1 = None else: cache.normals0 = cmesh.get_facet_normals(0) cache.normals1 = cmesh.get_facet_normals(1) output('cmesh setup: %f s' % (time.clock()-tt), verbose=verbose) tt = time.clock() if (cache.get('kdtree', None) is None) or not share_geometry: cache.kdtree = KDTree(cmesh.coors) output('kdtree: %f s' % (time.clock()-tt), verbose=verbose) return cache def interp_to_qp(self, dofs): """ Interpolate DOFs into quadrature points. The quadrature order is given by the field approximation order. Parameters ---------- dofs : array The array of DOF values of shape `(n_nod, n_component)`. Returns ------- data_qp : array The values interpolated into the quadrature points. integral : Integral The corresponding integral defining the quadrature points. """ integral = Integral('i', order=self.approx_order) bf = self.get_base('v', False, integral) bf = bf[:,0,:].copy() data_qp = nm.dot(bf, dofs[self.econn]) data_qp = nm.swapaxes(data_qp, 0, 1) data_qp.shape = data_qp.shape + (1,) return data_qp, integral def get_coor(self, nods=None): """ Get coordinates of the field nodes. Parameters ---------- nods : array, optional The indices of the required nodes. If not given, the coordinates of all the nodes are returned. """ if nods is None: return self.coors else: return self.coors[nods] def get_connectivity(self, region, integration, is_trace=False): """ Convenience alias to `Field.get_econn()`, that is used in some terms. """ return self.get_econn(integration, region, is_trace=is_trace) def create_mapping(self, region, integral, integration, return_mapping=True): """ Create a new reference mapping. Compute jacobians, element volumes and base function derivatives for Volume-type geometries (volume mappings), and jacobians, normals and base function derivatives for Surface-type geometries (surface mappings). Notes ----- - surface mappings are defined on the surface region - surface mappings require field order to be > 0 """ domain = self.domain coors = domain.get_mesh_coors(actual=True) dconn = domain.get_conn() if integration == 'volume': qp = self.get_qp('v', integral) 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
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization, Struct(kind='strip')) out = {} if linearization.kind is None: out[key] = Struct(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=dof_names, field_name=self.name) elif linearization.kind == 'strip': if extend: ext = self.extend_dofs(dofs, fill_value) else: ext = self.remove_extra_dofs(dofs) if ext is not None: approx_order = self.get_output_approx_order() if approx_order != 0: # Has vertex data. out[key] = Struct(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs=dof_names) else: ext.shape = (ext.shape[0], 1, ext.shape[1], 1) out[key] = Struct(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=dof_names) else: mesh, vdofs, levels = self.linearize(dofs, linearization.min_level, linearization.max_level, linearization.eps) out[key] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=var_name, dofs=dof_names, mesh=mesh, levels=levels) out = convert_complex_output(out) return out def create_mesh(self, extra_nodes=True): """ Create a mesh from the field region, optionally including the field extra nodes. """ mesh = self.domain.mesh if self.approx_order != 0: if extra_nodes: conn = self.econn else: conn = self.econn[:, :self.gel.n_vertex] conns = [conn] mat_ids = [mesh.cmesh.cell_groups] descs = mesh.descs[:1] if extra_nodes: coors = self.coors else: coors = self.coors[:self.n_vertex_dof] mesh = Mesh.from_data(self.name, coors, None, conns, mat_ids, descs) return mesh def get_evaluate_cache(self, cache=None, share_geometry=False, verbose=False): """ Get the evaluate cache for :func:`Variable.evaluate_at() <sfepy.discrete.variables.Variable.evaluate_at()>`. Parameters ---------- cache : Struct instance, optional Optionally, use the provided instance to store the cache data. share_geometry : bool Set to True to indicate that all the evaluations will work on the same region. Certain data are then computed only for the first probe and cached. verbose : bool If False, reduce verbosity. Returns ------- cache : Struct instance The evaluate cache. """ import time try: from scipy.spatial import cKDTree as KDTree except ImportError: from scipy.spatial import KDTree from sfepy.discrete.fem.geometry_element import create_geometry_elements if cache is None: cache = Struct(name='evaluate_cache') tt = time.clock() if (cache.get('cmesh', None) is None) or not share_geometry: mesh = self.create_mesh(extra_nodes=False) cache.cmesh = cmesh = mesh.cmesh gels = create_geometry_elements() cmesh.set_local_entities(gels) cmesh.setup_entities() cache.centroids = cmesh.get_centroids(cmesh.tdim) if self.gel.name != '3_8': cache.normals0 = cmesh.get_facet_normals() cache.normals1 = None else: cache.normals0 = cmesh.get_facet_normals(0) cache.normals1 = cmesh.get_facet_normals(1) output('cmesh setup: %f s' % (time.clock()-tt), verbose=verbose) tt = time.clock() if (cache.get('kdtree', None) is None) or not share_geometry: cache.kdtree = KDTree(cmesh.coors) output('kdtree: %f s' % (time.clock()-tt), verbose=verbose) return cache def interp_to_qp(self, dofs): """ Interpolate DOFs into quadrature points. The quadrature order is given by the field approximation order. Parameters ---------- dofs : array The array of DOF values of shape `(n_nod, n_component)`. Returns ------- data_qp : array The values interpolated into the quadrature points. integral : Integral The corresponding integral defining the quadrature points. """ integral = Integral('i', order=self.approx_order) bf = self.get_base('v', False, integral) bf = bf[:,0,:].copy() data_qp = nm.dot(bf, dofs[self.econn]) data_qp = nm.swapaxes(data_qp, 0, 1) data_qp.shape = data_qp.shape + (1,) return data_qp, integral def get_coor(self, nods=None): """ Get coordinates of the field nodes. Parameters ---------- nods : array, optional The indices of the required nodes. If not given, the coordinates of all the nodes are returned. """ if nods is None: return self.coors else: return self.coors[nods] def get_connectivity(self, region, integration, is_trace=False): """ Convenience alias to `Field.get_econn()`, that is used in some terms. """ return self.get_econn(integration, region, is_trace=is_trace) def create_mapping(self, region, integral, integration, return_mapping=True): """ Create a new reference mapping. Compute jacobians, element volumes and base function derivatives for Volume-type geometries (volume mappings), and jacobians, normals and base function derivatives for Surface-type geometries (surface mappings). Notes ----- - surface mappings are defined on the surface region - surface mappings require field order to be > 0 """ domain = self.domain coors = domain.get_mesh_coors(actual=True) dconn = domain.get_conn() if integration == 'volume': qp = self.get_qp('v', integral) 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 elif (integration == 'surface') or (integration == 'surface_extra'): assert_(self.approx_order > 0) if self.ori is not None: msg = 'surface integrals do not work yet with the' \ ' hierarchical basis!' raise ValueError(msg) sd = domain.surface_groups[region.name] esd = self.surface_data[region.name] geo_ps = self.gel.poly_space ps = self.poly_space conn = sd.get_connectivity() mapping = SurfaceMapping(coors, conn, poly_space=geo_ps) if not self.is_surface: self.create_bqp(region.name, integral) qp = self.qp_coors[(integral.order, esd.bkey)] abf = ps.eval_base(qp.vals[0], transform=self.basis_transform) bf = abf[..., self.efaces[0]] indx = self.gel.get_surface_entities()[0] # Fix geometry element's 1st facet orientation for gradients. indx = nm.roll(indx, -1)[::-1] mapping.set_basis_indices(indx) sg = mapping.get_mapping(qp.vals[0], qp.weights, poly_space=Struct(n_nod=bf.shape[-1]), mode=integration) if integration == 'surface_extra': sg.alloc_extra_data(self.econn.shape[1]) bf_bg = geo_ps.eval_base(qp.vals, diff=True) ebf_bg = self.get_base(esd.bkey, 1, integral) sg.evaluate_bfbgm(bf_bg, ebf_bg, coors, sd.fis, dconn) else: # Do not use BQP for surface fields. qp = self.get_qp(sd.face_type, integral) bf = ps.eval_base(qp.vals, transform=self.basis_transform) sg = mapping.get_mapping(qp.vals, qp.weights, poly_space=Struct(n_nod=bf.shape[-1]), mode=integration) out = sg elif integration == 'point': out = mapping = None elif integration == 'custom': raise ValueError('cannot create custom mapping!') else: raise ValueError('unknown 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 class VolumeField(FEField): """ Finite element field base class over volume elements (element dimension equals space dimension). """ def _check_region(self, region): """ Check whether the `region` can be used for the field. Returns ------- ok : bool True if the region is usable for the field. """ ok = True domain = region.domain if region.kind != 'cell': output("bad region kind! (is: %r, should be: 'cell')" % region.kind) ok = False elif (region.kind_tdim != domain.shape.tdim): output('cells with a bad topological dimension! (%d == %d)' % (region.kind_tdim, domain.shape.tdim)) ok = False return ok def _setup_geometry(self): """ Setup the field region geometry. """ cmesh = self.domain.cmesh for key, gel in six.iteritems(self.domain.geom_els): ct = cmesh.cell_types if (ct[self.region.cells] == cmesh.key_to_index[gel.name]).all(): self.gel = gel break else: raise ValueError('region %s of field %s contains multiple' ' reference geometries!' % (self.region.name, self.name)) self.is_surface = False def _create_interpolant(self): name = '%s_%s_%s_%d%s' % (self.gel.name, self.space, self.poly_space_base, self.approx_order, 'B' * self.force_bubble) ps = PolySpace.any_from_args(name, self.gel, self.approx_order, base=self.poly_space_base, force_bubble=self.force_bubble) self.poly_space = ps def _init_econn(self): """ Initialize the extended DOF connectivity. """ n_ep = self.poly_space.n_nod n_cell = self.region.get_n_cells() self.econn = nm.zeros((n_cell, n_ep), nm.int32) def _setup_vertex_dofs(self): """ Setup vertex DOF connectivity. """ if self.node_desc.vertex is None: return 0, None region = self.region cmesh = self.domain.cmesh conn, offsets = cmesh.get_incident(0, region.cells, region.tdim, ret_offsets=True) vertices = nm.unique(conn) remap = prepare_remap(vertices, region.n_v_max) n_dof = vertices.shape[0] aux = nm.unique(nm.diff(offsets)) assert_(len(aux) == 1, 'region with multiple reference geometries!') offset = aux[0] # Remap vertex node connectivity to field-local numbering. aux = conn.reshape((-1, offset)).astype(nm.int32) self.econn[:, :offset] = nm.take(remap, aux) return n_dof, remap def setup_extra_data(self, geometry, info, is_trace): dct = info.dc_type.type if geometry != None: geometry_flag = 'surface' in geometry else: geometry_flag = False if (dct == 'surface') or (geometry_flag): reg = info.get_region() mreg_name = info.get_region_name(can_trace=False) self.domain.create_surface_group(reg) self.setup_surface_data(reg, is_trace, mreg_name) elif dct == 'edge': raise NotImplementedError('dof connectivity type %s' % dct) elif dct == 'point': self.setup_point_data(self, info.region) elif dct not in ('volume', 'scalar', 'custom'): raise ValueError('unknown dof connectivity type! (%s)' % dct) def setup_point_data(self, field, region): if region.name not in self.point_data: conn = field.get_dofs_in_region(region, merge=True) conn.shape += (1,) self.point_data[region.name] = conn def setup_surface_data(self, region, is_trace=False, trace_region=None): """nodes[leconn] == econn""" """nodes are sorted by node number -> same order as region.vertices""" if region.name not in self.surface_data: sd = FESurface('surface_data_%s' % region.name, region, self.efaces, self.econn, self.region) self.surface_data[region.name] = sd if region.name in self.surface_data and is_trace: sd = self.surface_data[region.name] sd.setup_mirror_connectivity(region, trace_region) return self.surface_data[region.name] def get_econn(self, conn_type, region, is_trace=False, integration=None): """ Get extended connectivity of the given type in the given region. """ ct = conn_type.type if isinstance(conn_type, Struct) else conn_type if ct in ('volume', 'custom'): if region.name == self.region.name: conn = self.econn else: tco = integration in ('volume', 'custom') cells = region.get_cells(true_cells_only=tco) ii = self.region.get_cell_indices(cells, true_cells_only=tco) conn = nm.take(self.econn, ii, axis=0) elif ct == 'surface': sd = self.surface_data[region.name] conn = sd.get_connectivity(is_trace=is_trace) elif ct == 'edge': raise NotImplementedError('connectivity type %s' % ct) elif ct == 'point': conn = self.point_data[region.name] else: raise ValueError('unknown connectivity type! (%s)' % ct) return conn def average_qp_to_vertices(self, data_qp, integral): """ Average data given in quadrature points in region elements into region vertices. .. math:: u_n = \sum_e (u_{e,avg} * volume_e) / \sum_e volume_e = \sum_e \int_{volume_e} u / \sum volume_e """ region = self.region n_cells = region.get_n_cells() if n_cells != data_qp.shape[0]: msg = 'incomatible shape! (%d == %d)' % (n_cells, data_qp.shape[0]) raise ValueError(msg) n_vertex = self.n_vertex_dof nc = data_qp.shape[2] nod_vol = nm.zeros((n_vertex,), dtype=nm.float64) data_vertex = nm.zeros((n_vertex, nc), dtype=nm.float64) vg = self.get_mapping(self.region, integral, 'volume')[0] volume = nm.squeeze(vg.volume) iels = self.region.get_cells() data_e = nm.zeros((volume.shape[0], 1, nc, 1), dtype=nm.float64) vg.integrate(data_e, data_qp[iels]) ir = nm.arange(nc, dtype=nm.int32) conn = self.econn[:, :self.gel.n_vertex] for ii, cc in enumerate(conn): # Assumes unique nodes in cc! ind2, ind1 = nm.meshgrid(ir, cc) data_vertex[ind1,ind2] += data_e[iels[ii],0,:,0] nod_vol[cc] += volume[ii] data_vertex /= nod_vol[:,nm.newaxis] return data_vertex class SurfaceField(FEField): """ Finite element field base class over surface (element dimension is one less than space dimension). """ def _check_region(self, region): """ Check whether the `region` can be used for the field. Returns ------- ok : bool True if the region is usable for the field. """ ok1 = ((region.kind_tdim == (region.tdim - 1)) and (region.get_n_cells(True) > 0)) if not ok1: output('bad region topological dimension and kind! (%d, %s)' % (region.tdim, region.kind)) n_ns = region.get_facet_indices().shape[0] - region.get_n_cells(True) ok2 = n_ns == 0 if not ok2:
output('%d region facets are not on the domain surface!' % n_ns)
sfepy.base.base.output
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value =
get_min_value(dofs)
sfepy.discrete.fem.utils.get_min_value
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value =
get_min_value(dofs.real)
sfepy.discrete.fem.utils.get_min_value
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization, Struct(kind='strip')) out = {} if linearization.kind is None: out[key] = Struct(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=dof_names, field_name=self.name) elif linearization.kind == 'strip': if extend: ext = self.extend_dofs(dofs, fill_value) else: ext = self.remove_extra_dofs(dofs) if ext is not None: approx_order = self.get_output_approx_order() if approx_order != 0: # Has vertex data. out[key] = Struct(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs=dof_names) else: ext.shape = (ext.shape[0], 1, ext.shape[1], 1) out[key] = Struct(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=dof_names) else: mesh, vdofs, levels = self.linearize(dofs, linearization.min_level, linearization.max_level, linearization.eps) out[key] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=var_name, dofs=dof_names, mesh=mesh, levels=levels) out = convert_complex_output(out) return out def create_mesh(self, extra_nodes=True): """ Create a mesh from the field region, optionally including the field extra nodes. """ mesh = self.domain.mesh if self.approx_order != 0: if extra_nodes: conn = self.econn else: conn = self.econn[:, :self.gel.n_vertex] conns = [conn] mat_ids = [mesh.cmesh.cell_groups] descs = mesh.descs[:1] if extra_nodes: coors = self.coors else: coors = self.coors[:self.n_vertex_dof] mesh = Mesh.from_data(self.name, coors, None, conns, mat_ids, descs) return mesh def get_evaluate_cache(self, cache=None, share_geometry=False, verbose=False): """ Get the evaluate cache for :func:`Variable.evaluate_at() <sfepy.discrete.variables.Variable.evaluate_at()>`. Parameters ---------- cache : Struct instance, optional Optionally, use the provided instance to store the cache data. share_geometry : bool Set to True to indicate that all the evaluations will work on the same region. Certain data are then computed only for the first probe and cached. verbose : bool If False, reduce verbosity. Returns ------- cache : Struct instance The evaluate cache. """ import time try: from scipy.spatial import cKDTree as KDTree except ImportError: from scipy.spatial import KDTree from sfepy.discrete.fem.geometry_element import create_geometry_elements if cache is None: cache = Struct(name='evaluate_cache') tt = time.clock() if (cache.get('cmesh', None) is None) or not share_geometry: mesh = self.create_mesh(extra_nodes=False) cache.cmesh = cmesh = mesh.cmesh gels = create_geometry_elements() cmesh.set_local_entities(gels) cmesh.setup_entities() cache.centroids = cmesh.get_centroids(cmesh.tdim) if self.gel.name != '3_8': cache.normals0 = cmesh.get_facet_normals() cache.normals1 = None else: cache.normals0 = cmesh.get_facet_normals(0) cache.normals1 = cmesh.get_facet_normals(1) output('cmesh setup: %f s' % (time.clock()-tt), verbose=verbose) tt = time.clock() if (cache.get('kdtree', None) is None) or not share_geometry: cache.kdtree = KDTree(cmesh.coors) output('kdtree: %f s' % (time.clock()-tt), verbose=verbose) return cache def interp_to_qp(self, dofs): """ Interpolate DOFs into quadrature points. The quadrature order is given by the field approximation order. Parameters ---------- dofs : array The array of DOF values of shape `(n_nod, n_component)`. Returns ------- data_qp : array The values interpolated into the quadrature points. integral : Integral The corresponding integral defining the quadrature points. """ integral = Integral('i', order=self.approx_order) bf = self.get_base('v', False, integral) bf = bf[:,0,:].copy() data_qp = nm.dot(bf, dofs[self.econn]) data_qp = nm.swapaxes(data_qp, 0, 1) data_qp.shape = data_qp.shape + (1,) return data_qp, integral def get_coor(self, nods=None): """ Get coordinates of the field nodes. Parameters ---------- nods : array, optional The indices of the required nodes. If not given, the coordinates of all the nodes are returned. """ if nods is None: return self.coors else: return self.coors[nods] def get_connectivity(self, region, integration, is_trace=False): """ Convenience alias to `Field.get_econn()`, that is used in some terms. """ return self.get_econn(integration, region, is_trace=is_trace) def create_mapping(self, region, integral, integration, return_mapping=True): """ Create a new reference mapping. Compute jacobians, element volumes and base function derivatives for Volume-type geometries (volume mappings), and jacobians, normals and base function derivatives for Surface-type geometries (surface mappings). Notes ----- - surface mappings are defined on the surface region - surface mappings require field order to be > 0 """ domain = self.domain coors = domain.get_mesh_coors(actual=True) dconn = domain.get_conn() if integration == 'volume': qp = self.get_qp('v', integral) 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 elif (integration == 'surface') or (integration == 'surface_extra'):
assert_(self.approx_order > 0)
sfepy.base.base.assert_
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization, Struct(kind='strip')) out = {} if linearization.kind is None: out[key] = Struct(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=dof_names, field_name=self.name) elif linearization.kind == 'strip': if extend: ext = self.extend_dofs(dofs, fill_value) else: ext = self.remove_extra_dofs(dofs) if ext is not None: approx_order = self.get_output_approx_order() if approx_order != 0: # Has vertex data. out[key] = Struct(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs=dof_names) else: ext.shape = (ext.shape[0], 1, ext.shape[1], 1) out[key] = Struct(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=dof_names) else: mesh, vdofs, levels = self.linearize(dofs, linearization.min_level, linearization.max_level, linearization.eps) out[key] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=var_name, dofs=dof_names, mesh=mesh, levels=levels) out = convert_complex_output(out) return out def create_mesh(self, extra_nodes=True): """ Create a mesh from the field region, optionally including the field extra nodes. """ mesh = self.domain.mesh if self.approx_order != 0: if extra_nodes: conn = self.econn else: conn = self.econn[:, :self.gel.n_vertex] conns = [conn] mat_ids = [mesh.cmesh.cell_groups] descs = mesh.descs[:1] if extra_nodes: coors = self.coors else: coors = self.coors[:self.n_vertex_dof] mesh = Mesh.from_data(self.name, coors, None, conns, mat_ids, descs) return mesh def get_evaluate_cache(self, cache=None, share_geometry=False, verbose=False): """ Get the evaluate cache for :func:`Variable.evaluate_at() <sfepy.discrete.variables.Variable.evaluate_at()>`. Parameters ---------- cache : Struct instance, optional Optionally, use the provided instance to store the cache data. share_geometry : bool Set to True to indicate that all the evaluations will work on the same region. Certain data are then computed only for the first probe and cached. verbose : bool If False, reduce verbosity. Returns ------- cache : Struct instance The evaluate cache. """ import time try: from scipy.spatial import cKDTree as KDTree except ImportError: from scipy.spatial import KDTree from sfepy.discrete.fem.geometry_element import create_geometry_elements if cache is None: cache = Struct(name='evaluate_cache') tt = time.clock() if (cache.get('cmesh', None) is None) or not share_geometry: mesh = self.create_mesh(extra_nodes=False) cache.cmesh = cmesh = mesh.cmesh gels = create_geometry_elements() cmesh.set_local_entities(gels) cmesh.setup_entities() cache.centroids = cmesh.get_centroids(cmesh.tdim) if self.gel.name != '3_8': cache.normals0 = cmesh.get_facet_normals() cache.normals1 = None else: cache.normals0 = cmesh.get_facet_normals(0) cache.normals1 = cmesh.get_facet_normals(1) output('cmesh setup: %f s' % (time.clock()-tt), verbose=verbose) tt = time.clock() if (cache.get('kdtree', None) is None) or not share_geometry: cache.kdtree = KDTree(cmesh.coors) output('kdtree: %f s' % (time.clock()-tt), verbose=verbose) return cache def interp_to_qp(self, dofs): """ Interpolate DOFs into quadrature points. The quadrature order is given by the field approximation order. Parameters ---------- dofs : array The array of DOF values of shape `(n_nod, n_component)`. Returns ------- data_qp : array The values interpolated into the quadrature points. integral : Integral The corresponding integral defining the quadrature points. """ integral = Integral('i', order=self.approx_order) bf = self.get_base('v', False, integral) bf = bf[:,0,:].copy() data_qp = nm.dot(bf, dofs[self.econn]) data_qp = nm.swapaxes(data_qp, 0, 1) data_qp.shape = data_qp.shape + (1,) return data_qp, integral def get_coor(self, nods=None): """ Get coordinates of the field nodes. Parameters ---------- nods : array, optional The indices of the required nodes. If not given, the coordinates of all the nodes are returned. """ if nods is None: return self.coors else: return self.coors[nods] def get_connectivity(self, region, integration, is_trace=False): """ Convenience alias to `Field.get_econn()`, that is used in some terms. """ return self.get_econn(integration, region, is_trace=is_trace) def create_mapping(self, region, integral, integration, return_mapping=True): """ Create a new reference mapping. Compute jacobians, element volumes and base function derivatives for Volume-type geometries (volume mappings), and jacobians, normals and base function derivatives for Surface-type geometries (surface mappings). Notes ----- - surface mappings are defined on the surface region - surface mappings require field order to be > 0 """ domain = self.domain coors = domain.get_mesh_coors(actual=True) dconn = domain.get_conn() if integration == 'volume': qp = self.get_qp('v', integral) 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 elif (integration == 'surface') or (integration == 'surface_extra'): assert_(self.approx_order > 0) if self.ori is not None: msg = 'surface integrals do not work yet with the' \ ' hierarchical basis!' raise ValueError(msg) sd = domain.surface_groups[region.name] esd = self.surface_data[region.name] geo_ps = self.gel.poly_space ps = self.poly_space conn = sd.get_connectivity() mapping =
SurfaceMapping(coors, conn, poly_space=geo_ps)
sfepy.discrete.fem.mappings.SurfaceMapping
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j *
get_min_value(dofs.imag)
sfepy.discrete.fem.utils.get_min_value
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization, Struct(kind='strip')) out = {} if linearization.kind is None: out[key] = Struct(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=dof_names, field_name=self.name) elif linearization.kind == 'strip': if extend: ext = self.extend_dofs(dofs, fill_value) else: ext = self.remove_extra_dofs(dofs) if ext is not None: approx_order = self.get_output_approx_order() if approx_order != 0: # Has vertex data. out[key] = Struct(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs=dof_names) else: ext.shape = (ext.shape[0], 1, ext.shape[1], 1) out[key] = Struct(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=dof_names) else: mesh, vdofs, levels = self.linearize(dofs, linearization.min_level, linearization.max_level, linearization.eps) out[key] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=var_name, dofs=dof_names, mesh=mesh, levels=levels) out = convert_complex_output(out) return out def create_mesh(self, extra_nodes=True): """ Create a mesh from the field region, optionally including the field extra nodes. """ mesh = self.domain.mesh if self.approx_order != 0: if extra_nodes: conn = self.econn else: conn = self.econn[:, :self.gel.n_vertex] conns = [conn] mat_ids = [mesh.cmesh.cell_groups] descs = mesh.descs[:1] if extra_nodes: coors = self.coors else: coors = self.coors[:self.n_vertex_dof] mesh = Mesh.from_data(self.name, coors, None, conns, mat_ids, descs) return mesh def get_evaluate_cache(self, cache=None, share_geometry=False, verbose=False): """ Get the evaluate cache for :func:`Variable.evaluate_at() <sfepy.discrete.variables.Variable.evaluate_at()>`. Parameters ---------- cache : Struct instance, optional Optionally, use the provided instance to store the cache data. share_geometry : bool Set to True to indicate that all the evaluations will work on the same region. Certain data are then computed only for the first probe and cached. verbose : bool If False, reduce verbosity. Returns ------- cache : Struct instance The evaluate cache. """ import time try: from scipy.spatial import cKDTree as KDTree except ImportError: from scipy.spatial import KDTree from sfepy.discrete.fem.geometry_element import create_geometry_elements if cache is None: cache = Struct(name='evaluate_cache') tt = time.clock() if (cache.get('cmesh', None) is None) or not share_geometry: mesh = self.create_mesh(extra_nodes=False) cache.cmesh = cmesh = mesh.cmesh gels = create_geometry_elements() cmesh.set_local_entities(gels) cmesh.setup_entities() cache.centroids = cmesh.get_centroids(cmesh.tdim) if self.gel.name != '3_8': cache.normals0 = cmesh.get_facet_normals() cache.normals1 = None else: cache.normals0 = cmesh.get_facet_normals(0) cache.normals1 = cmesh.get_facet_normals(1) output('cmesh setup: %f s' % (time.clock()-tt), verbose=verbose) tt = time.clock() if (cache.get('kdtree', None) is None) or not share_geometry: cache.kdtree = KDTree(cmesh.coors) output('kdtree: %f s' % (time.clock()-tt), verbose=verbose) return cache def interp_to_qp(self, dofs): """ Interpolate DOFs into quadrature points. The quadrature order is given by the field approximation order. Parameters ---------- dofs : array The array of DOF values of shape `(n_nod, n_component)`. Returns ------- data_qp : array The values interpolated into the quadrature points. integral : Integral The corresponding integral defining the quadrature points. """ integral = Integral('i', order=self.approx_order) bf = self.get_base('v', False, integral) bf = bf[:,0,:].copy() data_qp = nm.dot(bf, dofs[self.econn]) data_qp = nm.swapaxes(data_qp, 0, 1) data_qp.shape = data_qp.shape + (1,) return data_qp, integral def get_coor(self, nods=None): """ Get coordinates of the field nodes. Parameters ---------- nods : array, optional The indices of the required nodes. If not given, the coordinates of all the nodes are returned. """ if nods is None: return self.coors else: return self.coors[nods] def get_connectivity(self, region, integration, is_trace=False): """ Convenience alias to `Field.get_econn()`, that is used in some terms. """ return self.get_econn(integration, region, is_trace=is_trace) def create_mapping(self, region, integral, integration, return_mapping=True): """ Create a new reference mapping. Compute jacobians, element volumes and base function derivatives for Volume-type geometries (volume mappings), and jacobians, normals and base function derivatives for Surface-type geometries (surface mappings). Notes ----- - surface mappings are defined on the surface region - surface mappings require field order to be > 0 """ domain = self.domain coors = domain.get_mesh_coors(actual=True) dconn = domain.get_conn() if integration == 'volume': qp = self.get_qp('v', integral) 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 elif (integration == 'surface') or (integration == 'surface_extra'): assert_(self.approx_order > 0) if self.ori is not None: msg = 'surface integrals do not work yet with the' \ ' hierarchical basis!' raise ValueError(msg) sd = domain.surface_groups[region.name] esd = self.surface_data[region.name] geo_ps = self.gel.poly_space ps = self.poly_space conn = sd.get_connectivity() mapping = SurfaceMapping(coors, conn, poly_space=geo_ps) if not self.is_surface: self.create_bqp(region.name, integral) qp = self.qp_coors[(integral.order, esd.bkey)] abf = ps.eval_base(qp.vals[0], transform=self.basis_transform) bf = abf[..., self.efaces[0]] indx = self.gel.get_surface_entities()[0] # Fix geometry element's 1st facet orientation for gradients. indx = nm.roll(indx, -1)[::-1] mapping.set_basis_indices(indx) sg = mapping.get_mapping(qp.vals[0], qp.weights, poly_space=
Struct(n_nod=bf.shape[-1])
sfepy.base.base.Struct
""" Notes ----- Important attributes of continuous (order > 0) :class:`Field` and :class:`SurfaceField` instances: - `vertex_remap` : `econn[:, :n_vertex] = vertex_remap[conn]` - `vertex_remap_i` : `conn = vertex_remap_i[econn[:, :n_vertex]]` where `conn` is the mesh vertex connectivity, `econn` is the region-local field connectivity. """ from __future__ import absolute_import import numpy as nm from sfepy.base.base import output, get_default, assert_ from sfepy.base.base import Struct from sfepy.discrete.common.fields import parse_shape, Field from sfepy.discrete.fem.mesh import Mesh from sfepy.discrete.fem.meshio import convert_complex_output from sfepy.discrete.fem.utils import (extend_cell_data, prepare_remap, invert_remap, get_min_value) from sfepy.discrete.fem.mappings import VolumeMapping, SurfaceMapping from sfepy.discrete.fem.poly_spaces import PolySpace from sfepy.discrete.fem.fe_surface import FESurface from sfepy.discrete.integrals import Integral from sfepy.discrete.fem.linearizer import (get_eval_dofs, get_eval_coors, create_output) import six def set_mesh_coors(domain, fields, coors, update_fields=False, actual=False, clear_all=True, extra_dofs=False): if actual: if not hasattr(domain.mesh, 'coors_act'): domain.mesh.coors_act = nm.zeros_like(domain.mesh.coors) domain.mesh.coors_act[:] = coors[:domain.mesh.n_nod] else: domain.cmesh.coors[:] = coors[:domain.mesh.n_nod] if update_fields: for field in six.itervalues(fields): field.set_coors(coors, extra_dofs=extra_dofs) field.clear_mappings(clear_all=clear_all) def eval_nodal_coors(coors, mesh_coors, region, poly_space, geom_poly_space, econn, only_extra=True): """ Compute coordinates of nodes corresponding to `poly_space`, given mesh coordinates and `geom_poly_space`. """ if only_extra: iex = (poly_space.nts[:,0] > 0).nonzero()[0] if iex.shape[0] == 0: return qp_coors = poly_space.node_coors[iex, :] econn = econn[:, iex].copy() else: qp_coors = poly_space.node_coors ## # Evaluate geometry interpolation base functions in (extra) nodes. bf = geom_poly_space.eval_base(qp_coors) bf = bf[:,0,:].copy() ## # Evaluate extra coordinates with 'bf'. cmesh = region.domain.cmesh conn = cmesh.get_incident(0, region.cells, region.tdim) conn.shape = (econn.shape[0], -1) ecoors = nm.dot(bf, mesh_coors[conn]) coors[econn] = nm.swapaxes(ecoors, 0, 1) def _interp_to_faces(vertex_vals, bfs, faces): dim = vertex_vals.shape[1] n_face = faces.shape[0] n_qp = bfs.shape[0] faces_vals = nm.zeros((n_face, n_qp, dim), nm.float64) for ii, face in enumerate(faces): vals = vertex_vals[face,:dim] faces_vals[ii,:,:] = nm.dot(bfs[:,0,:], vals) return(faces_vals) def get_eval_expression(expression, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Get the function for evaluating an expression given a list of elements, and reference element coordinates. """ from sfepy.discrete.evaluate import eval_in_els_and_qp def _eval(iels, coors): val = eval_in_els_and_qp(expression, iels, coors, fields, materials, variables, functions=functions, mode=mode, term_mode=term_mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) return val[..., 0] return _eval def create_expression_output(expression, name, primary_field_name, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None, min_level=0, max_level=1, eps=1e-4): """ Create output mesh and data for the expression using the adaptive linearizer. Parameters ---------- expression : str The expression to evaluate. name : str The name of the data. primary_field_name : str The name of field that defines the element groups and polynomial spaces. fields : dict The dictionary of fields used in `variables`. materials : Materials instance The materials used in the expression. variables : Variables instance The variables used in the expression. functions : Functions instance, optional The user functions for materials etc. mode : one of 'eval', 'el_avg', 'qp' The evaluation mode - 'qp' requests the values in quadrature points, 'el_avg' element averages and 'eval' means integration over each term region. term_mode : str The term call mode - some terms support different call modes and depending on the call mode different values are returned. extra_args : dict, optional Extra arguments to be passed to terms in the expression. verbose : bool If False, reduce verbosity. kwargs : dict, optional The variables (dictionary of (variable name) : (Variable instance)) to be used in the expression. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- out : dict The output dictionary. """ field = fields[primary_field_name] vertex_coors = field.coors[:field.n_vertex_dof, :] ps = field.poly_space gps = field.gel.poly_space vertex_conn = field.econn[:, :field.gel.n_vertex] eval_dofs = get_eval_expression(expression, fields, materials, variables, functions=functions, mode=mode, extra_args=extra_args, verbose=verbose, kwargs=kwargs) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], field.domain.mesh.descs) out = {} out[name] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=name, dofs=None, mesh=mesh, level=level) out = convert_complex_output(out) return out class FEField(Field): """ Base class for finite element fields. Notes ----- - interps and hence node_descs are per region (must have single geometry!) Field shape information: - ``shape`` - the shape of the base functions in a point - ``n_components`` - the number of DOFs per FE node - ``val_shape`` - the shape of field value (the product of DOFs and base functions) in a point """ def __init__(self, name, dtype, shape, region, approx_order=1): """ Create a finite element field. Parameters ---------- name : str The field name. dtype : numpy.dtype The field data type: float64 or complex128. shape : int/tuple/str The field shape: 1 or (1,) or 'scalar', space dimension (2, or (2,) or 3 or (3,)) or 'vector', or a tuple. The field shape determines the shape of the FE base functions and is related to the number of components of variables and to the DOF per node count, depending on the field kind. region : Region The region where the field is defined. approx_order : int or tuple The FE approximation order. The tuple form is (order, has_bubble), e.g. (1, True) means order 1 with a bubble function. Notes ----- Assumes one cell type for the whole region! """ shape = parse_shape(shape, region.domain.shape.dim) if not self._check_region(region): raise ValueError('unsuitable region for field %s! (%s)' % (name, region.name)) Struct.__init__(self, name=name, dtype=dtype, shape=shape, region=region) self.domain = self.region.domain self._set_approx_order(approx_order) self._setup_geometry() self._setup_kind() self._setup_shape() self.surface_data = {} self.point_data = {} self.ori = None self._create_interpolant() self._setup_global_base() self.setup_coors() self.clear_mappings(clear_all=True) self.clear_qp_base() self.basis_transform = None self.econn0 = None self.unused_dofs = None self.stored_subs = None def _set_approx_order(self, approx_order): """ Set a uniform approximation order. """ if isinstance(approx_order, tuple): self.approx_order = approx_order[0] self.force_bubble = approx_order[1] else: self.approx_order = approx_order self.force_bubble = False def get_true_order(self): """ Get the true approximation order depending on the reference element geometry. For example, for P1 (linear) approximation the true order is 1, while for Q1 (bilinear) approximation in 2D the true order is 2. """ gel = self.gel if (gel.dim + 1) == gel.n_vertex: order = self.approx_order else: order = gel.dim * self.approx_order if self.force_bubble: bubble_order = gel.dim + 1 order = max(order, bubble_order) return order def is_higher_order(self): """ Return True, if the field's approximation order is greater than one. """ return self.force_bubble or (self.approx_order > 1) def _setup_global_base(self): """ Setup global DOF/base functions, their indices and connectivity of the field. Called methods implemented in subclasses. """ self._setup_facet_orientations() self._init_econn() self.n_vertex_dof, self.vertex_remap = self._setup_vertex_dofs() self.vertex_remap_i = invert_remap(self.vertex_remap) aux = self._setup_edge_dofs() self.n_edge_dof, self.edge_dofs, self.edge_remap = aux aux = self._setup_face_dofs() self.n_face_dof, self.face_dofs, self.face_remap = aux aux = self._setup_bubble_dofs() self.n_bubble_dof, self.bubble_dofs, self.bubble_remap = aux self.n_nod = self.n_vertex_dof + self.n_edge_dof \ + self.n_face_dof + self.n_bubble_dof self._setup_esurface() def _setup_esurface(self): """ Setup extended surface entities (edges in 2D, faces in 3D), i.e. indices of surface entities into the extended connectivity. """ node_desc = self.node_desc gel = self.gel self.efaces = gel.get_surface_entities().copy() nd = node_desc.edge if nd is not None: efs = [] for eof in gel.get_edges_per_face(): efs.append(nm.concatenate([nd[ie] for ie in eof])) efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) efs = node_desc.face if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.efaces = nm.hstack((self.efaces, efs)) if gel.dim == 3: self.eedges = gel.edges.copy() efs = node_desc.edge if efs is not None: efs = nm.array(efs).squeeze() if efs.ndim < 2: efs = efs[:,nm.newaxis] self.eedges = nm.hstack((self.eedges, efs)) def set_coors(self, coors, extra_dofs=False): """ Set coordinates of field nodes. """ # Mesh vertex nodes. if self.n_vertex_dof: indx = self.vertex_remap_i self.coors[:self.n_vertex_dof] = nm.take(coors, indx.astype(nm.int32), axis=0) n_ex_dof = self.n_bubble_dof + self.n_edge_dof + self.n_face_dof # extra nodes if n_ex_dof: if extra_dofs: if self.n_nod != coors.shape[0]: raise NotImplementedError self.coors[:] = coors else: gps = self.gel.poly_space ps = self.poly_space eval_nodal_coors(self.coors, coors, self.region, ps, gps, self.econn) def setup_coors(self): """ Setup coordinates of field nodes. """ mesh = self.domain.mesh self.coors = nm.empty((self.n_nod, mesh.dim), nm.float64) self.set_coors(mesh.coors) def get_vertices(self): """ Return indices of vertices belonging to the field region. """ return self.vertex_remap_i def _get_facet_dofs(self, rfacets, remap, dofs): facets = remap[rfacets] return dofs[facets[facets >= 0]].ravel() def get_data_shape(self, integral, integration='volume', region_name=None): """ Get element data dimensions. Parameters ---------- integral : Integral instance The integral describing used numerical quadrature. integration : 'volume', 'surface', 'surface_extra', 'point' or 'custom' The term integration type. region_name : str The name of the region of the integral. Returns ------- data_shape : 4 ints The `(n_el, n_qp, dim, n_en)` for volume shape kind, `(n_fa, n_qp, dim, n_fn)` for surface shape kind and `(n_nod, 0, 0, 1)` for point shape kind. Notes ----- - `n_el`, `n_fa` = number of elements/facets - `n_qp` = number of quadrature points per element/facet - `dim` = spatial dimension - `n_en`, `n_fn` = number of element/facet nodes - `n_nod` = number of element nodes """ region = self.domain.regions[region_name] shape = region.shape dim = region.dim if integration in ('surface', 'surface_extra'): sd = self.surface_data[region_name] # This works also for surface fields. key = sd.face_type weights = self.get_qp(key, integral).weights n_qp = weights.shape[0] if integration == 'surface': data_shape = (sd.n_fa, n_qp, dim, sd.n_fp) else: data_shape = (sd.n_fa, n_qp, dim, self.econn.shape[1]) elif integration in ('volume', 'custom'): _, weights = integral.get_qp(self.gel.name) n_qp = weights.shape[0] data_shape = (shape.n_cell, n_qp, dim, self.econn.shape[1]) elif integration == 'point': dofs = self.get_dofs_in_region(region, merge=True) data_shape = (dofs.shape[0], 0, 0, 1) else: raise NotImplementedError('unsupported integration! (%s)' % integration) return data_shape def get_dofs_in_region(self, region, merge=True): """ Return indices of DOFs that belong to the given region and group. """ node_desc = self.node_desc dofs = [] vdofs = nm.empty((0,), dtype=nm.int32) if node_desc.vertex is not None: vdofs = self.vertex_remap[region.vertices] vdofs = vdofs[vdofs >= 0] dofs.append(vdofs) edofs = nm.empty((0,), dtype=nm.int32) if node_desc.edge is not None: edofs = self._get_facet_dofs(region.edges, self.edge_remap, self.edge_dofs) dofs.append(edofs) fdofs = nm.empty((0,), dtype=nm.int32) if node_desc.face is not None: fdofs = self._get_facet_dofs(region.faces, self.face_remap, self.face_dofs) dofs.append(fdofs) bdofs = nm.empty((0,), dtype=nm.int32) if (node_desc.bubble is not None) and region.has_cells(): els = self.bubble_remap[region.cells] bdofs = self.bubble_dofs[els[els >= 0]].ravel() dofs.append(bdofs) if merge: dofs = nm.concatenate(dofs) return dofs def clear_qp_base(self): """ Remove cached quadrature points and base functions. """ self.qp_coors = {} self.bf = {} def get_qp(self, key, integral): """ Get quadrature points and weights corresponding to the given key and integral. The key is 'v' or 's#', where # is the number of face vertices. """ qpkey = (integral.order, key) if qpkey not in self.qp_coors: if (key[0] == 's') and not self.is_surface: dim = self.gel.dim - 1 n_fp = self.gel.surface_facet.n_vertex geometry = '%d_%d' % (dim, n_fp) else: geometry = self.gel.name vals, weights = integral.get_qp(geometry) self.qp_coors[qpkey] = Struct(vals=vals, weights=weights) return self.qp_coors[qpkey] def substitute_dofs(self, subs, restore=False): """ Perform facet DOF substitutions according to `subs`. Modifies `self.econn` in-place and sets `self.econn0`, `self.unused_dofs` and `self.basis_transform`. """ if restore and (self.stored_subs is not None): self.econn0 = self.econn self.econn, self.unused_dofs, basis_transform = self.stored_subs else: if subs is None: self.econn0 = self.econn return else: self.econn0 = self.econn.copy() self._substitute_dofs(subs) self.unused_dofs = nm.setdiff1d(self.econn0, self.econn) basis_transform = self._eval_basis_transform(subs) self.set_basis_transform(basis_transform) def restore_dofs(self, store=False): """ Undoes the effect of :func:`FEField.substitute_dofs()`. """ if self.econn0 is None: raise ValueError('no original DOFs to restore!') if store: self.stored_subs = (self.econn, self.unused_dofs, self.basis_transform) else: self.stored_subs = None self.econn = self.econn0 self.econn0 = None self.unused_dofs = None self.basis_transform = None def set_basis_transform(self, transform): """ Set local element basis transformation. The basis transformation is applied in :func:`FEField.get_base()` and :func:`FEField.create_mapping()`. Parameters ---------- transform : array, shape `(n_cell, n_ep, n_ep)` The array with `(n_ep, n_ep)` transformation matrices for each cell in the field's region, where `n_ep` is the number of element DOFs. """ self.basis_transform = transform def restore_substituted(self, vec): """ Restore values of the unused DOFs using the transpose of the applied basis transformation. """ if (self.econn0 is None) or (self.basis_transform is None): raise ValueError('no original DOF values to restore!!') vec = vec.reshape((self.n_nod, self.n_components)).copy() evec = vec[self.econn] vec[self.econn0] = nm.einsum('cji,cjk->cik', self.basis_transform, evec) return vec.ravel() def get_base(self, key, derivative, integral, iels=None, from_geometry=False, base_only=True): qp = self.get_qp(key, integral) if from_geometry: ps = self.gel.poly_space else: ps = self.poly_space _key = key if not from_geometry else 'g' + key bf_key = (integral.order, _key, derivative) if bf_key not in self.bf: if (iels is not None) and (self.ori is not None): ori = self.ori[iels] else: ori = self.ori self.bf[bf_key] = ps.eval_base(qp.vals, diff=derivative, ori=ori, transform=self.basis_transform) if base_only: return self.bf[bf_key] else: return self.bf[bf_key], qp.weights def create_bqp(self, region_name, integral): gel = self.gel sd = self.surface_data[region_name] bqpkey = (integral.order, sd.bkey) if not bqpkey in self.qp_coors: qp = self.get_qp(sd.face_type, integral) ps_s = self.gel.surface_facet.poly_space bf_s = ps_s.eval_base(qp.vals) coors, faces = gel.coors, gel.get_surface_entities() vals = _interp_to_faces(coors, bf_s, faces) self.qp_coors[bqpkey] = Struct(name='BQP_%s' % sd.bkey, vals=vals, weights=qp.weights) def extend_dofs(self, dofs, fill_value=None): """ Extend DOFs to the whole domain using the `fill_value`, or the smallest value in `dofs` if `fill_value` is None. """ if fill_value is None: if nm.isrealobj(dofs): fill_value = get_min_value(dofs) else: # Complex values - treat real and imaginary parts separately. fill_value = get_min_value(dofs.real) fill_value += 1j * get_min_value(dofs.imag) if self.approx_order != 0: indx = self.get_vertices() n_nod = self.domain.shape.n_nod new_dofs = nm.empty((n_nod, dofs.shape[1]), dtype=self.dtype) new_dofs.fill(fill_value) new_dofs[indx] = dofs[:indx.size] else: new_dofs = extend_cell_data(dofs, self.domain, self.region, val=fill_value) return new_dofs def remove_extra_dofs(self, dofs): """ Remove DOFs defined in higher order nodes (order > 1). """ if self.approx_order != 0: new_dofs = dofs[:self.n_vertex_dof] else: new_dofs = dofs return new_dofs def linearize(self, dofs, min_level=0, max_level=1, eps=1e-4): """ Linearize the solution for post-processing. Parameters ---------- dofs : array, shape (n_nod, n_component) The array of DOFs reshaped so that each column corresponds to one component. min_level : int The minimum required level of mesh refinement. max_level : int The maximum level of mesh refinement. eps : float The relative tolerance parameter of mesh adaptivity. Returns ------- mesh : Mesh instance The adapted, nonconforming, mesh. vdofs : array The DOFs defined in vertices of `mesh`. levels : array of ints The refinement level used for each element group. """ assert_(dofs.ndim == 2) n_nod, dpn = dofs.shape assert_(n_nod == self.n_nod) assert_(dpn == self.shape[0]) vertex_coors = self.coors[:self.n_vertex_dof, :] ps = self.poly_space gps = self.gel.poly_space vertex_conn = self.econn[:, :self.gel.n_vertex] eval_dofs = get_eval_dofs(dofs, self.econn, ps, ori=self.ori) eval_coors = get_eval_coors(vertex_coors, vertex_conn, gps) (level, coors, conn, vdofs, mat_ids) = create_output(eval_dofs, eval_coors, vertex_conn.shape[0], ps, min_level=min_level, max_level=max_level, eps=eps) mesh = Mesh.from_data('linearized_mesh', coors, None, [conn], [mat_ids], self.domain.mesh.descs) return mesh, vdofs, level def get_output_approx_order(self): """ Get the approximation order used in the output file. """ return min(self.approx_order, 1) def create_output(self, dofs, var_name, dof_names=None, key=None, extend=True, fill_value=None, linearization=None): """ Convert the DOFs corresponding to the field to a dictionary of output data usable by Mesh.write(). Parameters ---------- dofs : array, 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. key : str, optional The key to be used in the output dictionary instead of the variable name. extend : bool Extend the DOF values to cover the whole domain. fill_value : float or complex The value used to fill the missing DOF values if `extend` is True. linearization : Struct or None The linearization configuration for higher order approximations. Returns ------- out : dict The output dictionary. """ linearization = get_default(linearization, Struct(kind='strip')) out = {} if linearization.kind is None: out[key] = Struct(name='output_data', mode='full', data=dofs, var_name=var_name, dofs=dof_names, field_name=self.name) elif linearization.kind == 'strip': if extend: ext = self.extend_dofs(dofs, fill_value) else: ext = self.remove_extra_dofs(dofs) if ext is not None: approx_order = self.get_output_approx_order() if approx_order != 0: # Has vertex data. out[key] = Struct(name='output_data', mode='vertex', data=ext, var_name=var_name, dofs=dof_names) else: ext.shape = (ext.shape[0], 1, ext.shape[1], 1) out[key] = Struct(name='output_data', mode='cell', data=ext, var_name=var_name, dofs=dof_names) else: mesh, vdofs, levels = self.linearize(dofs, linearization.min_level, linearization.max_level, linearization.eps) out[key] = Struct(name='output_data', mode='vertex', data=vdofs, var_name=var_name, dofs=dof_names, mesh=mesh, levels=levels) out = convert_complex_output(out) return out def create_mesh(self, extra_nodes=True): """ Create a mesh from the field region, optionally including the field extra nodes. """ mesh = self.domain.mesh if self.approx_order != 0: if extra_nodes: conn = self.econn else: conn = self.econn[:, :self.gel.n_vertex] conns = [conn] mat_ids = [mesh.cmesh.cell_groups] descs = mesh.descs[:1] if extra_nodes: coors = self.coors else: coors = self.coors[:self.n_vertex_dof] mesh = Mesh.from_data(self.name, coors, None, conns, mat_ids, descs) return mesh def get_evaluate_cache(self, cache=None, share_geometry=False, verbose=False): """ Get the evaluate cache for :func:`Variable.evaluate_at() <sfepy.discrete.variables.Variable.evaluate_at()>`. Parameters ---------- cache : Struct instance, optional Optionally, use the provided instance to store the cache data. share_geometry : bool Set to True to indicate that all the evaluations will work on the same region. Certain data are then computed only for the first probe and cached. verbose : bool If False, reduce verbosity. Returns ------- cache : Struct instance The evaluate cache. """ import time try: from scipy.spatial import cKDTree as KDTree except ImportError: from scipy.spatial import KDTree from sfepy.discrete.fem.geometry_element import create_geometry_elements if cache is None: cache = Struct(name='evaluate_cache') tt = time.clock() if (cache.get('cmesh', None) is None) or not share_geometry: mesh = self.create_mesh(extra_nodes=False) cache.cmesh = cmesh = mesh.cmesh gels = create_geometry_elements() cmesh.set_local_entities(gels) cmesh.setup_entities() cache.centroids = cmesh.get_centroids(cmesh.tdim) if self.gel.name != '3_8': cache.normals0 = cmesh.get_facet_normals() cache.normals1 = None else: cache.normals0 = cmesh.get_facet_normals(0) cache.normals1 = cmesh.get_facet_normals(1) output('cmesh setup: %f s' % (time.clock()-tt), verbose=verbose) tt = time.clock() if (cache.get('kdtree', None) is None) or not share_geometry: cache.kdtree = KDTree(cmesh.coors) output('kdtree: %f s' % (time.clock()-tt), verbose=verbose) return cache def interp_to_qp(self, dofs): """ Interpolate DOFs into quadrature points. The quadrature order is given by the field approximation order. Parameters ---------- dofs : array The array of DOF values of shape `(n_nod, n_component)`. Returns ------- data_qp : array The values interpolated into the quadrature points. integral : Integral The corresponding integral defining the quadrature points. """ integral = Integral('i', order=self.approx_order) bf = self.get_base('v', False, integral) bf = bf[:,0,:].copy() data_qp = nm.dot(bf, dofs[self.econn]) data_qp = nm.swapaxes(data_qp, 0, 1) data_qp.shape = data_qp.shape + (1,) return data_qp, integral def get_coor(self, nods=None): """ Get coordinates of the field nodes. Parameters ---------- nods : array, optional The indices of the required nodes. If not given, the coordinates of all the nodes are returned. """ if nods is None: return self.coors else: return self.coors[nods] def get_connectivity(self, region, integration, is_trace=False): """ Convenience alias to `Field.get_econn()`, that is used in some terms. """ return self.get_econn(integration, region, is_trace=is_trace) def create_mapping(self, region, integral, integration, return_mapping=True): """ Create a new reference mapping. Compute jacobians, element volumes and base function derivatives for Volume-type geometries (volume mappings), and jacobians, normals and base function derivatives for Surface-type geometries (surface mappings). Notes ----- - surface mappings are defined on the surface region - surface mappings require field order to be > 0 """ domain = self.domain coors = domain.get_mesh_coors(actual=True) dconn = domain.get_conn() if integration == 'volume': qp = self.get_qp('v', integral) 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 elif (integration == 'surface') or (integration == 'surface_extra'): assert_(self.approx_order > 0) if self.ori is not None: msg = 'surface integrals do not work yet with the' \ ' hierarchical basis!' raise ValueError(msg) sd = domain.surface_groups[region.name] esd = self.surface_data[region.name] geo_ps = self.gel.poly_space ps = self.poly_space conn = sd.get_connectivity() mapping = SurfaceMapping(coors, conn, poly_space=geo_ps) if not self.is_surface: self.create_bqp(region.name, integral) qp = self.qp_coors[(integral.order, esd.bkey)] abf = ps.eval_base(qp.vals[0], transform=self.basis_transform) bf = abf[..., self.efaces[0]] indx = self.gel.get_surface_entities()[0] # Fix geometry element's 1st facet orientation for gradients. indx = nm.roll(indx, -1)[::-1] mapping.set_basis_indices(indx) sg = mapping.get_mapping(qp.vals[0], qp.weights, poly_space=Struct(n_nod=bf.shape[-1]), mode=integration) if integration == 'surface_extra': sg.alloc_extra_data(self.econn.shape[1]) bf_bg = geo_ps.eval_base(qp.vals, diff=True) ebf_bg = self.get_base(esd.bkey, 1, integral) sg.evaluate_bfbgm(bf_bg, ebf_bg, coors, sd.fis, dconn) else: # Do not use BQP for surface fields. qp = self.get_qp(sd.face_type, integral) bf = ps.eval_base(qp.vals, transform=self.basis_transform) sg = mapping.get_mapping(qp.vals, qp.weights, poly_space=
Struct(n_nod=bf.shape[-1])
sfepy.base.base.Struct
from __future__ import absolute_import import os.path as op import shutil import numpy as nm from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_ from sfepy.base.base import Struct from sfepy.homogenization.engine import HomogenizationEngine from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.homogenization.coefficients import Coefficients from sfepy.homogenization.coefs_base import CoefDummy from sfepy.applications import PDESolverApp from sfepy.base.plotutils import plt import six from six.moves import range def try_set_defaults(obj, attr, defaults, recur=False): try: values = getattr(obj, attr) except: values = defaults else: if recur and isinstance(values, dict): for key, val in six.iteritems(values): set_defaults(val, defaults) else: set_defaults(values, defaults) return values def save_raw_bg_logs(filename, logs): """ Save raw band gaps `logs` into the `filename` file. """ out = {} iranges = nm.cumsum([0] + [len(ii) for ii in logs.freqs]) out['iranges'] = iranges for key, log in ordered_iteritems(logs.to_dict()): out[key] = nm.concatenate(log, axis=0) with open(filename, 'w') as fd: nm.savez(fd, **out) def transform_plot_data(datas, plot_transform, conf): if plot_transform is not None: fun = conf.get_function(plot_transform[0]) dmin, dmax = 1e+10, -1e+10 tdatas = [] for data in datas: tdata = data.copy() if plot_transform is not None: tdata = fun(tdata, *plot_transform[1:]) dmin = min(dmin, nm.nanmin(tdata)) dmax = max(dmax, nm.nanmax(tdata)) tdatas.append(tdata) dmin, dmax = min(dmax - 1e-8, dmin), max(dmin + 1e-8, dmax) return (dmin, dmax), tdatas def plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot resonance/eigen-frequencies. `valid` must correspond to `freq_range` resonances : red masked resonances: dotted red """ if plt is None: return assert_(len(valid) == len(freq_range)) fig =
plt.figure(fig_num)
sfepy.base.plotutils.plt.figure
from __future__ import absolute_import import os.path as op import shutil import numpy as nm from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_ from sfepy.base.base import Struct from sfepy.homogenization.engine import HomogenizationEngine from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.homogenization.coefficients import Coefficients from sfepy.homogenization.coefs_base import CoefDummy from sfepy.applications import PDESolverApp from sfepy.base.plotutils import plt import six from six.moves import range def try_set_defaults(obj, attr, defaults, recur=False): try: values = getattr(obj, attr) except: values = defaults else: if recur and isinstance(values, dict): for key, val in six.iteritems(values): set_defaults(val, defaults) else: set_defaults(values, defaults) return values def save_raw_bg_logs(filename, logs): """ Save raw band gaps `logs` into the `filename` file. """ out = {} iranges = nm.cumsum([0] + [len(ii) for ii in logs.freqs]) out['iranges'] = iranges for key, log in ordered_iteritems(logs.to_dict()): out[key] = nm.concatenate(log, axis=0) with open(filename, 'w') as fd: nm.savez(fd, **out) def transform_plot_data(datas, plot_transform, conf): if plot_transform is not None: fun = conf.get_function(plot_transform[0]) dmin, dmax = 1e+10, -1e+10 tdatas = [] for data in datas: tdata = data.copy() if plot_transform is not None: tdata = fun(tdata, *plot_transform[1:]) dmin = min(dmin, nm.nanmin(tdata)) dmax = max(dmax, nm.nanmax(tdata)) tdatas.append(tdata) dmin, dmax = min(dmax - 1e-8, dmin), max(dmin + 1e-8, dmax) return (dmin, dmax), tdatas def plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot resonance/eigen-frequencies. `valid` must correspond to `freq_range` resonances : red masked resonances: dotted red """ if plt is None: return assert_(len(valid) == len(freq_range)) fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() l0 = l1 = None for ii, f in enumerate(freq_range): if valid[ii]: l0 = ax.plot([f, f], plot_range, **plot_rsc['resonance'])[0] else: l1 = ax.plot([f, f], plot_range, **plot_rsc['masked'])[0] if l0: l0.set_label(plot_labels['resonance']) if l1: l1.set_label(plot_labels['masked']) if new_axes: ax.set_xlim([freq_range[0], freq_range[-1]]) ax.set_ylim(plot_range) if show: plt.show() return fig def plot_logs(fig_num, plot_rsc, plot_labels, freqs, logs, valid, freq_range, plot_range, draw_eigs=True, show_legend=True, show=False, clear=False, new_axes=False): """ Plot logs of min/middle/max eigs of a mass matrix. """ if plt is None: return fig =
plt.figure(fig_num)
sfepy.base.plotutils.plt.figure
from __future__ import absolute_import import os.path as op import shutil import numpy as nm from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_ from sfepy.base.base import Struct from sfepy.homogenization.engine import HomogenizationEngine from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.homogenization.coefficients import Coefficients from sfepy.homogenization.coefs_base import CoefDummy from sfepy.applications import PDESolverApp from sfepy.base.plotutils import plt import six from six.moves import range def try_set_defaults(obj, attr, defaults, recur=False): try: values = getattr(obj, attr) except: values = defaults else: if recur and isinstance(values, dict): for key, val in six.iteritems(values): set_defaults(val, defaults) else: set_defaults(values, defaults) return values def save_raw_bg_logs(filename, logs): """ Save raw band gaps `logs` into the `filename` file. """ out = {} iranges = nm.cumsum([0] + [len(ii) for ii in logs.freqs]) out['iranges'] = iranges for key, log in ordered_iteritems(logs.to_dict()): out[key] = nm.concatenate(log, axis=0) with open(filename, 'w') as fd: nm.savez(fd, **out) def transform_plot_data(datas, plot_transform, conf): if plot_transform is not None: fun = conf.get_function(plot_transform[0]) dmin, dmax = 1e+10, -1e+10 tdatas = [] for data in datas: tdata = data.copy() if plot_transform is not None: tdata = fun(tdata, *plot_transform[1:]) dmin = min(dmin, nm.nanmin(tdata)) dmax = max(dmax, nm.nanmax(tdata)) tdatas.append(tdata) dmin, dmax = min(dmax - 1e-8, dmin), max(dmin + 1e-8, dmax) return (dmin, dmax), tdatas def plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot resonance/eigen-frequencies. `valid` must correspond to `freq_range` resonances : red masked resonances: dotted red """ if plt is None: return assert_(len(valid) == len(freq_range)) fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() l0 = l1 = None for ii, f in enumerate(freq_range): if valid[ii]: l0 = ax.plot([f, f], plot_range, **plot_rsc['resonance'])[0] else: l1 = ax.plot([f, f], plot_range, **plot_rsc['masked'])[0] if l0: l0.set_label(plot_labels['resonance']) if l1: l1.set_label(plot_labels['masked']) if new_axes: ax.set_xlim([freq_range[0], freq_range[-1]]) ax.set_ylim(plot_range) if show: plt.show() return fig def plot_logs(fig_num, plot_rsc, plot_labels, freqs, logs, valid, freq_range, plot_range, draw_eigs=True, show_legend=True, show=False, clear=False, new_axes=False): """ Plot logs of min/middle/max eigs of a mass matrix. """ if plt is None: return fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() if draw_eigs: plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range) for ii, log in enumerate(logs): l1 = ax.plot(freqs[ii], log[:, -1], **plot_rsc['eig_max']) if log.shape[1] >= 2: l2 = ax.plot(freqs[ii], log[:, 0], **plot_rsc['eig_min']) else: l2 = None if log.shape[1] == 3: l3 = ax.plot(freqs[ii], log[:, 1], **plot_rsc['eig_mid']) else: l3 = None l1[0].set_label(plot_labels['eig_max']) if l2: l2[0].set_label(plot_labels['eig_min']) if l3: l3[0].set_label(plot_labels['eig_mid']) fmin, fmax = freqs[0][0], freqs[-1][-1] ax.plot([fmin, fmax], [0, 0], **plot_rsc['x_axis']) ax.set_xlabel(plot_labels['x_axis']) ax.set_ylabel(plot_labels['y_axis']) if new_axes: ax.set_xlim([fmin, fmax]) ax.set_ylim(plot_range) if show_legend: ax.legend() if show: plt.show() return fig def plot_gap(ax, ranges, kind, kind_desc, plot_range, plot_rsc): """ Plot single band gap frequency ranges as rectangles. """ def draw_rect(ax, x, y, rsc): ax.fill(nm.asarray(x)[[0,1,1,0]], nm.asarray(y)[[0,0,1,1]], **rsc) # Colors. strong = plot_rsc['strong_gap'] weak = plot_rsc['weak_gap'] propagation = plot_rsc['propagation'] if kind == 'p': draw_rect(ax, ranges[0], plot_range, propagation) elif kind == 'w': draw_rect(ax, ranges[0], plot_range, weak) elif kind == 'wp': draw_rect(ax, ranges[0], plot_range, weak) draw_rect(ax, ranges[1], plot_range, propagation) elif kind == 's': draw_rect(ax, ranges[0], plot_range, strong) elif kind == 'sw': draw_rect(ax, ranges[0], plot_range, strong) draw_rect(ax, ranges[1], plot_range, weak) elif kind == 'swp': draw_rect(ax, ranges[0], plot_range, strong) draw_rect(ax, ranges[1], plot_range, weak) draw_rect(ax, ranges[2], plot_range, propagation) elif kind == 'is': draw_rect(ax, ranges[0], plot_range, strong) elif kind == 'iw': draw_rect(ax, ranges[0], plot_range, weak) else: raise ValueError('unknown band gap kind! (%s)' % kind) def plot_gaps(fig_num, plot_rsc, gaps, kinds, gap_ranges, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot band gaps as rectangles. """ if plt is None: return fig =
plt.figure(fig_num)
sfepy.base.plotutils.plt.figure
from __future__ import absolute_import import os.path as op import shutil import numpy as nm from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_ from sfepy.base.base import Struct from sfepy.homogenization.engine import HomogenizationEngine from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.homogenization.coefficients import Coefficients from sfepy.homogenization.coefs_base import CoefDummy from sfepy.applications import PDESolverApp from sfepy.base.plotutils import plt import six from six.moves import range def try_set_defaults(obj, attr, defaults, recur=False): try: values = getattr(obj, attr) except: values = defaults else: if recur and isinstance(values, dict): for key, val in six.iteritems(values): set_defaults(val, defaults) else: set_defaults(values, defaults) return values def save_raw_bg_logs(filename, logs): """ Save raw band gaps `logs` into the `filename` file. """ out = {} iranges = nm.cumsum([0] + [len(ii) for ii in logs.freqs]) out['iranges'] = iranges for key, log in ordered_iteritems(logs.to_dict()): out[key] = nm.concatenate(log, axis=0) with open(filename, 'w') as fd: nm.savez(fd, **out) def transform_plot_data(datas, plot_transform, conf): if plot_transform is not None: fun = conf.get_function(plot_transform[0]) dmin, dmax = 1e+10, -1e+10 tdatas = [] for data in datas: tdata = data.copy() if plot_transform is not None: tdata = fun(tdata, *plot_transform[1:]) dmin = min(dmin, nm.nanmin(tdata)) dmax = max(dmax, nm.nanmax(tdata)) tdatas.append(tdata) dmin, dmax = min(dmax - 1e-8, dmin), max(dmin + 1e-8, dmax) return (dmin, dmax), tdatas def plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot resonance/eigen-frequencies. `valid` must correspond to `freq_range` resonances : red masked resonances: dotted red """ if plt is None: return assert_(len(valid) == len(freq_range)) fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() l0 = l1 = None for ii, f in enumerate(freq_range): if valid[ii]: l0 = ax.plot([f, f], plot_range, **plot_rsc['resonance'])[0] else: l1 = ax.plot([f, f], plot_range, **plot_rsc['masked'])[0] if l0: l0.set_label(plot_labels['resonance']) if l1: l1.set_label(plot_labels['masked']) if new_axes: ax.set_xlim([freq_range[0], freq_range[-1]]) ax.set_ylim(plot_range) if show:
plt.show()
sfepy.base.plotutils.plt.show
from __future__ import absolute_import import os.path as op import shutil import numpy as nm from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_ from sfepy.base.base import Struct from sfepy.homogenization.engine import HomogenizationEngine from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.homogenization.coefficients import Coefficients from sfepy.homogenization.coefs_base import CoefDummy from sfepy.applications import PDESolverApp from sfepy.base.plotutils import plt import six from six.moves import range def try_set_defaults(obj, attr, defaults, recur=False): try: values = getattr(obj, attr) except: values = defaults else: if recur and isinstance(values, dict): for key, val in six.iteritems(values): set_defaults(val, defaults) else: set_defaults(values, defaults) return values def save_raw_bg_logs(filename, logs): """ Save raw band gaps `logs` into the `filename` file. """ out = {} iranges = nm.cumsum([0] + [len(ii) for ii in logs.freqs]) out['iranges'] = iranges for key, log in ordered_iteritems(logs.to_dict()): out[key] = nm.concatenate(log, axis=0) with open(filename, 'w') as fd: nm.savez(fd, **out) def transform_plot_data(datas, plot_transform, conf): if plot_transform is not None: fun = conf.get_function(plot_transform[0]) dmin, dmax = 1e+10, -1e+10 tdatas = [] for data in datas: tdata = data.copy() if plot_transform is not None: tdata = fun(tdata, *plot_transform[1:]) dmin = min(dmin, nm.nanmin(tdata)) dmax = max(dmax, nm.nanmax(tdata)) tdatas.append(tdata) dmin, dmax = min(dmax - 1e-8, dmin), max(dmin + 1e-8, dmax) return (dmin, dmax), tdatas def plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot resonance/eigen-frequencies. `valid` must correspond to `freq_range` resonances : red masked resonances: dotted red """ if plt is None: return assert_(len(valid) == len(freq_range)) fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() l0 = l1 = None for ii, f in enumerate(freq_range): if valid[ii]: l0 = ax.plot([f, f], plot_range, **plot_rsc['resonance'])[0] else: l1 = ax.plot([f, f], plot_range, **plot_rsc['masked'])[0] if l0: l0.set_label(plot_labels['resonance']) if l1: l1.set_label(plot_labels['masked']) if new_axes: ax.set_xlim([freq_range[0], freq_range[-1]]) ax.set_ylim(plot_range) if show: plt.show() return fig def plot_logs(fig_num, plot_rsc, plot_labels, freqs, logs, valid, freq_range, plot_range, draw_eigs=True, show_legend=True, show=False, clear=False, new_axes=False): """ Plot logs of min/middle/max eigs of a mass matrix. """ if plt is None: return fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() if draw_eigs: plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range) for ii, log in enumerate(logs): l1 = ax.plot(freqs[ii], log[:, -1], **plot_rsc['eig_max']) if log.shape[1] >= 2: l2 = ax.plot(freqs[ii], log[:, 0], **plot_rsc['eig_min']) else: l2 = None if log.shape[1] == 3: l3 = ax.plot(freqs[ii], log[:, 1], **plot_rsc['eig_mid']) else: l3 = None l1[0].set_label(plot_labels['eig_max']) if l2: l2[0].set_label(plot_labels['eig_min']) if l3: l3[0].set_label(plot_labels['eig_mid']) fmin, fmax = freqs[0][0], freqs[-1][-1] ax.plot([fmin, fmax], [0, 0], **plot_rsc['x_axis']) ax.set_xlabel(plot_labels['x_axis']) ax.set_ylabel(plot_labels['y_axis']) if new_axes: ax.set_xlim([fmin, fmax]) ax.set_ylim(plot_range) if show_legend: ax.legend() if show:
plt.show()
sfepy.base.plotutils.plt.show
from __future__ import absolute_import import os.path as op import shutil import numpy as nm from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_ from sfepy.base.base import Struct from sfepy.homogenization.engine import HomogenizationEngine from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.homogenization.coefficients import Coefficients from sfepy.homogenization.coefs_base import CoefDummy from sfepy.applications import PDESolverApp from sfepy.base.plotutils import plt import six from six.moves import range def try_set_defaults(obj, attr, defaults, recur=False): try: values = getattr(obj, attr) except: values = defaults else: if recur and isinstance(values, dict): for key, val in six.iteritems(values): set_defaults(val, defaults) else: set_defaults(values, defaults) return values def save_raw_bg_logs(filename, logs): """ Save raw band gaps `logs` into the `filename` file. """ out = {} iranges = nm.cumsum([0] + [len(ii) for ii in logs.freqs]) out['iranges'] = iranges for key, log in ordered_iteritems(logs.to_dict()): out[key] = nm.concatenate(log, axis=0) with open(filename, 'w') as fd: nm.savez(fd, **out) def transform_plot_data(datas, plot_transform, conf): if plot_transform is not None: fun = conf.get_function(plot_transform[0]) dmin, dmax = 1e+10, -1e+10 tdatas = [] for data in datas: tdata = data.copy() if plot_transform is not None: tdata = fun(tdata, *plot_transform[1:]) dmin = min(dmin, nm.nanmin(tdata)) dmax = max(dmax, nm.nanmax(tdata)) tdatas.append(tdata) dmin, dmax = min(dmax - 1e-8, dmin), max(dmin + 1e-8, dmax) return (dmin, dmax), tdatas def plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot resonance/eigen-frequencies. `valid` must correspond to `freq_range` resonances : red masked resonances: dotted red """ if plt is None: return assert_(len(valid) == len(freq_range)) fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() l0 = l1 = None for ii, f in enumerate(freq_range): if valid[ii]: l0 = ax.plot([f, f], plot_range, **plot_rsc['resonance'])[0] else: l1 = ax.plot([f, f], plot_range, **plot_rsc['masked'])[0] if l0: l0.set_label(plot_labels['resonance']) if l1: l1.set_label(plot_labels['masked']) if new_axes: ax.set_xlim([freq_range[0], freq_range[-1]]) ax.set_ylim(plot_range) if show: plt.show() return fig def plot_logs(fig_num, plot_rsc, plot_labels, freqs, logs, valid, freq_range, plot_range, draw_eigs=True, show_legend=True, show=False, clear=False, new_axes=False): """ Plot logs of min/middle/max eigs of a mass matrix. """ if plt is None: return fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() if draw_eigs: plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range) for ii, log in enumerate(logs): l1 = ax.plot(freqs[ii], log[:, -1], **plot_rsc['eig_max']) if log.shape[1] >= 2: l2 = ax.plot(freqs[ii], log[:, 0], **plot_rsc['eig_min']) else: l2 = None if log.shape[1] == 3: l3 = ax.plot(freqs[ii], log[:, 1], **plot_rsc['eig_mid']) else: l3 = None l1[0].set_label(plot_labels['eig_max']) if l2: l2[0].set_label(plot_labels['eig_min']) if l3: l3[0].set_label(plot_labels['eig_mid']) fmin, fmax = freqs[0][0], freqs[-1][-1] ax.plot([fmin, fmax], [0, 0], **plot_rsc['x_axis']) ax.set_xlabel(plot_labels['x_axis']) ax.set_ylabel(plot_labels['y_axis']) if new_axes: ax.set_xlim([fmin, fmax]) ax.set_ylim(plot_range) if show_legend: ax.legend() if show: plt.show() return fig def plot_gap(ax, ranges, kind, kind_desc, plot_range, plot_rsc): """ Plot single band gap frequency ranges as rectangles. """ def draw_rect(ax, x, y, rsc): ax.fill(nm.asarray(x)[[0,1,1,0]], nm.asarray(y)[[0,0,1,1]], **rsc) # Colors. strong = plot_rsc['strong_gap'] weak = plot_rsc['weak_gap'] propagation = plot_rsc['propagation'] if kind == 'p': draw_rect(ax, ranges[0], plot_range, propagation) elif kind == 'w': draw_rect(ax, ranges[0], plot_range, weak) elif kind == 'wp': draw_rect(ax, ranges[0], plot_range, weak) draw_rect(ax, ranges[1], plot_range, propagation) elif kind == 's': draw_rect(ax, ranges[0], plot_range, strong) elif kind == 'sw': draw_rect(ax, ranges[0], plot_range, strong) draw_rect(ax, ranges[1], plot_range, weak) elif kind == 'swp': draw_rect(ax, ranges[0], plot_range, strong) draw_rect(ax, ranges[1], plot_range, weak) draw_rect(ax, ranges[2], plot_range, propagation) elif kind == 'is': draw_rect(ax, ranges[0], plot_range, strong) elif kind == 'iw': draw_rect(ax, ranges[0], plot_range, weak) else: raise ValueError('unknown band gap kind! (%s)' % kind) def plot_gaps(fig_num, plot_rsc, gaps, kinds, gap_ranges, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot band gaps as rectangles. """ if plt is None: return fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() for ii in range(len(freq_range) - 1): f0, f1 = freq_range[[ii, ii+1]] gap = gaps[ii] ranges = gap_ranges[ii] if isinstance(gap, list): for ig, (gmin, gmax) in enumerate(gap): kind, kind_desc = kinds[ii][ig] plot_gap(ax, ranges[ig], kind, kind_desc, plot_range, plot_rsc) output(ii, gmin[0], gmax[0], '%.8f' % f0, '%.8f' % f1) output(' -> %s\n %s' %(kind_desc, ranges[ig])) else: gmin, gmax = gap kind, kind_desc = kinds[ii] plot_gap(ax, ranges, kind, kind_desc, plot_range, plot_rsc) output(ii, gmin[0], gmax[0], '%.8f' % f0, '%.8f' % f1) output(' -> %s\n %s' %(kind_desc, ranges)) if new_axes: ax.set_xlim([freq_range[0], freq_range[-1]]) ax.set_ylim(plot_range) if show:
plt.show()
sfepy.base.plotutils.plt.show
from __future__ import absolute_import import os.path as op import shutil import numpy as nm from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_ from sfepy.base.base import Struct from sfepy.homogenization.engine import HomogenizationEngine from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.homogenization.coefficients import Coefficients from sfepy.homogenization.coefs_base import CoefDummy from sfepy.applications import PDESolverApp from sfepy.base.plotutils import plt import six from six.moves import range def try_set_defaults(obj, attr, defaults, recur=False): try: values = getattr(obj, attr) except: values = defaults else: if recur and isinstance(values, dict): for key, val in six.iteritems(values): set_defaults(val, defaults) else: set_defaults(values, defaults) return values def save_raw_bg_logs(filename, logs): """ Save raw band gaps `logs` into the `filename` file. """ out = {} iranges = nm.cumsum([0] + [len(ii) for ii in logs.freqs]) out['iranges'] = iranges for key, log in ordered_iteritems(logs.to_dict()): out[key] = nm.concatenate(log, axis=0) with open(filename, 'w') as fd: nm.savez(fd, **out) def transform_plot_data(datas, plot_transform, conf): if plot_transform is not None: fun = conf.get_function(plot_transform[0]) dmin, dmax = 1e+10, -1e+10 tdatas = [] for data in datas: tdata = data.copy() if plot_transform is not None: tdata = fun(tdata, *plot_transform[1:]) dmin = min(dmin, nm.nanmin(tdata)) dmax = max(dmax, nm.nanmax(tdata)) tdatas.append(tdata) dmin, dmax = min(dmax - 1e-8, dmin), max(dmin + 1e-8, dmax) return (dmin, dmax), tdatas def plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot resonance/eigen-frequencies. `valid` must correspond to `freq_range` resonances : red masked resonances: dotted red """ if plt is None: return assert_(len(valid) == len(freq_range)) fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() l0 = l1 = None for ii, f in enumerate(freq_range): if valid[ii]: l0 = ax.plot([f, f], plot_range, **plot_rsc['resonance'])[0] else: l1 = ax.plot([f, f], plot_range, **plot_rsc['masked'])[0] if l0: l0.set_label(plot_labels['resonance']) if l1: l1.set_label(plot_labels['masked']) if new_axes: ax.set_xlim([freq_range[0], freq_range[-1]]) ax.set_ylim(plot_range) if show: plt.show() return fig def plot_logs(fig_num, plot_rsc, plot_labels, freqs, logs, valid, freq_range, plot_range, draw_eigs=True, show_legend=True, show=False, clear=False, new_axes=False): """ Plot logs of min/middle/max eigs of a mass matrix. """ if plt is None: return fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() if draw_eigs: plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range) for ii, log in enumerate(logs): l1 = ax.plot(freqs[ii], log[:, -1], **plot_rsc['eig_max']) if log.shape[1] >= 2: l2 = ax.plot(freqs[ii], log[:, 0], **plot_rsc['eig_min']) else: l2 = None if log.shape[1] == 3: l3 = ax.plot(freqs[ii], log[:, 1], **plot_rsc['eig_mid']) else: l3 = None l1[0].set_label(plot_labels['eig_max']) if l2: l2[0].set_label(plot_labels['eig_min']) if l3: l3[0].set_label(plot_labels['eig_mid']) fmin, fmax = freqs[0][0], freqs[-1][-1] ax.plot([fmin, fmax], [0, 0], **plot_rsc['x_axis']) ax.set_xlabel(plot_labels['x_axis']) ax.set_ylabel(plot_labels['y_axis']) if new_axes: ax.set_xlim([fmin, fmax]) ax.set_ylim(plot_range) if show_legend: ax.legend() if show: plt.show() return fig def plot_gap(ax, ranges, kind, kind_desc, plot_range, plot_rsc): """ Plot single band gap frequency ranges as rectangles. """ def draw_rect(ax, x, y, rsc): ax.fill(nm.asarray(x)[[0,1,1,0]], nm.asarray(y)[[0,0,1,1]], **rsc) # Colors. strong = plot_rsc['strong_gap'] weak = plot_rsc['weak_gap'] propagation = plot_rsc['propagation'] if kind == 'p': draw_rect(ax, ranges[0], plot_range, propagation) elif kind == 'w': draw_rect(ax, ranges[0], plot_range, weak) elif kind == 'wp': draw_rect(ax, ranges[0], plot_range, weak) draw_rect(ax, ranges[1], plot_range, propagation) elif kind == 's': draw_rect(ax, ranges[0], plot_range, strong) elif kind == 'sw': draw_rect(ax, ranges[0], plot_range, strong) draw_rect(ax, ranges[1], plot_range, weak) elif kind == 'swp': draw_rect(ax, ranges[0], plot_range, strong) draw_rect(ax, ranges[1], plot_range, weak) draw_rect(ax, ranges[2], plot_range, propagation) elif kind == 'is': draw_rect(ax, ranges[0], plot_range, strong) elif kind == 'iw': draw_rect(ax, ranges[0], plot_range, weak) else: raise ValueError('unknown band gap kind! (%s)' % kind) def plot_gaps(fig_num, plot_rsc, gaps, kinds, gap_ranges, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot band gaps as rectangles. """ if plt is None: return fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() for ii in range(len(freq_range) - 1): f0, f1 = freq_range[[ii, ii+1]] gap = gaps[ii] ranges = gap_ranges[ii] if isinstance(gap, list): for ig, (gmin, gmax) in enumerate(gap): kind, kind_desc = kinds[ii][ig] plot_gap(ax, ranges[ig], kind, kind_desc, plot_range, plot_rsc) output(ii, gmin[0], gmax[0], '%.8f' % f0, '%.8f' % f1) output(' -> %s\n %s' %(kind_desc, ranges[ig])) else: gmin, gmax = gap kind, kind_desc = kinds[ii] plot_gap(ax, ranges, kind, kind_desc, plot_range, plot_rsc) output(ii, gmin[0], gmax[0], '%.8f' % f0, '%.8f' % f1) output(' -> %s\n %s' %(kind_desc, ranges)) if new_axes: ax.set_xlim([freq_range[0], freq_range[-1]]) ax.set_ylim(plot_range) if show: plt.show() return fig def _get_fig_name(output_dir, fig_name, key, common, fig_suffix): """ Construct the complete name of figure file. """ name = key.replace(common, '') if name and (not name.startswith('_')): name = '_' + name fig_name = fig_name + name + fig_suffix return op.join(output_dir, fig_name) class AcousticBandGapsApp(HomogenizationApp): """ Application for computing acoustic band gaps. """ @staticmethod def process_options(options): """ Application options setup. Sets default values for missing non-compulsory options. """ get = options.get default_plot_options = {'show' : True,'legend' : False,} aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : r'min eig($M^*$)', 'eig_mid' : r'mid eig($M^*$)', 'eig_max' : r'max eig($M^*$)', 'x_axis' : r'$\sqrt{\lambda}$, $\omega$', 'y_axis' : r'eigenvalues of mass matrix $M^*$', } plot_labels = try_set_defaults(options, 'plot_labels', aux, recur=True) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : r'$\kappa$(min)', 'eig_mid' : r'$\kappa$(mid)', 'eig_max' : r'$\kappa$(max)', 'x_axis' : r'$\sqrt{\lambda}$, $\omega$', 'y_axis' : 'polarization angles', } plot_labels_angle = try_set_defaults(options, 'plot_labels_angle', aux) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : r'wave number (min)', 'eig_mid' : r'wave number (mid)', 'eig_max' : r'wave number (max)', 'x_axis' : r'$\sqrt{\lambda}$, $\omega$', 'y_axis' : 'wave numbers', } plot_labels_wave = try_set_defaults(options, 'plot_labels_wave', aux) plot_rsc = { 'resonance' : {'linewidth' : 0.5, 'color' : 'r', 'linestyle' : '-'}, 'masked' : {'linewidth' : 0.5, 'color' : 'r', 'linestyle' : ':'}, 'x_axis' : {'linewidth' : 0.5, 'color' : 'k', 'linestyle' : '--'}, 'eig_min' : {'linewidth' : 2.0, 'color' : (0.0, 0.0, 1.0), 'linestyle' : ':' }, 'eig_mid' : {'linewidth' : 2.0, 'color' : (0.0, 0.0, 0.8), 'linestyle' : '--' }, 'eig_max' : {'linewidth' : 2.0, 'color' : (0.0, 0.0, 0.6), 'linestyle' : '-' }, 'strong_gap' : {'linewidth' : 0, 'facecolor' : (0.2, 0.4, 0.2)}, 'weak_gap' : {'linewidth' : 0, 'facecolor' : (0.6, 0.8, 0.6)}, 'propagation' : {'linewidth' : 0, 'facecolor' : (1, 1, 1)}, 'params' : {'axes.labelsize': 'x-large', 'font.size': 14, 'legend.fontsize': 'large', 'legend.loc': 'best', 'xtick.labelsize': 'large', 'ytick.labelsize': 'large', 'text.usetex': True}, } plot_rsc = try_set_defaults(options, 'plot_rsc', plot_rsc) return Struct(incident_wave_dir=get('incident_wave_dir', None), plot_transform=get('plot_transform', None), plot_transform_wave=get('plot_transform_wave', None), plot_transform_angle=get('plot_transform_angle', None), plot_options=get('plot_options', default_plot_options), fig_name=get('fig_name', None), fig_name_wave=get('fig_name_wave', None), fig_name_angle=get('fig_name_angle', None), fig_suffix=get('fig_suffix', '.pdf'), plot_labels=plot_labels, plot_labels_angle=plot_labels_angle, plot_labels_wave=plot_labels_wave, plot_rsc=plot_rsc) @staticmethod def process_options_pv(options): """ Application options setup for phase velocity computation. Sets default values for missing non-compulsory options. """ get = options.get incident_wave_dir=get('incident_wave_dir', None, 'missing "incident_wave_dir" in options!') return
Struct(incident_wave_dir=incident_wave_dir)
sfepy.base.base.Struct
from __future__ import absolute_import import os.path as op import shutil import numpy as nm from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_ from sfepy.base.base import Struct from sfepy.homogenization.engine import HomogenizationEngine from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.homogenization.coefficients import Coefficients from sfepy.homogenization.coefs_base import CoefDummy from sfepy.applications import PDESolverApp from sfepy.base.plotutils import plt import six from six.moves import range def try_set_defaults(obj, attr, defaults, recur=False): try: values = getattr(obj, attr) except: values = defaults else: if recur and isinstance(values, dict): for key, val in six.iteritems(values): set_defaults(val, defaults) else: set_defaults(values, defaults) return values def save_raw_bg_logs(filename, logs): """ Save raw band gaps `logs` into the `filename` file. """ out = {} iranges = nm.cumsum([0] + [len(ii) for ii in logs.freqs]) out['iranges'] = iranges for key, log in ordered_iteritems(logs.to_dict()): out[key] = nm.concatenate(log, axis=0) with open(filename, 'w') as fd: nm.savez(fd, **out) def transform_plot_data(datas, plot_transform, conf): if plot_transform is not None: fun = conf.get_function(plot_transform[0]) dmin, dmax = 1e+10, -1e+10 tdatas = [] for data in datas: tdata = data.copy() if plot_transform is not None: tdata = fun(tdata, *plot_transform[1:]) dmin = min(dmin, nm.nanmin(tdata)) dmax = max(dmax, nm.nanmax(tdata)) tdatas.append(tdata) dmin, dmax = min(dmax - 1e-8, dmin), max(dmin + 1e-8, dmax) return (dmin, dmax), tdatas def plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot resonance/eigen-frequencies. `valid` must correspond to `freq_range` resonances : red masked resonances: dotted red """ if plt is None: return assert_(len(valid) == len(freq_range)) fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() l0 = l1 = None for ii, f in enumerate(freq_range): if valid[ii]: l0 = ax.plot([f, f], plot_range, **plot_rsc['resonance'])[0] else: l1 = ax.plot([f, f], plot_range, **plot_rsc['masked'])[0] if l0: l0.set_label(plot_labels['resonance']) if l1: l1.set_label(plot_labels['masked']) if new_axes: ax.set_xlim([freq_range[0], freq_range[-1]]) ax.set_ylim(plot_range) if show: plt.show() return fig def plot_logs(fig_num, plot_rsc, plot_labels, freqs, logs, valid, freq_range, plot_range, draw_eigs=True, show_legend=True, show=False, clear=False, new_axes=False): """ Plot logs of min/middle/max eigs of a mass matrix. """ if plt is None: return fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() if draw_eigs: plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range) for ii, log in enumerate(logs): l1 = ax.plot(freqs[ii], log[:, -1], **plot_rsc['eig_max']) if log.shape[1] >= 2: l2 = ax.plot(freqs[ii], log[:, 0], **plot_rsc['eig_min']) else: l2 = None if log.shape[1] == 3: l3 = ax.plot(freqs[ii], log[:, 1], **plot_rsc['eig_mid']) else: l3 = None l1[0].set_label(plot_labels['eig_max']) if l2: l2[0].set_label(plot_labels['eig_min']) if l3: l3[0].set_label(plot_labels['eig_mid']) fmin, fmax = freqs[0][0], freqs[-1][-1] ax.plot([fmin, fmax], [0, 0], **plot_rsc['x_axis']) ax.set_xlabel(plot_labels['x_axis']) ax.set_ylabel(plot_labels['y_axis']) if new_axes: ax.set_xlim([fmin, fmax]) ax.set_ylim(plot_range) if show_legend: ax.legend() if show: plt.show() return fig def plot_gap(ax, ranges, kind, kind_desc, plot_range, plot_rsc): """ Plot single band gap frequency ranges as rectangles. """ def draw_rect(ax, x, y, rsc): ax.fill(nm.asarray(x)[[0,1,1,0]], nm.asarray(y)[[0,0,1,1]], **rsc) # Colors. strong = plot_rsc['strong_gap'] weak = plot_rsc['weak_gap'] propagation = plot_rsc['propagation'] if kind == 'p': draw_rect(ax, ranges[0], plot_range, propagation) elif kind == 'w': draw_rect(ax, ranges[0], plot_range, weak) elif kind == 'wp': draw_rect(ax, ranges[0], plot_range, weak) draw_rect(ax, ranges[1], plot_range, propagation) elif kind == 's': draw_rect(ax, ranges[0], plot_range, strong) elif kind == 'sw': draw_rect(ax, ranges[0], plot_range, strong) draw_rect(ax, ranges[1], plot_range, weak) elif kind == 'swp': draw_rect(ax, ranges[0], plot_range, strong) draw_rect(ax, ranges[1], plot_range, weak) draw_rect(ax, ranges[2], plot_range, propagation) elif kind == 'is': draw_rect(ax, ranges[0], plot_range, strong) elif kind == 'iw': draw_rect(ax, ranges[0], plot_range, weak) else: raise ValueError('unknown band gap kind! (%s)' % kind) def plot_gaps(fig_num, plot_rsc, gaps, kinds, gap_ranges, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot band gaps as rectangles. """ if plt is None: return fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() for ii in range(len(freq_range) - 1): f0, f1 = freq_range[[ii, ii+1]] gap = gaps[ii] ranges = gap_ranges[ii] if isinstance(gap, list): for ig, (gmin, gmax) in enumerate(gap): kind, kind_desc = kinds[ii][ig] plot_gap(ax, ranges[ig], kind, kind_desc, plot_range, plot_rsc) output(ii, gmin[0], gmax[0], '%.8f' % f0, '%.8f' % f1) output(' -> %s\n %s' %(kind_desc, ranges[ig])) else: gmin, gmax = gap kind, kind_desc = kinds[ii] plot_gap(ax, ranges, kind, kind_desc, plot_range, plot_rsc) output(ii, gmin[0], gmax[0], '%.8f' % f0, '%.8f' % f1) output(' -> %s\n %s' %(kind_desc, ranges)) if new_axes: ax.set_xlim([freq_range[0], freq_range[-1]]) ax.set_ylim(plot_range) if show: plt.show() return fig def _get_fig_name(output_dir, fig_name, key, common, fig_suffix): """ Construct the complete name of figure file. """ name = key.replace(common, '') if name and (not name.startswith('_')): name = '_' + name fig_name = fig_name + name + fig_suffix return op.join(output_dir, fig_name) class AcousticBandGapsApp(HomogenizationApp): """ Application for computing acoustic band gaps. """ @staticmethod def process_options(options): """ Application options setup. Sets default values for missing non-compulsory options. """ get = options.get default_plot_options = {'show' : True,'legend' : False,} aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : r'min eig($M^*$)', 'eig_mid' : r'mid eig($M^*$)', 'eig_max' : r'max eig($M^*$)', 'x_axis' : r'$\sqrt{\lambda}$, $\omega$', 'y_axis' : r'eigenvalues of mass matrix $M^*$', } plot_labels = try_set_defaults(options, 'plot_labels', aux, recur=True) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : r'$\kappa$(min)', 'eig_mid' : r'$\kappa$(mid)', 'eig_max' : r'$\kappa$(max)', 'x_axis' : r'$\sqrt{\lambda}$, $\omega$', 'y_axis' : 'polarization angles', } plot_labels_angle = try_set_defaults(options, 'plot_labels_angle', aux) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : r'wave number (min)', 'eig_mid' : r'wave number (mid)', 'eig_max' : r'wave number (max)', 'x_axis' : r'$\sqrt{\lambda}$, $\omega$', 'y_axis' : 'wave numbers', } plot_labels_wave = try_set_defaults(options, 'plot_labels_wave', aux) plot_rsc = { 'resonance' : {'linewidth' : 0.5, 'color' : 'r', 'linestyle' : '-'}, 'masked' : {'linewidth' : 0.5, 'color' : 'r', 'linestyle' : ':'}, 'x_axis' : {'linewidth' : 0.5, 'color' : 'k', 'linestyle' : '--'}, 'eig_min' : {'linewidth' : 2.0, 'color' : (0.0, 0.0, 1.0), 'linestyle' : ':' }, 'eig_mid' : {'linewidth' : 2.0, 'color' : (0.0, 0.0, 0.8), 'linestyle' : '--' }, 'eig_max' : {'linewidth' : 2.0, 'color' : (0.0, 0.0, 0.6), 'linestyle' : '-' }, 'strong_gap' : {'linewidth' : 0, 'facecolor' : (0.2, 0.4, 0.2)}, 'weak_gap' : {'linewidth' : 0, 'facecolor' : (0.6, 0.8, 0.6)}, 'propagation' : {'linewidth' : 0, 'facecolor' : (1, 1, 1)}, 'params' : {'axes.labelsize': 'x-large', 'font.size': 14, 'legend.fontsize': 'large', 'legend.loc': 'best', 'xtick.labelsize': 'large', 'ytick.labelsize': 'large', 'text.usetex': True}, } plot_rsc = try_set_defaults(options, 'plot_rsc', plot_rsc) return Struct(incident_wave_dir=get('incident_wave_dir', None), plot_transform=get('plot_transform', None), plot_transform_wave=get('plot_transform_wave', None), plot_transform_angle=get('plot_transform_angle', None), plot_options=get('plot_options', default_plot_options), fig_name=get('fig_name', None), fig_name_wave=get('fig_name_wave', None), fig_name_angle=get('fig_name_angle', None), fig_suffix=get('fig_suffix', '.pdf'), plot_labels=plot_labels, plot_labels_angle=plot_labels_angle, plot_labels_wave=plot_labels_wave, plot_rsc=plot_rsc) @staticmethod def process_options_pv(options): """ Application options setup for phase velocity computation. Sets default values for missing non-compulsory options. """ get = options.get incident_wave_dir=get('incident_wave_dir', None, 'missing "incident_wave_dir" in options!') return Struct(incident_wave_dir=incident_wave_dir) def __init__(self, conf, options, output_prefix, **kwargs): PDESolverApp.__init__(self, conf, options, output_prefix, init_equations=False) self.setup_options() if conf._filename: output_dir = self.problem.output_dir shutil.copyfile(conf._filename, op.join(output_dir, op.basename(conf._filename))) def setup_options(self):
HomogenizationApp.setup_options(self)
sfepy.homogenization.homogen_app.HomogenizationApp.setup_options
from __future__ import absolute_import import os.path as op import shutil import numpy as nm from sfepy.base.base import ordered_iteritems, output, set_defaults, assert_ from sfepy.base.base import Struct from sfepy.homogenization.engine import HomogenizationEngine from sfepy.homogenization.homogen_app import HomogenizationApp from sfepy.homogenization.coefficients import Coefficients from sfepy.homogenization.coefs_base import CoefDummy from sfepy.applications import PDESolverApp from sfepy.base.plotutils import plt import six from six.moves import range def try_set_defaults(obj, attr, defaults, recur=False): try: values = getattr(obj, attr) except: values = defaults else: if recur and isinstance(values, dict): for key, val in six.iteritems(values): set_defaults(val, defaults) else: set_defaults(values, defaults) return values def save_raw_bg_logs(filename, logs): """ Save raw band gaps `logs` into the `filename` file. """ out = {} iranges = nm.cumsum([0] + [len(ii) for ii in logs.freqs]) out['iranges'] = iranges for key, log in ordered_iteritems(logs.to_dict()): out[key] = nm.concatenate(log, axis=0) with open(filename, 'w') as fd: nm.savez(fd, **out) def transform_plot_data(datas, plot_transform, conf): if plot_transform is not None: fun = conf.get_function(plot_transform[0]) dmin, dmax = 1e+10, -1e+10 tdatas = [] for data in datas: tdata = data.copy() if plot_transform is not None: tdata = fun(tdata, *plot_transform[1:]) dmin = min(dmin, nm.nanmin(tdata)) dmax = max(dmax, nm.nanmax(tdata)) tdatas.append(tdata) dmin, dmax = min(dmax - 1e-8, dmin), max(dmin + 1e-8, dmax) return (dmin, dmax), tdatas def plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot resonance/eigen-frequencies. `valid` must correspond to `freq_range` resonances : red masked resonances: dotted red """ if plt is None: return assert_(len(valid) == len(freq_range)) fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() l0 = l1 = None for ii, f in enumerate(freq_range): if valid[ii]: l0 = ax.plot([f, f], plot_range, **plot_rsc['resonance'])[0] else: l1 = ax.plot([f, f], plot_range, **plot_rsc['masked'])[0] if l0: l0.set_label(plot_labels['resonance']) if l1: l1.set_label(plot_labels['masked']) if new_axes: ax.set_xlim([freq_range[0], freq_range[-1]]) ax.set_ylim(plot_range) if show: plt.show() return fig def plot_logs(fig_num, plot_rsc, plot_labels, freqs, logs, valid, freq_range, plot_range, draw_eigs=True, show_legend=True, show=False, clear=False, new_axes=False): """ Plot logs of min/middle/max eigs of a mass matrix. """ if plt is None: return fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() if draw_eigs: plot_eigs(fig_num, plot_rsc, plot_labels, valid, freq_range, plot_range) for ii, log in enumerate(logs): l1 = ax.plot(freqs[ii], log[:, -1], **plot_rsc['eig_max']) if log.shape[1] >= 2: l2 = ax.plot(freqs[ii], log[:, 0], **plot_rsc['eig_min']) else: l2 = None if log.shape[1] == 3: l3 = ax.plot(freqs[ii], log[:, 1], **plot_rsc['eig_mid']) else: l3 = None l1[0].set_label(plot_labels['eig_max']) if l2: l2[0].set_label(plot_labels['eig_min']) if l3: l3[0].set_label(plot_labels['eig_mid']) fmin, fmax = freqs[0][0], freqs[-1][-1] ax.plot([fmin, fmax], [0, 0], **plot_rsc['x_axis']) ax.set_xlabel(plot_labels['x_axis']) ax.set_ylabel(plot_labels['y_axis']) if new_axes: ax.set_xlim([fmin, fmax]) ax.set_ylim(plot_range) if show_legend: ax.legend() if show: plt.show() return fig def plot_gap(ax, ranges, kind, kind_desc, plot_range, plot_rsc): """ Plot single band gap frequency ranges as rectangles. """ def draw_rect(ax, x, y, rsc): ax.fill(nm.asarray(x)[[0,1,1,0]], nm.asarray(y)[[0,0,1,1]], **rsc) # Colors. strong = plot_rsc['strong_gap'] weak = plot_rsc['weak_gap'] propagation = plot_rsc['propagation'] if kind == 'p': draw_rect(ax, ranges[0], plot_range, propagation) elif kind == 'w': draw_rect(ax, ranges[0], plot_range, weak) elif kind == 'wp': draw_rect(ax, ranges[0], plot_range, weak) draw_rect(ax, ranges[1], plot_range, propagation) elif kind == 's': draw_rect(ax, ranges[0], plot_range, strong) elif kind == 'sw': draw_rect(ax, ranges[0], plot_range, strong) draw_rect(ax, ranges[1], plot_range, weak) elif kind == 'swp': draw_rect(ax, ranges[0], plot_range, strong) draw_rect(ax, ranges[1], plot_range, weak) draw_rect(ax, ranges[2], plot_range, propagation) elif kind == 'is': draw_rect(ax, ranges[0], plot_range, strong) elif kind == 'iw': draw_rect(ax, ranges[0], plot_range, weak) else: raise ValueError('unknown band gap kind! (%s)' % kind) def plot_gaps(fig_num, plot_rsc, gaps, kinds, gap_ranges, freq_range, plot_range, show=False, clear=False, new_axes=False): """ Plot band gaps as rectangles. """ if plt is None: return fig = plt.figure(fig_num) if clear: fig.clf() if new_axes: ax = fig.add_subplot(111) else: ax = fig.gca() for ii in range(len(freq_range) - 1): f0, f1 = freq_range[[ii, ii+1]] gap = gaps[ii] ranges = gap_ranges[ii] if isinstance(gap, list): for ig, (gmin, gmax) in enumerate(gap): kind, kind_desc = kinds[ii][ig] plot_gap(ax, ranges[ig], kind, kind_desc, plot_range, plot_rsc) output(ii, gmin[0], gmax[0], '%.8f' % f0, '%.8f' % f1) output(' -> %s\n %s' %(kind_desc, ranges[ig])) else: gmin, gmax = gap kind, kind_desc = kinds[ii] plot_gap(ax, ranges, kind, kind_desc, plot_range, plot_rsc) output(ii, gmin[0], gmax[0], '%.8f' % f0, '%.8f' % f1) output(' -> %s\n %s' %(kind_desc, ranges)) if new_axes: ax.set_xlim([freq_range[0], freq_range[-1]]) ax.set_ylim(plot_range) if show: plt.show() return fig def _get_fig_name(output_dir, fig_name, key, common, fig_suffix): """ Construct the complete name of figure file. """ name = key.replace(common, '') if name and (not name.startswith('_')): name = '_' + name fig_name = fig_name + name + fig_suffix return op.join(output_dir, fig_name) class AcousticBandGapsApp(HomogenizationApp): """ Application for computing acoustic band gaps. """ @staticmethod def process_options(options): """ Application options setup. Sets default values for missing non-compulsory options. """ get = options.get default_plot_options = {'show' : True,'legend' : False,} aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : r'min eig($M^*$)', 'eig_mid' : r'mid eig($M^*$)', 'eig_max' : r'max eig($M^*$)', 'x_axis' : r'$\sqrt{\lambda}$, $\omega$', 'y_axis' : r'eigenvalues of mass matrix $M^*$', } plot_labels = try_set_defaults(options, 'plot_labels', aux, recur=True) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : r'$\kappa$(min)', 'eig_mid' : r'$\kappa$(mid)', 'eig_max' : r'$\kappa$(max)', 'x_axis' : r'$\sqrt{\lambda}$, $\omega$', 'y_axis' : 'polarization angles', } plot_labels_angle = try_set_defaults(options, 'plot_labels_angle', aux) aux = { 'resonance' : 'eigenfrequencies', 'masked' : 'masked eigenfrequencies', 'eig_min' : r'wave number (min)', 'eig_mid' : r'wave number (mid)', 'eig_max' : r'wave number (max)', 'x_axis' : r'$\sqrt{\lambda}$, $\omega$', 'y_axis' : 'wave numbers', } plot_labels_wave = try_set_defaults(options, 'plot_labels_wave', aux) plot_rsc = { 'resonance' : {'linewidth' : 0.5, 'color' : 'r', 'linestyle' : '-'}, 'masked' : {'linewidth' : 0.5, 'color' : 'r', 'linestyle' : ':'}, 'x_axis' : {'linewidth' : 0.5, 'color' : 'k', 'linestyle' : '--'}, 'eig_min' : {'linewidth' : 2.0, 'color' : (0.0, 0.0, 1.0), 'linestyle' : ':' }, 'eig_mid' : {'linewidth' : 2.0, 'color' : (0.0, 0.0, 0.8), 'linestyle' : '--' }, 'eig_max' : {'linewidth' : 2.0, 'color' : (0.0, 0.0, 0.6), 'linestyle' : '-' }, 'strong_gap' : {'linewidth' : 0, 'facecolor' : (0.2, 0.4, 0.2)}, 'weak_gap' : {'linewidth' : 0, 'facecolor' : (0.6, 0.8, 0.6)}, 'propagation' : {'linewidth' : 0, 'facecolor' : (1, 1, 1)}, 'params' : {'axes.labelsize': 'x-large', 'font.size': 14, 'legend.fontsize': 'large', 'legend.loc': 'best', 'xtick.labelsize': 'large', 'ytick.labelsize': 'large', 'text.usetex': True}, } plot_rsc = try_set_defaults(options, 'plot_rsc', plot_rsc) return Struct(incident_wave_dir=get('incident_wave_dir', None), plot_transform=get('plot_transform', None), plot_transform_wave=get('plot_transform_wave', None), plot_transform_angle=get('plot_transform_angle', None), plot_options=get('plot_options', default_plot_options), fig_name=get('fig_name', None), fig_name_wave=get('fig_name_wave', None), fig_name_angle=get('fig_name_angle', None), fig_suffix=get('fig_suffix', '.pdf'), plot_labels=plot_labels, plot_labels_angle=plot_labels_angle, plot_labels_wave=plot_labels_wave, plot_rsc=plot_rsc) @staticmethod def process_options_pv(options): """ Application options setup for phase velocity computation. Sets default values for missing non-compulsory options. """ get = options.get incident_wave_dir=get('incident_wave_dir', None, 'missing "incident_wave_dir" in options!') return Struct(incident_wave_dir=incident_wave_dir) def __init__(self, conf, options, output_prefix, **kwargs): PDESolverApp.__init__(self, conf, options, output_prefix, init_equations=False) self.setup_options() if conf._filename: output_dir = self.problem.output_dir shutil.copyfile(conf._filename, op.join(output_dir, op.basename(conf._filename))) def setup_options(self): HomogenizationApp.setup_options(self) if self.options.phase_velocity: process_options = AcousticBandGapsApp.process_options_pv else: process_options = AcousticBandGapsApp.process_options self.app_options += process_options(self.conf.options) def call(self): """ Construct and call the homogenization engine accoring to options. """ options = self.options opts = self.app_options conf = self.problem.conf coefs_name = opts.coefs coef_info = conf.get(opts.coefs, None, 'missing "%s" in problem description!' % opts.coefs) if options.detect_band_gaps: # Compute band gaps coefficients and data. keys = [key for key in coef_info if key.startswith('band_gaps')] elif options.analyze_dispersion or options.phase_velocity: # Insert incident wave direction to coefficients that need it. for key, val in six.iteritems(coef_info): coef_opts = val.get('options', None) if coef_opts is None: continue if (('incident_wave_dir' in coef_opts) and (coef_opts['incident_wave_dir'] is None)): coef_opts['incident_wave_dir'] = opts.incident_wave_dir if options.analyze_dispersion: # Compute dispersion coefficients and data. keys = [key for key in coef_info if key.startswith('dispersion') or key.startswith('polarization_angles')] else: # Compute phase velocity and its requirements. keys = [key for key in coef_info if key.startswith('phase_velocity')] else: # Compute only the eigenvalue problems. names = [req for req in conf.get(opts.requirements, ['']) if req.startswith('evp')] coefs = {'dummy' : {'requires' : names, 'class' : CoefDummy,}} conf.coefs_dummy = coefs coefs_name = 'coefs_dummy' keys = ['dummy'] he_options = Struct(coefs=coefs_name, requirements=opts.requirements, compute_only=keys, post_process_hook=self.post_process_hook, multiprocessing=False) volumes = {} if hasattr(opts, 'volumes') and (opts.volumes is not None): volumes.update(opts.volumes) elif hasattr(opts, 'volume') and (opts.volume is not None): volumes['total'] = opts.volume else: volumes['total'] = 1.0 he = HomogenizationEngine(self.problem, options, app_options=he_options, volumes=volumes) coefs = he() coefs = Coefficients(**coefs.to_dict()) coefs_filename = op.join(opts.output_dir, opts.coefs_filename) coefs.to_file_txt(coefs_filename + '.txt', opts.tex_names, opts.float_format) bg_keys = [key for key in coefs.to_dict() if key.startswith('band_gaps') or key.startswith('dispersion')] for ii, key in enumerate(bg_keys): bg = coefs.get(key) log_save_name = bg.get('log_save_name', None) if log_save_name is not None: filename = op.join(self.problem.output_dir, log_save_name) bg.save_log(filename, opts.float_format, bg) raw_log_save_name = bg.get('raw_log_save_name', None) if raw_log_save_name is not None: filename = op.join(self.problem.output_dir, raw_log_save_name) save_raw_bg_logs(filename, bg.logs) if options.plot: if options.detect_band_gaps: self.plot_band_gaps(coefs) elif options.analyze_dispersion: self.plot_dispersion(coefs) elif options.phase_velocity: keys = [key for key in coefs.to_dict() if key.startswith('phase_velocity')] for key in keys: output('%s:' % key, coefs.get(key)) return coefs def plot_band_gaps(self, coefs): opts = self.app_options bg_keys = [key for key in coefs.to_dict() if key.startswith('band_gaps')] plot_opts = opts.plot_options plot_rsc = opts.plot_rsc
plt.rcParams.update(plot_rsc['params'])
sfepy.base.plotutils.plt.rcParams.update